如何在Django中进行表单验证/处理?

时间:2011-06-13 09:11:37

标签: python django validation

这是我的views.py

from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django import forms
from django.core import validators
from django.contrib.auth.models import User
from django.utils import simplejson

def PermLayer(request):
    users = User.objects.all()
    if request.method == 'POST': 
            form = PermForm(request.POST) 
            if form.is_valid():
            user = form.cleaned_data['user']
                    rad1=form.cleaned_data['radio1']
                            rad2=form.cleaned_data['radio2']
                perm = Permission()
            perm.user = user
            perm.table = ContentType.objects.get_for_model(TableToAddPermissionFor)
            perm.permi = rad1 + rad2 
            perm.save()
            return render_to_response('permission.html',{'user':users})
        else:
            form = PermForm()



        return render_to_response('permission.html', {'user':users})

这是我的forms.py

from django import forms
from django.forms.widgets import RadioSelect

class PermForm(forms.Form):
    user = forms.CharField(max_length=100)
    RADIO_CHOICES1 = [['1','Radio 1'],['2','Radio 2']]
    RADIO_CHOICES2 = [['3','Radio 2'],['4','Radio 2']]
    radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES1)
    radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES2)

如何验证表单,就像我想检查用户是否在数据库中,并检索其主键一样。我知道必须使用来自django.db的Q,但是有一些文档缺乏。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你想检查数据库中是否存在用户?

如果是这样,为什么不将PermForm(forms.py)中的用户字段设置为ForeignKey(User)?

好的,通过这种方式让用户可以:

user = User.objects.get(username=form.cleaned_data['user'])

用户的主键为user.id