1

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.

icebox3d
  • 449
  • 7
  • 17

2 Answers2

1

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.

  • Hey Rickard, That worked perfectly, it is now saving correctly. However do you know of a way to use a number submitted in a form. Say for example the number 4 is submitted in the forum so I have submithours = int(pirephours.totalhours) as the code but how would I add the submitted number to pirephours.totalhours so it can be saved to the db – icebox3d Dec 10 '12 at 19:30
  • This box is to small to give a good answer to that and to keep it clean I rather answer that question in a new thread. :) – Rickard Zachrisson Dec 11 '12 at 08:12
  • Hi Rickard, well the new post is 'http://stackoverflow.com/questions/13821173/using-submitted-information-in-a-view-django' if you would like to answer, feel free :) – icebox3d Dec 11 '12 at 13:12
0

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)

Community
  • 1
  • 1
dani herrera
  • 48,760
  • 8
  • 117
  • 177