Django:来自视图的初始值

时间:2011-06-28 22:27:39

标签: django django-forms django-views

如何从视图中获取初始值?我应该在表格中使用什么参数?

views.py

def cadastro_usuario(request):
    if request.method == 'POST':
        form = cadastroForm(request.POST)
        if form.is_valid():            
            new_user = form.save()
            return HttpResponseRedirect("/")
    else:
        form = cadastroForm()
    return render_to_response("registration/registration.html", {
        'form': form, 'tipo_cadastro': 'PF',})

forms.py

class cadastroForm(UserCreationForm):

    tipo_cadastro = forms.CharField(XXXXX)

3 个答案:

答案 0 :(得分:6)

好的,根据你对@J的回应。 Lnadgrave,我们假设您在UserProfile模型上有一个“user_type”属性,可以设置为“普通”用户或“公司”用户......

#your_app.constants
NORMAL_USER = 0
COMPANY_USER = 1

USER_TYPE_CHOICES = (
    (NORMAL_USER, "Normal"),
    (COMPANY_USER, "Company"),
)


#your_app.models
from django.contrib.auth.models import User
from your_app.constants import USER_TYPE_CHOICES

class UserProfile(models.Model):
    user = models.OneToOne(User)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)


#your_app.forms
from your_app.models import UserProfile

class UserProfileForm(forms.ModelForm):
    class Meta():
        model = UserProfile

    user_type = forms.IntegerField(widget=forms.HiddenInput)


#your_app.views
form django.http import HttpResponseRedirect
from django.shortcuts import render
from your_app.constants import NORMAL_USER, COMPANY_USER
from your_app.forms import UserProfileForm
from your_app.models import UserProfile

def normal_user_registration(request):
    user_profile_form = UserProfileForm(request.POST or None,
        initial={'user_type' : NORMAL_USER})
    if request.method == 'POST':
        user_profile_form.save()
        return HttpResponseRedirect('/')
    return render(request, 'registration/registration.html',
        {'user_profile_form' : user_profile_form})

def company_user_registration(request):
    user_profile_form = UserProfileForm(request.POST or None,
        initial={'user_type' : COMPANY_USER})
    if request.method == 'POST':
        user_profile_form.save()
        return HttpResponseRedirect('/')
    return render(request, 'registration/registration.html',
        {'user_profile_form' : user_profile_form})

这是一个非常冗长的方法来解决这个问题,但我认为如何将初始值传递给表单非常明显。希望能帮到你。

答案 1 :(得分:1)

我认为您不应该初始化视图中的任何数据,因为它更适合处理请求的数据,例如在普通请求上操作或设置查询。我认为你正在寻找这个tidbit on initializing values for a form,因为这是我在审核你给我们的示例代码后的假设。如果我错了,请纠正我。

答案 2 :(得分:1)

不确定您需要什么,但在我看来,查看Dynamic initial values 可能有用。您可以在视图中为表单定义初始值,如下所示:

f = cadastroForm(initial={'tipo_cadastro': 'Initial Value!'})