为什么不验证表格?

时间:2014-05-09 09:10:32

标签: python django

请帮助解决问题。

我制作了一个表格,其中有一个字段选择:

class DrumDataForm(forms.ModelForm):            
    class Meta:
        model = UserProfile
        fields = (
            'drum_photo', 
            'teacher', 
            'drummers',
        )

models.py:

class UserProfile(User):
    CHOICES_teacher = (
        ('0', '0', ),
        ('1', '1',),
        ('2', '2', ),
    )       

    drum_photo = models.ImageField(
        'ph',
        upload_to='userprofile/drum_photo/', 
        blank=True,
        null=True,
    )
    teacher = models.CharField(
        'te',
        max_length=30, 
        choices=CHOICES_teacher,        
        blank=True,
        null=True,
    )   
    drummers = models.CharField(
        'dr',
        max_length=300, 
        blank=True,
        null=True,
    )   

views.py:

@login_required
def drum_data_page(request):            
    if request.method == 'POST':
        form = DrumDataForm(request.POST, request.FILES)
        if form.is_valid():         
            entry_user = User.objects.get(username__exact=request.user.username)
            entry_user_profile = UserProfile.objects.get(user_ptr_id__exact=entry_user.id)
            entry_user_profile.drum_photo = form.cleaned_data.get('drum_photo')
            entry_user_profile.teacher = form.cleaned_data.get('teacher')
            entry_user_profile.drummers = form.cleaned_data.get('drummers').strip()
            entry_user_profile.save()

            return HttpResponseRedirect('/userprofile/drum_data_page_changed/')
    else:
        entry_user = User.objects.get(username__exact=request.user.username)
        entry_user_profile = UserProfile.objects.get(user_ptr_id__exact=entry_user.id)
        arg = {
            'drum_photo': entry_user_profile.drum_photo,
            'teacher': entry_user_profile.teacher,
            'drummers': entry_user_profile.drummers,
        }

        form = DrumDataForm(arg)        

    t = loader.get_template('drum_data_page.html')
    c = RequestContext(request, {
        'form': form,
        'drum_photo': arg['drum_photo'],
    }, [custom_proc])
    return HttpResponse(t.render(c)) 

如果用户在"中选择" (0,1或2),然后提交表格。除非用户在"中选择" (无),中断的形状并显示以下错误消息:

UnboundLocalError at /userprofile/drum_data_page/
local variable 'arg' referenced before assignment
Request Method: POST
Request URL:    http://127.0.0.1:8000/userprofile/drum_data_page/
Django Version: 1.6.2
Exception Type: UnboundLocalError
Exception Value:    
local variable 'arg' referenced before assignment

在任何情况下,我都需要这种形式

2 个答案:

答案 0 :(得分:2)

您将初始数据传递到GET块中错误位置的表单:它被解释为数据。你应该这样做:

form = DrumDataForm(initial=arg)

除非你不应该尝试使用ModelForm传递初始数据,否则你应该传递你想要编辑的实际实例:

form = DrumDataForm(instance=entry_user_profile)

您的代码还有其他一些问题。首先,您无需通过request.user.username查询用户:request.user 相关的用户对象。

其次,当你来保存时,你应该再次使用instance参数并直接保存ModelForm,而不是单独设置值:

if request.method == 'POST':
    form = DrumDataForm(request.POST, request.FILES, instance=my_user)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(...)

最后,您不应该使用UserProfile模型扩展User,但是您应该扩展AbstractUser并将AUTH_MODEL设置设置为指向UserProfile:然后request.user将是您的自定义用户模型的实例。

答案 1 :(得分:1)

如果arg与“POST”不同,则初始化request.method变量。为避免此错误,请在方法顶部初始化arg变量。

@login_required
def drum_data_page(request):
    args = {}

    entry_user_profile = UserProfile.objects.get(user_ptr_id__exact=request.user.id)            
    if request.method == 'POST':
        form = DrumDataForm(request.POST, request.FILES)
        if form.is_valid():         

            form.save()

            return HttpResponseRedirect('/userprofile/drum_data_page_changed/')
    else:

        form = DrumDataForm(instance=entry_user_profile)        

    t = loader.get_template('drum_data_page.html')
    c = RequestContext(request, {
            'form': form,
            'drum_photo': entry_user_profile.drum_photo,,
            },
            [custom_proc])
    return HttpResponse(t.render(c)) 

一般来说,@ daniel-roseman解释得非常好。