开发者

How to do form validation/processing in Django?

This is my 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})

This is my 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)
    r开发者_StackOverflowadio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES2)

How to do validate the form, as in I want to check if the user is there in the database, and retrieve its primary key. I do understand that Q from django.db has to be used, but there is a bit of lack of documentation on this.


If I've understood you correctly you want to check if user exist in database?

If so, why didn't you set user field in PermForm (forms.py) as ForeignKey(User)?

And okay, get User you can by this way:

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

user's primary key will be user.id

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜