Hiding field in dhangoforms which are generated from a model and saving it in the database
1] I have the following model:
class UserReportedData(db.Model):
#country selected by the user, this will also populate the drop down list on the html page
country = db.StringProperty(default='Afghanistan',choices=['Afghanistan'])
#city selected by the user
city = db.StringProperty()
user_reported_boolean = db.BooleanProperty() # value that needs to be hidden from the display
date = db.DateTimeProperty(auto_now_add=True)
class UserReportedDataForm(djangoforms.ModelForm):
class Meta:
model = UserReportedData
2] The html code which will decide the boolean "user_reported_boolean" looks like follows
'开发者_开发百科<input type="submit" name="report_up" value= "Report Up">'
'<input type="submit" name="report_down" value= "Report Down">'
3] The idea is if "report_up" is pressed, the boolean value "user_reported_boolean" should be saved as true
4] The code that gets the call, when the user submits looks like follows
class UserReporting(webapp.RequestHandler):
def post(self):
#get the data that the user put in the django form UserReportForm
data = UserReportedDataForm(data=self.request.POST)
#need to find whether user hit the button with the name "report_up" or "report_down"
# this is not working either
if 'report_up' in self.request.POST:
data.user_reported_boolean = True
elif 'report_down' in self.request.POST:
data.user_reported_boolean = False
if data.is_valid():
# Save the data, and redirect to the view page
entity = data.save(commit=False)
entity.put()
self.redirect('/')
Questions:
1] How do i hide the field "user_reported_boolean" from being displayed on the html form
2] How do i save this field "user_reported_boolean" in the database
1: Exclude the field from your modelform.
class MyModelForm(ModelForm):
class Meta:
model = Foo
exclude = ('myfield',)
2: In the unsaved model instance you have via commit=False
entity = data.save(commit=False)
entity.user_reported_boolean = True # False, whatever.
entity.save()
精彩评论