我试图了解如何扩展CreationForm库以利用我在另一个模型中的一些自定义字段。基本上,在我的模型中,我有一个名为codeid的字段,我的目标是让用户输入一个整数,并在注册时将该存储放入数据库。我知道我有点走上正轨,但我现在的代码背后有一些有缺陷的逻辑。
from django import forms
from django.contrib.auth.models import User # fill in custom user info then save it
from django.contrib.auth.forms import UserCreationForm
from .models import Address, Job
class MyRegistrationForm(UserCreationForm):
username = forms.CharField(required = True)
#udid = forms.CharField(required = True)
class Meta:
model = Address
fields = ('username', 'codeid', )
def save(self,commit = True):
user = super(MyRegistrationForm, self).save(commit = False)
user.codeid = self.cleaned_data['codeid']
if commit:
user.save()
return
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import MyRegistrationForm
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
print args
return render(request, 'register.html', args)
from django.db import models
from django.contrib.auth.models import User
class Address(models.Model):
user = models.ForeignKey(User)
street_address = models.CharField(max_length = 200)
city = models.CharField(max_length = 100)
state = models.CharField(max_length = 100)
zipcode = models.IntegerField(max_length = 5)
updated = models.DateTimeField(auto_now = True, auto_now_add = False)
timestamp = models.DateTimeField(auto_now = False, auto_now_add = True)
active = models.BooleanField(default = True)
codeid = models.IntegerField(max_length = 10, default = 0)
image = models.ImageField(upload_to='profiles/', default="")
def __str__(self,):
return 'test'
{% extends 'home.html' %}
{%block content %}
<h2>Register</h2>
<form action='/register/' method = "post"> {% csrf_token %}
{{ form }}
<input type = "submit" value = "Register" />
</form>
{% endblock %}
答案 0 :(得分:0)
在forms.py中进行更改:
返回用户