icebox3d
icebox3d

Reputation: 459

Django Views and Forms

I am having a problem when using a model to provide the total number of flown hours so the total flown hours can be added to the hours being submitted. Here is a snippet of the code I am using but so far for the past hour or so of working on it, nothing has worked.

Views.py

        pirephours = int(user_profile.totalhours) + 1
        user_profile.update(totalhours=pirephours)

Models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    country = models.CharField("Country", max_length=50)
    totalflights = models.IntegerField("Total Flights", default=0)
    totalhours = models.IntegerField("Total Hours",default=0)
    hub = models.ForeignKey(Airports, default=0)

The + 1 in the view is just for now to add 1 hour to the total hours but I would also like to know if there is a way to use what was submitted in a form instead of a number. The form is just a modelform from the model it self.

Any input would be great.

Upvotes: 1

Views: 570

Answers (2)

dani herrera
dani herrera

Reputation: 51745

My approach for this issues is work with FormSets. I add both forms to a formset list, the model form and a second form with extra fields. Then I send formSet to template. In view:

forM = UserProfileModelFormForm( ...
forE = ExtraUserProfileSingleForm( ...
formSet = [ forM, forE  ]

In template:

<form method="post" action="">
    {% for form in formSet %}
        {{ form }}
    {% endfor %}
</form>

At view side you should send POST request to both forms to check for is_valid() method (an 'and' operator is enough: if forM.is_valid() and forE.is_valid(): ...

Notice than exists a non documented way to add extrafields to a model form: Specifying widget for model form extra field (Django)

Upvotes: 0

Rickard Zachrisson
Rickard Zachrisson

Reputation: 985

I assume user_profile is an object from the ORM, for example UserProfile.objects.get(pk=1).

Django handles insert and update automatically.

What you want to do is to use user_profile.save()

If user_profile contains an id it will try to update the database.

Upvotes: 1

Related Questions