UserProfile.location“必须是”Location“实例

时间:2012-04-23 13:48:46

标签: django forms foreign-keys instance

我仍然在理解模型表单之间的形式和关系方面遇到一些问题。 我收到一个错误: UserProfile.location“必须是”位置“实例。

我在models.py中将模型中的位置设置为空白= True,null = True且必需= False。 我现在还不知道该怎么做。

我如何解决这个问题?

from django.db import models
from django.contrib.auth.models import User

class Location(models.Model):
    location = models.CharField(max_length=32)
    #county = models.CharField(max_length=32)
    #province = models.CharField(max_length=32)

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, primary_key=True)
    location = models.ForeignKey("Location", null=True, blank=True)

    website = models.URLField("Site", null=True, blank=True)
    accepted_rules = models.BooleanField(default=False)
    accepted_rules_date = models.DateTimeField(auto_now_add=True)

    #points_count = models.IntegerField(default=0, null=True, blank=True)
    #posts_count = models.IntegerField(default=0, null=True, blank=True)
    #comments_count = models.IntegerField(default=0, null=True, blank=True)

形式:

from django import forms
from django.forms import Form
from django.forms.models import ModelForm
from accounts.models import UserProfile, Location
from django.contrib.auth.models import User


class UserCreationForm(forms.Form):

    username = forms.CharField(max_length=32)
    password = forms.CharField(widget=forms.PasswordInput())
    email = forms.EmailField()
    #password_repeat = forms.CharField(widget=forms.PasswordInput(render_value=False))

    def clean_username(self):

        try:
            # iexact = case-insensitive match / important for validation
            User.objects.get(username__iexact=self.cleaned_data['username'])
            print "User does already exist"
    except User.DoesNotExist:
        return self.cleaned_data['username'] 
    else:
        raise forms.ValidationError("User already exists")



def clean_email(self):

    if User.objects.filter(email__iexact=self.cleaned_data['email']):
        print u'Adres email jest już używany.' 
        raise forms.ValidationError('Adres email jest już używany.') 
    else:
        return self.cleaned_data['email']

def save(self):
    user  = User.objects.create(username = self.cleaned_data['username'], email = self.cleaned_data['email'],)

    user.set_password(self.cleaned_data['password'])
    return user


class UserProfileForm(ModelForm):
    website = forms.URLField(label="website", required=False)
    location = forms.ChoiceField(required=False)

    class Meta:
        model = UserProfile
        include = ['website', 'location']
        exclude = ('user', 'type', 'accepted_rules')

浏览

contrib.auth.models import User
from django.template.response import TemplateResponse
from django.views.decorators.csrf import csrf_protect
from django.core.context_processors import csrf
from django.forms.models import inlineformset_factory
from django.http import HttpResponseRedirect

from accounts.forms import UserCreationForm, UserProfileForm



def index(request):
    return TemplateResponse(request, "base.html")

@csrf_protect
def register(request):
    form = UserCreationForm()
    user_profile = UserProfileForm()

    if request.method == "POST":

        form = UserCreationForm(prefix='user', data=request.POST or None)
        user_profile = UserProfileForm(prefix='profile', data= request.POST or None)

        if form.is_valid() and user_profile.is_valid():
            user = form.save()
            profile = user_profile.save(commit=False)
            profile.user = user
            profile.save()


            return HttpResponseRedirect("/")

    return TemplateResponse(request, 'accounts/register.html', {
                             'form':form,
                             'user_profile':user_profile ,
                             }
                            )

1 个答案:

答案 0 :(得分:4)

问题出在这里。

class UserProfileForm(ModelForm):
    website = forms.URLField(label="website", required=False)
    location = forms.ChoiceField(required=False)

    class Meta:
        model = UserProfile
        include = ['website', 'location']
        exclude = ('user', 'type', 'accepted_rules')

ModelForm将为您的表单生成所需的字段。您无需手动定义它们。所以你应该使用这样的东西。

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        include = ['website', 'location']
        exclude = ('user', 'type', 'accepted_rules')

另一件事。没有include选项,我想您想使用fields。但您不必同时使用fieldsexclude,通常需要使用它们。在你的情况下exclude就足够了。最终结果:

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ('user', 'type', 'accepted_rules')