【问题标题】:Django having trouble linking a UserProfile to UserDjango 在将 UserProfile 链接到 User 时遇到问题
【发布时间】:2010-02-13 12:57:44
【问题描述】:

所以我想扩展 django auth.User 模型以添加额外的字段。我在这里和那里读过几篇文章,而且差不多了。

我现在只是想制作注册表单。所以新用户可以注册。我可以创建新用户,但是当我将 UserProfile 对象保存到数据库时,它引用失败

Cannot assign "u'clare'": "Customer.user" must be a "User" instance.

其中“clare”是我输入的用户名。此用户是在 Auth.User 中创建的,但未创建 UserProfile,在本例中称为 Customer。所以我认为我在创建对象并使用外键这样做时做错了。反正下面是相关文件。

models.py

from django.db import models
from RadioBusiSite.music.models import PlayList
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django import forms

class Location(models.Model):
    Address = models.CharField(max_length=300)
    PhoneNumber = models.CharField(max_length=15)
    Size = models.IntegerField('Size of Premises')

    def __unicode__(self):
        return self.Address

class Customer(models.Model):
    user = models.ForeignKey(User, unique=True)
    Company = models.CharField(max_length=200)
    ContactPerson = models.CharField('Contact Person', max_length=200)
    email = models.CharField(max_length=200)
    ABN = models.CharField(max_length=50)
    Location = models.ForeignKey(Location)
    Playlist = models.ManyToManyField(PlayList)

    def __unicode__(self):
        return self.Company

forms.py

from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django import forms
from RadioBusiSite.customer.models import Customer
from django.forms.models import modelformset_factory

class CustomerForm(forms.Form):
    user = forms.CharField(max_length=30, label='User Name')
    password1 = forms.CharField(max_length=30, label='Password', widget=forms.PasswordInput(render_value=False))
    password2 = forms.CharField(max_length=30, label=' Check Password', widget=forms.PasswordInput(render_value=False))
    Company = forms.CharField(max_length=200)
    ContactPerson = forms.CharField(max_length=200)
    email = forms.EmailField()
    ABN = forms.CharField(max_length=50)
    #Location = forms.ForeignKey(Location)
    #Playlist = forms.ManyToManyField(PlayList)

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("You must type the same password each time")
        return self.cleaned_data

    def clean_user(self):
        try:
            User.objects.get(username=self.cleaned_data['user'])
        except User.DoesNotExist:
            return self.cleaned_data['user']
        raise forms.ValidationError("This user is already in use. Please Choose another one.")

    def save(self):
        new_user = User.objects.create_user(username = self.cleaned_data['user'],
                                            email = self.cleaned_data['email'],
                                            password = self.cleaned_data['password1'])
        new_customer = Customer.objects.create(user=self.cleaned_data['user'],
                                               company = self.cleaned_data['Company'],
                                               ContactPerson = self.cleaned_data['ContactPerson'],
                                               email = self.cleaned_data['email'],
                                               ABN = self.cleaned_data['ABN'])

views.py

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from RadioBusiSite.customer.models import Customer,Location
from RadioBusiSite.customer.forms import CustomerForm
from django.contrib.auth import authenticate
from django.contrib.auth.models import User

def addCustomer(request):
    if request.method == 'POST':
        #user = UserForm(request.POST, instance=request.user)
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/home/')
    else:
        form = CustomerForm()

    return render_to_response('addCustomer.html', {
        'form': form,
    })

我启用了 AUTH 的想法

AUTH_PROFILE_MODULE = 'customer.Customer'

上面的文件都在一个名为“customer”的文件夹中

任何帮助都会很棒。

干杯 标记

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:
    def save(self):
        new_user = User.objects.create_user(username = self.cleaned_data['user'],
                            email = self.cleaned_data['email'],
                            password = self.cleaned_data['password1'])
        new_customer = Customer.objects.create(user=**new_user**,
                               company = self.cleaned_data['Company'],
                               ContactPerson = self.cleaned_data['ContactPerson'],
                               email = self.cleaned_data['email'],
                               ABN = self.cleaned_data['ABN'])
    

    注意上面**within stars** 的变化。 :)

    【讨论】:

    • 感谢就像一个魅力。只需将上面创建的对象传递给另一个对象。天才!
    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多