Mathias Damgaard
Mathias Damgaard

Reputation: 27

Dynamic Assignment of a value to Model object, dependent on user inputs in form in python

Im totally new in python and Django development, and is making a test run, where I have to make a Model object dynamic, and depending on a form input.

I want the T8 object to have the value of "hi", if the C8 object is = 1.

I have the following Models and views code:

    Models:
Class Patient
C8 = models.CharField(null=True, max_length=200)
T8 = models.CharField(null=True, max_length=200)

Views:

def reg(request):
    form = RegForm()
    if request.method == 'POST':
        form = RegForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect (reverse('behandlingsplan'))

if Patient.objects.get(Patient.C8) == 1:
    set (Patient.objects.get(Patient.T8)) = "Hi"
        print (Patient.T8)


context = {'ptid':ptid, 'form':form}
return render(request,'DentHelp/reg.html', context)

Any help?

Upvotes: 1

Views: 29

Answers (1)

Mikhail Tochenov
Mikhail Tochenov

Reputation: 119

You could use choices in your model.py or in your form.py

models.py:

class Patient(models.Model):
    CHOICES = (
        (1, 'Hi'),
        (2, 'Your_value')
    )

    t8 = models.PositiveSmallIntegerField(choices=CHOICES)
    ...

When user enter 1 it input Hi in DB. And you could remove if from your view. More information you could find in this article or in gjango documentatiin.

Upvotes: 1

Related Questions