在一个模型中使用多个模型,并将一个用户输入字段保存到两个模型

时间:2015-01-10 10:00:57

标签: django django-models django-forms

所以,我被困在这两天了,我曾经有一个视图和模板,结合了django内置用户模型和我自己的Maker模型,如下所示

Forms.py     来自.models导入Maker,Major,用户

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中的任何代码(或shoudl I?)

这是错误代码,我不明白为什么 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'

2 个答案:

答案 0 :(得分:0)

专业是一门课。类本身没有该属性,只有实例才有。出于某种原因,您正在获取或创建实例,忽略它,然后尝试使用不存在的类属性。相反,你应该保留并使用你得到的实例。

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

答案 1 :(得分:0)

所以,最后我弄清楚如何在模型中使用多个模型,以及如何保存它 英语不是我母语,所以我会让代码说话

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

我想在这里做的是让用户(制作者)选择一个专业(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

我使用ModelFormmodel=Maker,但我希望让用户不仅可以选择,还可以输入文字以将other_major添加到Major.major_name

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