just tried it out. worked perfectly. thanks! On Tue, Jun 16, 2009 at 3:18 PM, Rochak Neupane <kah...@gmail.com> wrote:
> ohh, thanks, Daniel! I like your way. and i don't even my to expose the > user_id in a form.I'll try that. > > > On Mon, Jun 15, 2009 at 10:55 PM, Daniel Roseman <dan...@roseman.org.uk>wrote: > >> >> On Jun 16, 1:12 am, k-dj <kah...@gmail.com> wrote: >> > I'm just starting to use django and have run into a problem I have not >> > been able to solve. >> > >> > I have a model Item which stores, among other things, user_id. >> > Then I have a ModelForm. I want user_id to be a hidden field. After >> > searching around the web, I found out how to create a hidden field. >> > The template is rendered as I like it. >> > user_id is a hidden field with a value of 1. The problem is when I >> > submit the form, I get IntegrityError. "Column 'user_id' cannot be >> > null". >> > >> > but from the debug message I get back I can see that POST has all 3 >> > things I need. So maybe when a new form is created there is problem. >> > >> > views.py >> > @login_required >> > def newItem(request): >> > if not request.POST: >> > form = ItemForm() >> > return >> render_to_response('manager/newItem.html',{'form':form}) >> > newForm = ItemForm(request.POST) >> > if newForm.is_valid(): >> > newForm.save() #problem here? >> > return HttpResponsePermanentRedirect('.') >> > >> > models.py >> > class Item(models.Model): >> > user = models.ForeignKey(User) >> > name = models.CharField(max_length=32) >> > description = models.CharField(max_length=128) >> > creation_date = models.DateField(auto_now=True) >> > >> > forms.py >> > class ItemForm(ModelForm): >> > user_id_wid = forms.HiddenInput(attrs={'value': 1}) >> > user_id = forms.IntegerField(widget=user_id_wid,required=False) >> > class Meta: >> > model = Item >> > fields = ['name', 'description'] >> >> >> You can't set 'value' as an argument to attrs. >> >> If you want to preset the value of a field, pass in an 'initial' >> dictionary on form instatiation: >> form = MyForm(initial={'user_id':1}) >> >> However a much better way is not to have the user_id field in the form >> at all, and set the correct value on the object on save. >> >> class itemForm(ModelForm): >> .... >> class Meta: >> model = Item >> exclude = ('user',) >> >> and in the view: >> if newForm.is_valid(): >> item = newForm.save(commit=False) >> item.user_id = 1 >> item.save() >> >> -- >> DR. >> >> >> > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---