实例的表单未保存

时间:2010-07-02 21:41:28

标签: django forms django-models django-forms validation

我正在尝试创建表单,用于添加新朋友/更新现有朋友。我的第一个解决方案使用ModelForm,但来自更新表单的数据未保存。另外一个问题是我的模型有CharFields('code','pid'),我需要通过我的表单验证regex。如果我在Meta中排除这些字段,并将它们添加到FriendForm,那么在加载表单时我没有数据。

def add_friend(request):
    userprofile = UserProfile.objects.get(user=request.user) 

    if request.method == 'POST':
        form = FriendForm(request.POST, request.FILES,)
        if form.is_valid():
            form.save()            
            next = reverse('user_profile',)
            return HttpResponseRedirect(next)
    else:
        form = FriendForm()
    return render_to_response('user/data_operations/add_friend.html', {
            'form':form, 'user':request.user,
            }, context_instance=RequestContext(request))

def edit_friend(request, id):
    userprofile = UserProfile.objects.get(user=request.user)
    friend = get_object_or_404(Friend, id=id)
    if friend.friend_of.id!=userprofile.id:
        raise Http404 
    if request.method == 'POST':
        form = FriendForm(request.POST, request.FILES, instance=friend)
        if form.is_valid(): 
            form.save()           
        return HttpResponseRedirect(reverse('user_profile',))
    else:
        form = FriendForm(instance=friend)
    return render_to_response('user/data_operations/edit_friend.html', {
            'form': form, 'user': request.user, 'friend': friend,
            }, context_instance=RequestContext(request))

class FriendForm(forms.ModelForm):      
    class Meta:
        model = Friend
        exclude = ( 'friend_of',)

第二个解决方案使用forms.Form。这里的问题是我无法将实例发送到我的表单,因此我无法获取要编辑的数据。因此,我无法检查我的保存方法是否有效以及此解决方案是否更好。

def add_friend(request):
    userprofile = UserProfile.objects.get(user=request.user)
    count = 0 

    if request.method == 'POST':
        form = FriendForm(request.POST, request.FILES,)
        if form.is_valid():
            form.save(user=userprofile)            
            next = reverse('user_profile',)
            return HttpResponseRedirect(next)
    else:
        form = FriendForm()
    return render_to_response('user/data_operations/add_friend.html', {
            'form':form, 'user':request.user,
            }, context_instance=RequestContext(request))

def edit_friend(request, id):
    userprofile = UserProfile.objects.get(user=request.user)
    friend = get_object_or_404(Friend, id=id)
    if friend.friend_of.id!=userprofile.id:
        raise Http404 
    if request.method == 'POST':
        form = FriendForm(request.POST, request.FILES, instance=friend)
        if form.is_valid(): 
            form.save(user=userprofile)           
        return HttpResponseRedirect(reverse('user_profile',))
    else:
        form = FriendForm()
    return render_to_response('user/data_operations/edit_friend.html', {
            'form': form, 'user': request.user, 'friend': friend,
            }, context_instance=RequestContext(request))

class FriendForm(forms.Form):
    first_name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), label="First name")
    last_name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), label="Last name")
    pid = forms.RegexField(regex=r'^\d{11}', max_length=11 ,widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)))
    image = forms.ImageField(label="Image", required=False)
    street = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), label="Street")
    number = forms.CharField(widget=forms.TextInput, label="House/flat number")
    code = forms.RegexField(regex=r'^\d{2}[-]\d{3}', max_length=6, widget=forms.TextInput(attrs=attrs_dict), label="Postal code")
    city = forms.CharField(widget=forms.TextInput, label="City")

    def save(self, user):
        if self.is_valid():
            from accounts.models import Friend
            new_friend = Friend(**self.cleaned_data)
            new_friend.friend_of = user
            new_friend.save()
            return new_friend

以下是我使用的模型:

class UserProfile(models.Model):
    (...)
    user = models.ForeignKey(User, unique=True, related_name='profile')       

class Friend(models.Model):
    (...)
    friend_of = models.ForeignKey(UserProfile, related_name='friend_of')

我怎样才能使这个工作?我的编辑用户表单(使用模型方法)没有任何问题:/

1 个答案:

答案 0 :(得分:0)

muntu - 坚持使用选项1,即使它需要一点点工作 - 这是一个更健全的方法,并提供更多的灵活性。我认为问题在于friend_of上的Friend字段 - 您已将其设为必填字段,因此如果没有该字段,则无法保存Friend,但您也不能t在代码中为它提供一个值。 (参见django online documentation中的咨询说明。)

使用这些指南,请在验证/保存部分中尝试此代码:

if form.is_valid():
    friend = form.save(commit=False)
    friend.friend_of = userprofile # (or whatever the user variable is)
    friend.save()

请评论这是否有效或出现了什么问题。