Django扩展用户onetoone

时间:2011-03-24 05:36:50

标签: python django django-forms

我有一个扩展用户模型并具有表单的模型

class Dealer(models.Model):
    account         =models.CharField(max_length=8,blank=True)
    addresses       = generic.GenericRelation( Addres, null=True, blank=True )       
    email           =models.EmailField(blank=True)           
    name            =models.CharField(max_length=50)       
    tel             =models.CharField(max_length=20,blank=True)    
    state           =models.ForeignKey(State)
    summa           =models.FloatField(blank=True)
    user            =models.OneToOneField(User, blank=True)

class DealerForm(forms.ModelForm):    
    username = forms.RegexField(label=("Username"), max_length=30, regex=r'^[\w.@+-]+$',
        help_text = ("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
        error_messages = {'invalid': ("This value may contain only letters, numbers and @/./+/-/_ characters.")})
    password = forms.CharField(label=("Password"), widget=forms.PasswordInput)

    class Meta:
        model=Dealer
        exclude=('user')

但是当我尝试用这样的观点展示它时

def dealer_form(request,id_):                          
        form=DealerForm(initial={'username':''})                                   
        return render_to_response('dealer_form.html', {'form': form},context_instance=RequestContext(request))

字段用户名和密码用第一个用户数据填充。帮我解决问题。

1 个答案:

答案 0 :(得分:1)

假设您传入的ID是经销商的ID:

views.py:

from django.shortcuts import get_object_or_404

def dealer_form(request, id_):
    if id_:
        dealer = get_object_or_404(Dealer, pk=id_)

    form=DealerForm(instance=dealer)
    return render_to_response('dealer_form.html', {'form':form},
        context_instance=RequestContext(request))