I am trying to understand how to expand the CreationForm library to utilize some custom fields I have in another model. Basically, in my model, I have a field called codeid and my goal is to have the user type in an integer and have that store into the database as they register. I know I'm somewhat on the right track, but there is some flawed logic behind my current code.
Forms.py
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
Views.py
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)
Models.py
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'
Registration HTML
{% extends 'home.html' %}
{%block content %}
<h2>Register</h2>
<form action='/register/' method = "post"> {% csrf_token %}
{{ form }}
<input type = "submit" value = "Register" />
</form>
{% endblock %}