0

model

class Person(models.Model):
    first_name = models.CharField(blank=False,max_length=256,default='')
    last_name = models.CharField(blank=False,max_length=256,default='')
    plan = models.CharField(blank=False,max_length=256,default='')   
    plan_price = models.CharField(blank=False,max_length=256,default='')

Views.py

if request.method == 'POST':

    if form.is_valid():
        form.save(commit=True)
        return index(request)

In my modelForm I accept 3 values from the user: first_name, last_name, and plan. I dont have any problem with posting to the database from the form, what i am trying to find out is how I can say something like this

if plan = 'plan1':
    #set plan_price to '$399'
else
    #set plan_price to '$699'

#then post first_name, last_name, plan, plan_price to database
1
  • Do you have a fix mapping from plans to prices? Commented Nov 18, 2017 at 18:59

2 Answers 2

1

You can try the following:

if form.is_valid():
    person = form.save(commit=False)
    plans = {
        'plan1': 399,
        'plan2': 699,
        # ...
    }
    person.plan_price = plans.get(person.plan, some_default)
    person.save()
    return index(request)  
    # you might consider a redirect instead so as not to have the same content on various urls

If the plan price always should match the plan you can also override the model's save method and leave the view as you had it:

class Person(models.Model):
    # ...
    def save(self, *args, **kwargs):
        self.plan_price = some_logic(self.plan)
        super(Person, self).save(*args, **kwargs)

But then, you could replace that field by a property alltogether as it seems redundant. If plans, for instance, change prices, I would consider a Plan model with a name and price field.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly thank you. I actually put both answer together to get the final working code. Much appreciated!
1

in your createview you can use this function and write your code there

    def form_valid(self, form):
        if self.object.plan = 'plan1':
            form.instance.price = 399
        else:
            [...]
        return super(your_class_name, self).form_valid(form)

you can access the created object fields by self.object.filed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.