Skip to content

Instantly share code, notes, and snippets.

@MdShohanurRahman
Last active November 11, 2019 13:16
Show Gist options
  • Save MdShohanurRahman/adf68b6fd87409135087ce4049e423c5 to your computer and use it in GitHub Desktop.
Save MdShohanurRahman/adf68b6fd87409135087ce4049e423c5 to your computer and use it in GitHub Desktop.
Extends User Model With OneToOne Relation
from django.contrib import admin
from .models import UserProfile
# Register your models here.
admin.site.register(UserProfile)
from .models import UserProfile
from django import forms
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('location','age')
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE )
location = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
return self.user.username
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import UserProfileForm
def home(request):
count = User.objects.count()
return render(request, 'home.html', {
'count': count
})
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
user = form.save() # return the object of the usercreation form
profile = profile_form.save(commit=False) # not save this monment just instantiate it
profile.user = user
profile.save()
return redirect('home')
else:
form = UserCreationForm()
profile_form = UserProfileForm
return render(request, 'registration/signup.html', {
'form': form,
'profile_form':profile_form
})
@login_required
def secret_page(request):
return render(request, 'secret_page.html')
# class based secret page view
class SecretPage(LoginRequiredMixin, TemplateView):
template_name = 'secret_page.html'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment