在一个模型中使用多个模型并将一个用户输入字段保存到两个模型
Use multiple model in one modelform and save one user input field to two model
所以,我被困在这两天了,我曾经有一个视图和模板结合了 django 内置用户模型和我自己的 Maker 模型,如下所示
Forms.py
来自 .models import Maker,Major,User
class NewMakerForm(forms.ModelForm):
password = forms.CharField()
username = forms.CharField()
def __init__(self ,*args, **kwargs):
super(NewMakerForm,self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['email'].required = True
class Meta:
model = User
fields = ('username','password','first_name','last_name','email')
class MakerProfileForm(forms.ModelForm):
#--------------------------------------error part------------------------
other_major = forms.CharField()
#--------------------------------------error part------------------------
class Meta:
model = Maker
fields = ('maker_major','other_major','maker_related_category','profile_pic',)
#--------------------------------------error part------------------------
def clean(self, *args, **kwargs):
super(MakerProfileForm,self).clean()
Major.objects.get_or_create(
major_name=self.cleaned_data.get('other_major')
)
self.cleaned_data['other_major']=Major.major_name
#--------------------------------------error part------------------------
一开始它工作正常,直到我添加一个新字段并尝试让用户输入一些 "other_major" 并将输入保存到模型 Major 的 major_name 行
Views.py
def NewMakerView(request):
registered = False
if request.method == 'POST':
user_form = NewMakerForm(data=request.POST)
profile_form = MakerProfileForm(data=request.POST,)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = NewMakerForm()
profile_form = MakerProfileForm()
return render(request,
'boodemo/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
我没有更改 Views.py 中的任何代码(或者我应该?)
这是错误代码,我不明白为什么 Major' 没有属性 'major_name
Traceback:
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/virtualproject/venv/bootsdemo/boodemo/views.py" in NewMakerView
114. if user_form.is_valid() and profile_form.is_valid():
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
162. return self.is_bound and not bool(self.errors)
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in errors
154. self.full_clean()
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
354. self._clean_form()
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in _clean_form
378. cleaned_data = self.clean()
File "/home/ubuntu/virtualproject/venv/bootsdemo/boodemo/forms.py" in clean
79. self.cleaned_data['other_major']=Major.major_name
Exception Type: AttributeError at /demo/newmaker/
Exception Value: type object 'Major' has no attribute 'major_name'
专业是 class。 class 本身没有那个属性,只有实例有。出于某种原因,您正在获取或创建一个实例,忽略它,然后尝试使用不存在的 class 属性。相反,您实际上应该保留并使用您获得的实例。
major_instance, created = Major.objects.get_or_create(
major_name=self.cleaned_data.get('other_major')
)
self.cleaned_data['other_major'] = major_instance.major_name
所以,我终于弄清楚了如何以模型形式使用多个模型,以及如何保存它
英语不是我的母语所以我让代码说话
class Major(models.Model):
major_name = models.CharField(max_length=200)
def __unicode__(self):
return self.major_name
class Maker(models.Model):
...
maker_major = models.ManyToManyField(Major,blank=True)
...
def __unicode__(self):
return self.user.username
我想在这里做的是让用户(Maker)选择专业(major_name)。
class MakerProfileForm(forms.ModelForm):
other_major = forms.CharField()
class Meta:
model = Maker
fields = ('maker_major','other_major',...)
def clean(self, *args, **kwargs):
super(MakerProfileForm,self).clean()
major, _ = Major.objects.get_or_create(
major_name=self.cleaned_data.get('other_major')
)
self.cleaned_data['other_major'] = major.major_name
我使用 ModelForm
和 model=Maker
,但我想 让用户不仅可以选择而且可以输入文本以将 other_major
添加到 [=16] =]
if request.method == 'POST':
profile_form = MakerProfileForm(data=request.POST,)
if profile_form.is_valid():
profile = profile_form.save(commit=False)
profile.save()
profile_form.save_m2m()
major = Major.objects.get(major_name=profile_form.cleaned_data['other_major'])
profile.maker_major.add(major)
最后保存maker_major
用户的选择,添加other_major
是用户输入的文本到MakerProfileForm
所以,我被困在这两天了,我曾经有一个视图和模板结合了 django 内置用户模型和我自己的 Maker 模型,如下所示
Forms.py 来自 .models import Maker,Major,User
class NewMakerForm(forms.ModelForm):
password = forms.CharField()
username = forms.CharField()
def __init__(self ,*args, **kwargs):
super(NewMakerForm,self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['email'].required = True
class Meta:
model = User
fields = ('username','password','first_name','last_name','email')
class MakerProfileForm(forms.ModelForm):
#--------------------------------------error part------------------------
other_major = forms.CharField()
#--------------------------------------error part------------------------
class Meta:
model = Maker
fields = ('maker_major','other_major','maker_related_category','profile_pic',)
#--------------------------------------error part------------------------
def clean(self, *args, **kwargs):
super(MakerProfileForm,self).clean()
Major.objects.get_or_create(
major_name=self.cleaned_data.get('other_major')
)
self.cleaned_data['other_major']=Major.major_name
#--------------------------------------error part------------------------
一开始它工作正常,直到我添加一个新字段并尝试让用户输入一些 "other_major" 并将输入保存到模型 Major 的 major_name 行
Views.py
def NewMakerView(request):
registered = False
if request.method == 'POST':
user_form = NewMakerForm(data=request.POST)
profile_form = MakerProfileForm(data=request.POST,)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = NewMakerForm()
profile_form = MakerProfileForm()
return render(request,
'boodemo/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
我没有更改 Views.py 中的任何代码(或者我应该?)
这是错误代码,我不明白为什么 Major' 没有属性 'major_name
Traceback:
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/virtualproject/venv/bootsdemo/boodemo/views.py" in NewMakerView
114. if user_form.is_valid() and profile_form.is_valid():
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
162. return self.is_bound and not bool(self.errors)
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in errors
154. self.full_clean()
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
354. self._clean_form()
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/forms/forms.py" in _clean_form
378. cleaned_data = self.clean()
File "/home/ubuntu/virtualproject/venv/bootsdemo/boodemo/forms.py" in clean
79. self.cleaned_data['other_major']=Major.major_name
Exception Type: AttributeError at /demo/newmaker/
Exception Value: type object 'Major' has no attribute 'major_name'
专业是 class。 class 本身没有那个属性,只有实例有。出于某种原因,您正在获取或创建一个实例,忽略它,然后尝试使用不存在的 class 属性。相反,您实际上应该保留并使用您获得的实例。
major_instance, created = Major.objects.get_or_create(
major_name=self.cleaned_data.get('other_major')
)
self.cleaned_data['other_major'] = major_instance.major_name
所以,我终于弄清楚了如何以模型形式使用多个模型,以及如何保存它 英语不是我的母语所以我让代码说话
class Major(models.Model):
major_name = models.CharField(max_length=200)
def __unicode__(self):
return self.major_name
class Maker(models.Model):
...
maker_major = models.ManyToManyField(Major,blank=True)
...
def __unicode__(self):
return self.user.username
我想在这里做的是让用户(Maker)选择专业(major_name)。
class MakerProfileForm(forms.ModelForm):
other_major = forms.CharField()
class Meta:
model = Maker
fields = ('maker_major','other_major',...)
def clean(self, *args, **kwargs):
super(MakerProfileForm,self).clean()
major, _ = Major.objects.get_or_create(
major_name=self.cleaned_data.get('other_major')
)
self.cleaned_data['other_major'] = major.major_name
我使用 ModelForm
和 model=Maker
,但我想 让用户不仅可以选择而且可以输入文本以将 other_major
添加到 [=16] =]
if request.method == 'POST':
profile_form = MakerProfileForm(data=request.POST,)
if profile_form.is_valid():
profile = profile_form.save(commit=False)
profile.save()
profile_form.save_m2m()
major = Major.objects.get(major_name=profile_form.cleaned_data['other_major'])
profile.maker_major.add(major)
最后保存maker_major
用户的选择,添加other_major
是用户输入的文本到MakerProfileForm