I have two different forms in my register page as the one to one relationship in one of the model will show a drop down box therefore I am using the second models field where the user will have to input the field.
How would I make it so when the forms are valid, the 'SNI' will save to the first form and not the second.
Model
from asyncio import FastChildWatcher
import email
from pyexpat import model
from xxlimited import Null
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class userCouncil(BaseUserManager):
def create_user(self, userID, password=None):
if not email:
raise ValueError("Email is required")
user = self.model(userID = self.normalize_email(userID))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, userID, password):
user = self.model(userID = self.normalize_email(userID))
user.set_password(password)
user.is_staff = True
user.is_admin = True
user.save(using=self._db)
return user
class sni(models.Model):
SNI = models.CharField(max_length=256, primary_key=True)
Used = models.IntegerField(null=True, blank=True)
password = None
USERNAME_FIELD = 'SNI'
def __str__(self):
return self.SNI
class Account(AbstractBaseUser):
userID = models.EmailField(primary_key= True ,max_length=256, unique=True)
name = models.CharField(max_length=100)
dateOfBirth = models.DateField(max_length=8, null=True)
homeAddress = models.CharField(max_length=100, null=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True)
USERNAME_FIELD = 'userID'
objects = userCouncil()
def __str__(self):
return self.userID
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
Forms
import email
from pprint import isreadable
from pyexpat import model
from statistics import mode
from tabnanny import check
from xxlimited import Null
from attr import field
from django.forms import ModelForm, forms, widgets
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from matplotlib import use
from matplotlib.style import context
from .models import Account, sni
class createUserForm(UserCreationForm):
class Meta:
model = Account
fields = ['userID','name','dateOfBirth','homeAddress','password1','password2', 'sni']
def clean_userID(self):
userID = self.cleaned_data['userID'].lower()
u = self.cleaned_data['userID']
check_existing = Account.objects.filter(userID=userID).exists()
if check_existing:
raise forms.ValidationError("The following userID already exists: " + u)
else:
return userID
class SNIForm(UserCreationForm):
class Meta:
model = sni
fields = ['SNI', 'Used']
class AccountAuthenticationForm(forms.ModelForm):
password = forms.CharField(label = "password", widget = forms.PasswordInput)
class Meta:
model = Account
fields = ('userID', 'password')
Views
from django.shortcuts import redirect, render
from django.http import HttpResponse
from matplotlib import use
from matplotlib.pyplot import get
from matplotlib.style import context
from werkzeug import Request
from .models import *
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as dj_login
from django.forms import ModelForm, forms
from django.contrib.auth.decorators import login_required
from .forms import AccountAuthenticationForm, SNIForm, createUserForm
def login(request):
context = {}
if request.method == 'POST':
username = request.POST.get('username').lower()
password = request.POST.get('password')
user = authenticate(request, userID = username, password = password)
form = AccountAuthenticationForm(request.GET)
if user is not None:
dj_login(request, user)
return redirect('dashboardPage')
else:
messages.info(request, "userID or password is incorrect")
return render(request, 'base.html', context)
def registerPage(request):
form = createUserForm()
form2 = SNIForm()
if request.method == 'POST':
form = createUserForm(request.POST)
form2 = SNIForm(request.POST)
if form.is_valid() and form2.is_valid:
print(form2['SNI'].value)
form.save()
form2.save()
userID = form.cleaned_data.get('userID')
messages.success(request, "Account created for: " + userID)
return redirect('loginPage')
context = {'form' : form, 'form2' : form2}
return render(request, 'register.html', context)
#login_required(login_url='loginPage')
def dashboardPage(request):
context = {}
return render(request, 'dashboard.html', context)
In views please refer to the registerPage function. Thank you
What the first form can take is Sni_id.
There is no sni_id without first saving an sni instance.
What you can do is...
Save both forms
f=form.save()
f2=form2.save()
f2.instance.user = f.instance.id
UPDATE:
if form2.is_valid():
sni = form2.data["sni"]
used = form2.data["used"]
if SNI.objects.filter(sni=sni, used=used).exists()
f=form.save()
Related
I've created a usercreationform and try to check if username and email is already exist in database or not. Here It only check for email if it is exist or not but it cannot check for the username.
Views.py
from django.shortcuts import render,redirect
from . forms import signupform
from django.contrib import messages
from django.contrib.auth import login,authenticate,logout
from django.contrib.auth.models import User
def signup_data(request):
form = signupform(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if User.objects.filter(username=username).exists():
messages.error(request,'Username is already taken')
return redirect('signup')
elif User.objects.filter(email=email).exists():
messages.error(request,'Email is already taken')
return redirect('signup')
else:
form.save()
messages.success(request,'Account Is Created')
return redirect('signup')
return render(request,'login_module/signup.html',{'form':form, 'message': messages})
Forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User class signupform(UserCreationForm):
username= forms.CharField(max_length=10,widget=forms.TextInput(attrs={'class':'form-control'}))
first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'}))
last_name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'class': 'form-control'}))
email = forms.EmailField(max_length=20,widget=forms.EmailInput(attrs={'class': 'form-control'}))
password1 = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2 = forms.CharField(label="Confirm Password",widget=forms.PasswordInput(attrs={'class':'form-control'}))
class Meta:
model = User
fields = ['username','first_name','last_name','email','password1','password2']
You can combine both the queries to run a OR query using Q for that:
from django.db.models import Q
if User.objects.filter(Q(username=username)|Q(email=email)).exists():
# do stuff
Iam coding in django and trying to figure how to update profile of a user in my app
Please help me Iam trying to learn how to code and this is a big barrier for me to learn
here's models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
image = models.ImageField(default='default.jpg',upload_to="profile_pics")
def __str__(self):
return f'{self.user.username} Profile'
here's my views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get("username")
messages.success(request, f'Yor account has been created! You are now able to login')
return redirect('/login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html',{'form': form})
#login_required
def profile(request):
u_form = UserUpdateForm(instance = request.user)
p_form = ProfileUpdateForm(instance= request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
Iam getting error at 'u_form':u_form,
and This is my forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1','password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email']
class ProfileUpdateForm(forms.ModelForm):
model = Profile
field = ['image']
Iam getting my error at this
p_form = ProfileUpdateForm()
In the ProfileUpdateForm you defined the model class name without the Meta class
Model name and fields should be defined inside the Meta class like this:
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
I am trying to implement a custom user model. Whenever I try to log in for a user (created using the registration form), it returns no user.
but if I create a user using the admin panel then the login function works perfectly.
I think the problem is with password hashing. Tried some solve from here and there but seems like I can't find what I am looking for.
The problem I am having :
email: yeamin21#outlook.com
pass: 1234 works (created using admin panel)
but, email: yeamin21#outlook.com
pass: hashed(1234) does not (created using the registration form)
models.py
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
class User(AbstractBaseUser):
username = models.CharField(max_length=30,unique=True)
email = models.EmailField(verbose_name='Email',unique=True)
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
is_restaurant = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
def __str__(self):
return self.name
class Restaurant(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
location = models.CharField(max_length=200)
def __str__(self):
return self.user.email
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from Customer.models import User, Restaurant
class RestaurantSignUpForm(UserCreationForm):
class Meta(UserCreationForm):
model = User
fields = ['email','name','username']
#transaction.atomic
def save(self, commit=True):
user = super().save(commit=False)
user.is_restaurant=True
user.is_active=True
user.save()
restaurant = Restaurant.objects.create(user=user)
restaurant.save()
return user
backend.py
from django.contrib.auth.backends import BaseBackend, ModelBackend
from Customer.models import User
class CustomBackend(ModelBackend):
def authenticate(self,email=None,password=None):
try:
user=User.objects.get(email=email)
print('active')
if user.check_password(password) is True:
return user
except User.DoesNotExist:
return None
return User.objects.get(email=User.email)
def get_user(self, email):
try:
return User.objects.get(email)
except User.DoesNotExist:
return None
views.py
from django.contrib.auth import login, authenticate
from django.http import HttpResponse
from django.shortcuts import render
from django.views import generic
from Customer.forms import RestaurantSignUpForm
from Customer.models import User
def login_page(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
print(user)
if user is not None:
login(request, user)
return HttpResponse("Logged in")
else:
print(user)
context = {}
return render(request, 'login.html', context)
The problem is fixed
thanks to this https://stackoverflow.com/a/48971226/10602634
def authenticate(self, request, email=None, password=None):
try:
user= User.objects.get(email=email)
if check_password(password, user.password):
return user
except User.DoesNotExist:
return None
i want to add country and cities in forms currently i'm using django-countries for country but i'm gettings this error:
django.core.exceptions.FieldError: Unknown field(s) (country) specified for CustomUser
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from bootstrap_datepicker_plus import DatePickerInput
from tempus_dominus.widgets import DatePicker
from .models import CustomUser
from django_countries.fields import CountryField
class RegistrationForm(UserCreationForm):
CHOICES = (
(0, 'celebrities'),
(1, 'singer'),
(2, 'comedian'),
(3, 'dancer'),
(4, 'model'),
(5, 'Photographer')
)
Mobile_Number = forms.CharField(label='Mobile Number', widget= forms.NumberInput)
Artist_Category = forms.ChoiceField(choices=CHOICES)
bio = forms.CharField(widget=forms.Textarea,label = 'something about yourself')
portfolio = forms.URLField(label = 'enter your portfolio')
country = CountryField(blank_label = '(select_country)')
# country = forms.co
class Meta:
model = CustomUser
fields = ('email','password','Mobile_Number','Artist_Category','portfolio','country','bio',)
models.py: custome user model
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=100, unique=True)
name = models.CharField(max_length=100)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
last_login=models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD='email'
REQUIRED_FIELDS=[]
objects=UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
view.py:
from django.shortcuts import render, redirect
from main_site.models import artist
from django.urls import reverse_lazy
from .forms import BookartistForm, ContactForm
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.core.mail import EmailMultiAlternatives,EmailMessage
from django.template import loader
from .forms import RegistrationForm
from django.contrib.auth import login, authenticate
from django.http import HttpResponseRedirect
register view
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user= form.save()
raw_password = form.cleaned_data.get('password1')
# user = authenticate(request, email=user.email, password=raw_password)
# if user is not None:
# login(request, user)
# else:
# print('user is not authenticated')
return redirect('login')
else:
form = RegistrationForm()
return render(request, 'main_site/register.html', {'form':form})
...........................................................................................................................
new to django. I am building a form for user to save to the database. the save to database part is working. However, I want to be able to view and edit the data on two separate template. let's call them view_self_eval.html and edit_self_eval.html. I am stuck.
following is my code for Models.py, Forms.py and View.py for the particular form
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.forms import ModelForm
class self_eval(models.Model):
Owner = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
First_Name = models.CharField(max_length=100, default=None)
Last_Name = models.CharField(max_length=100, default=None)
Current_Role = models.CharField(max_length=100)
My_Strengths = models.CharField(max_length=1000)
Improvement = models.CharField(max_length=4000)
Goals = models.CharField(max_length=4000)
Profesional_Certification = models.CharField(max_length=4000)
Important_discussion = models.CharField(max_length=4000)
def __str__(self):
return self.Owner.username
def create_self_eval(sender, **kwargs):
if kwargs['created']:
self_eval = self_eval.objects.create(user=kwargs['instance'])
post_save.connect(create_self_eval, sender=User)
Forms.Py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from accounts.models import self_eval
class SelfEvalForm(forms.ModelForm):
class Meta:
model = self_eval
fields=(
'First_Name',
'Last_Name',
'Current_Role',
'My_Strengths',
'Improvement',
'Goals',
'Profesional_Certification',
'Important_discussion'
)
def save(self, commit=True):
self_eval = super(SelfEvalForm, self).save(commit=False)
self_eval.First_Name = self.cleaned_data['First_Name']
self_eval.Last_Name = self.cleaned_data['Last_Name']
self_eval.Current_Role = self.cleaned_data['Current_Role']
self_eval.My_Strengths = self.cleaned_data['My_Strengths']
self_eval.Improvement = self.cleaned_data['Improvement']
self_eval.Goals = self.cleaned_data['Goals']
self_eval.Profesional_Certification = self.cleaned_data['Profesional_Certification']
self_eval.Important_discussion = self.cleaned_data['Important_discussion']
if commit:
self_eval.save()
return self_eval
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm,
SelfEvalForm,
EditSelfEvalForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .models import self_eval
from django.views.generic import UpdateView
def self_eval(request):
if request.method == 'POST':
form = SelfEvalForm(request.POST)
if form.is_valid():
#save form data to DB
instance = form.save(commit=False)
instance.Owner=request.user
instance.save()
return redirect(reverse('accounts:self_eval'))
else:
form = SelfEvalForm()
args = {'form': form}
return render(request, 'accounts/self_eval_form.html', args)
def edit_self_eval(request, Owner_id):
self_eval = get_object_or_404(self_eval, pk=Owner_id)
if request.method == 'POST':
form = SelfEvalForm(request.POST, instance=Current_Role, Owner=request.user)
if form.is_valid():
self_eval = form.save()
else:
form = SelfEvalForm(intance=self_eval, Owner=request.user)
args = {'form':form,
'Current_Role':Current_Role
}
return render(request, 'accounts/edit_self_eval.html', args)