Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend user to have many medications

I would like to save many medications to the Profile like so.

models.py

class Profile(AbstractUser):
    

class Medications(models.Model):
    user = models.ForeignKey(Profile,related_name='user',on_delete=models.CASCADE)
    name = models.CharField(default='',max_length=100)
    amount = models.IntegerField()
    per_time = models.IntegerField()
    time_choices = (('other', 'Other'),('Post meal', 'Post meal'),('Breakfast' ,'Breakfast'))
    choice = models.CharField(max_length=10, choices=time_choices,default='others')

forms.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class MedicationForm(forms.ModelForm):
    name = forms.CharField(max_length=100, required=True, help_text='Required.')
    amount = forms.IntegerField( required=True, help_text='Required.')
    class Meta:
        model = Medications
        fields = ('name','amount','per_time','choice')

Now in here I would like to create a Medication with the request user. I used if form.is_valid(): form.save() which just gives IntegrityError at /addMed/
NOT NULL constraint failed: pages_medications.user_id which needs to be from request.user

@login_required
@require_http_methods(["POST"])
def addMed(request):
    print('Adding med')
    print(request.user)
    print(request.POST)
    med = MedicationForm(request.POST or None,)
    print(med)
    return redirect('medications')

Which gives

Adding med
user
<QueryDict: {'csrfmiddlewaretoken': ['-'], 'name': ['Tylenol'], 'amount': ['1'], 'per_time': ['1'], 'choice': ['other'], 'medicationForm': ['Upload']}>

Then list all the medications in here.

views.py

@login_required
def medications(request):
    context={}  
    context['nmenu'] = 'medications'
    context['medicationForm'] = MedicationForm()
    return render(request, 'home.html', context)

>Solution :

You should assign the logged in user to the Medications object:

@login_required
@require_http_methods(['POST'])
def addMed(request):
    med = MedicationForm(request.POST, request.FILES)
    med.instance.user = request.user
    med.save()
    return redirect('medications')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading