On Thu, Feb 24, 2011 at 2:17 PM, galago <prog...@gmail.com> wrote: > Now I have some strange thing. I display my form, send post and try to save > it. But it doesn't save:/ > Here's my code: > model: > class UserProvince(models.Model): > user = models.ForeignKey(User) > province = models.ForeignKey(Province) > class Meta: > unique_together = (('user', 'province'), ) > def __unicode__(self): > return self.user.username + '/' + self.province.name > form: > class ProvinceForm(ModelForm): > def __init__(self, *args, **kwargs): > super(ProvinceForm, self).__init__(*args, **kwargs) > user_provinces = > UserProvince.objects.select_related().filter(user__exact=self.instance.id).values_list('province') > self.fields['province'].queryset = > Province.objects.exclude(id__in=user_provinces).only('id', 'name') > province = forms.ModelChoiceField(queryset=None, empty_label=None) > range_type = forms.CharField(initial='province', > widget=forms.HiddenInput()) > class Meta: > model = UserProvince > fields = ('province',) > view: > if request.POST: > form = ProvinceForm(request.POST, instance=request.user) > if form.is_valid(): > obj = form.save(commit=False) > obj.user = request.user > obj.save() > form is valid, but save method makes no effect :/ >
Your form is a ModelForm for a UserProvince model, and you are passing in an django.contrib.auth.User instance as the instance. This is wrong! If you are editing an existing UserProvince instance, then pass that object to the form as the instance. If you are creating a new UserProvince instance, then do not pass in instance. If you want your form to automatically associate the user with the instance, then that user should be passed to the form's constructor, and override save() to associate it with the instance, eg: class FooForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(FooForm, self).__init__(*args, **kwargs) def save(commit=False): foo = super(FooForm, self).save(commit=False) if not foo.user: foo.user = self.user if commit: foo.save() return foo Cheers Tom -- 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.