There are some ways to do it, here is one:
Url:
from app import views
from app import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^complementary/', views.complementary)
]
Model:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class UserProfile(models.Model):
user_p = models.OneToOneField(User, related_name='userprofile',
primary_key=True)
age = models.CharField(max_length=3, blank=True)
shortbio = models.CharField(max_length=400, blank=True)
Views:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import redirect
from django.shortcuts import render
from app.forms import UserEditForm, ProfileEditForm
from app.models import UserProfile
# Create your views here.
def complementary(request):
profile = UserProfile.objects.get(user_p=1)
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user)
if request.method == 'POST':
user_form = UserEditForm(instance=request.user,
data=request.POST)
profile_form = ProfileEditForm(instance=request.user.usuario,
data=request.POST,
files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('redirect_url')
dic = {'profile': profile,
'user_form': user_form,
'profile_form': profile_form}
return render(request, 'template.html', dic)
Forms:
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from app.models import UserProfile
class UserEditForm(forms.ModelForm):
# Regex for non-digits
name_val = [RegexValidator(r'^[a-zA-ZÀ-Ÿ_]+( [a-zA-ZÀ-Ÿ_]+)*$',
message='Non-digits',
code='invalid_name')]
first_name = forms.CharField(
label='Name *',
validators=name_val,
widget=forms.TextInput(attrs={'placeholder': 'Name: '})
)
last_name = forms.CharField(
label='Last Name *',
validators=name_val,
widget=forms.TextInput(attrs={'placeholder': 'Last Name: '})
)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class ProfileEditForm(forms.ModelForm):
class Meta:
model = UserProfile
exclude = 'id',
Template.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ profile.shortbio }}
<form role="form" method="post" id="custom-form">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<button type="submit"></button>
</form>
</body>
</html>