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})
...........................................................................................................................
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
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()
I will like to be able to send files in email in this django project. But files with spacies in their names seem not to go through, also when selecting the files to be sent i am able to select multiple files but only one file will go through the others are not recieved in mail.
Views.py
import os
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from .forms import EmailForm
from django.core.mail import send_mail
from django.conf import settings
from datetime import datetime
from django.core.mail import EmailMessage
def email1(request):
if request.method == "POST":
form = EmailForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.published_date = datetime.now()
post.save()
email = request.POST.get('email')
subject = request.POST.get('subject')
message = request.POST.get('message')
document = request.FILES.get('document')
email_from = settings.EMAIL_HOST_USER
recipient_list = [email]
email = EmailMessage(subject,message,email_from,recipient_list)
base_dir = 'media/documents/'
try:
for i in document:
email.attach_file('media/documents/'+str(document))
os.rename(document(document.replace(' ', '_')))
email.send()
return render(request, 'sendmail/sendmail.html')
except:
pass
else:
form = EmailForm()
return render(request, 'sendmail/sendmail.html', {'form': form})
forms.py
from django import forms
from django.forms import ClearableFileInput
from .models import Mails
class EmailForm(forms.ModelForm):
email = forms.EmailField(max_length=200, widget=forms.TextInput(attrs={'class': "form-control", 'id': "clientemail"}))
message = forms.CharField(widget=forms.Textarea(attrs={'class': "form-control"}))
document = forms.FileField(widget = forms.ClearableFileInput(attrs={'multiple':True}))
subject = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control"}))
class Meta:
model = Mails
fields = ('email', 'subject', 'message', 'document',)
models.py
from django.db import models
class Mails(models.Model):
email = models.EmailField()
subject = models.CharField(max_length=1000)
message = models.CharField(max_length=20000)
document = models.FileField(upload_to='documents/')
def __str__(self):
return self.email
I am creating a project to register and view profile using Django.
The problem is when I am trying to register a new user I am getting some errors
NOT NULL constraint failed: auth_user.username
Here is my form.py and view.py file:
form.py
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
class FileDataForm(forms.Form):
name = forms.CharField(max_length=50)
file = forms.FileField()
image = forms.ImageField()
class userregister(UserCreationForm):
first_name = forms.CharField(max_length=50, required = False ,help_text ='optional')
last_name = forms.CharField(max_length=50, required = False ,help_text ='optional')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password1', 'password2', )
class editprofileform(UserChangeForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email','password')
View.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render,redirect,render_to_response
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from .models import FileData
from .forms import FileDataForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .forms import userregister,editprofileform
from django.contrib.auth.forms import UserChangeForm , PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
# Create your views here.
#login_required
def home(request):
return HttpResponse('<h1>Welcome to your first page<h1>')
def registration(request):
print request
print 'request'
if request.method == 'POST':
#save the user data
form = userregister(request.POST)
print form.errors
print 'here'
if form.is_valid():
print 'i am here'
form.save()
return render(request , 'registration/success.html' ,{'form' : form,} )
else:
form = userregister()
return render(request , 'registration/register.html' ,{'form' : form,} )
else:
form = userregister()
return render(request , 'registration/register.html' , {'form': form,})
models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length = 100,default='')
city = models.CharField(max_length =30)
mobile = models.IntegerField(default=0)
def create_profile(sender , **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user = kwargs['instance'])
post_save.connect(create_profile , sender=User)
error:
Exception Value:
NOT NULL constraint failed: auth_user.username
In your form.py file, try inserting 'username' as the first element in the 'fields' list. It looks like you're not using that in the form so when you submit, it's leaving the username null.
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)