gpt4 book ai didi

Django:来自 View 的初始值

转载 作者:行者123 更新时间:2023-12-01 09:36:37 25 4
gpt4 key购买 nike

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

View .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',})

表格.py
class cadastroForm(UserCreationForm):

tipo_cadastro = forms.CharField(XXXXX)

最佳答案

好的,根据您对@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})

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

关于Django:来自 View 的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6513812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com