IntegrityError at /signup UNIQUE constraint failed: auth_user.username ---> In django - python

When I click on sign in button I get integrity error!! I have checked in my admin site and all users are properly visible which I had signed up. But when I click sign in button with entries already registered in admin, my code crashes and gives integrity error!!
views.py:
from django.http import HttpResponse
from django.shortcuts import redirect, render , HttpResponse
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate , login
# Create your views here.
def home(request):
return render(request,"authentication/index.html")
def signup(request):
if request.method=="POST":
username=request.POST.get('username')
fname=request.POST.get('fname')
lname=request.POST.get('lname')
email=request.POST.get('email')
pass1=request.POST.get('pass1')
pass2=request.POST.get('pass2')
myuser=User.objects.create_user(username,email,pass1) #creating user
myuser.first_name=fname
myuser.last_name=lname
myuser.save()
messages.success(request,"Your account has been successfuly created")
return redirect('/signin')
return render(request,"authentication/signup.html")
def signin(request):
if request.method=='POST':
username=request.POST.get('username')
pass1=request.POST.get('pass1')
user=authenticate(username=username,password=pass1)
if user is not None:
login(request,user)
return render(request,"authentication/index.html")
else:
messages.error(request,"Bad credentials")
redirect('home')
return render(request,"authentication/signin.html")
def signout(request):
pass

Related

Passing Id and Context in Django Redirect

I want to pass a model to a html page as context when I login into an account.
My Home page url comes with user id as a url parameter.
But i cant pass any context in redirect
views.py
from django.contrib.auth import authenticate,login,logout
from django.contrib import messages
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .models import users
from home.models import Posts
def f1(request):
Post = Posts.objects.all()
context = {'Post':Post}
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
uz = authenticate(request,username=username, password=password)
if uz is not None:
login(request,uz)
id = users.objects.filter(name=username).values('id')[0]['id']
return redirect('home',id) # This Works Fine
return redirect('home',id,context) # This is not Working
else:
messages.error(request,"Wrong Credentials")
return render(request,'login.html')
urls.py
from django.contrib.auth import logout
from django.urls import path
from . import views
urlpatterns=[
path('<str:users_id>/',views.func,name="home"),
]
How can I pass the context?
If I can't tell me an alternative way to do it.
You're redirecting to another view, so you're passing data through your url. You can't put your context in it, so you can directly render your template :
return render(request, "home.html", context)
If you really want to redirect to another url, as your context only contains all Post objects, you can build it in your home view.
Then you have :
f1 :
return redirect('home',id)
func :
context = {'Post': Posts.objects.all()}
return render(request, "home.html", context)
Add the id to your context dictionary and pass to redirect. Something like
context = {'Post':Post, 'Id':id}
return redirect('home', context)
#Balizok is correct: you can't pass context via the URL, without urlencoding it, which would be a bad idea for large amounts of data. If you need the home page to show posts or not show posts depending on whether the user has just logged in, you could do it in a few ways:
Show posts only if the user is logged in:
def home(request, id):
context = {}
if request.user.is_authenticated:
context["Post"] = Posts.objects.all()
return render(request, "home.html", context)
Show posts only if the user has just been redirected from the login page via a query parameter:
from django.url import reverse
def f1(request):
# ... log the user in etc.
url = reverse("home", id) + "?show_posts=true"
return redirect(url)
def func(request, id):
context = {}
if request.GET.get("show_posts") == "true":
context["Post"] = Posts.objects.all()
return render(request, "home.html", context)
Show posts only if the user has just been redirected from the login page via the session:
from django.url import reverse
def f1(request):
# ... log the user in etc.
request.session["show_posts"] = True
return redirect("home", id)
def func(request, id):
context = {}
if request.session.get("show_posts"):
context["Post"] = Posts.objects.all()
return render(request, "home.html", context)

IntegrityError at /signup UNIQUE constraint failed: auth_user.username

I'm trying to make an authentication system using Django using only 3 fields for SignUp (username & email & password ) and 2 fields for sign in ( username & password )
I think that the error that I get has relation to database, which I haven't used my models file yet, I don't know where the problem is coming from, is it from the signup function or the signing function
IntegrityError at /signup
UNIQUE constraint failed: auth_user.username
Request Method: POST
Request URL: http://127.0.0.1:8000/signup
Django Version: 3.2.6
Exception Type: IntegrityError
Exception Value:
UNIQUE constraint failed: auth_user.username
Exception Location: C:\Users\dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute
Python Executable: C:\Users\dell\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.0
Python Path:
['C:\\Users\\dell\\Desktop\\greenaftech',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib',
'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin']
Server time: Sat, 30 Apr 2022 00:24:12 +0000
this is my views.py:
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib import messages
# Create your views here.
def home(request):
return render(request,"website/index.html")
def signup(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
email=request.POST.get('email')
myuser= User.objects.create_user(username,email,password)
myuser.save()
messages.success(request,"Your Account has been created.")
return redirect('signin')
return render(request,"website/signup.html")
def signin(request):
if request.method=='POST':
usern=request.POST.get('username')
passs=request.POST.get('password')
user=authenticate(username=usern,password=passs)
if user is not None:
login(request,user)
userr=user.username
return render(request,"website/index.html",{'username':userr})
else:
messages.error(request,"Wrong Infos")
return redirect('home')
return render(request,"website/signin.html")
def signout(request):
pass
and these are my URLs.py :
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('signup',views.signup,name='signup'),
path('signin',views.signin,name='signin'),
path('signout',views.signout,name='signout'),
]
That error would be incurred if you try and create two users with the same username, with your uath_user model's username field having a unique=True constraint (which prevents two records having the same value in that field).
Note that if you use User.objects.create(...) as opposed to User(username="username"...) it will automatically save the new record, so myUser.save() may be trying to replicate that creation, creating the constraint issue, while still allowing you to see the item in admin

I want to add registeration to my web by django. I did all things right:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Tutorial
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User
def register (request):
form = UserCreationForm(request.POST)
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages():
print(form.error_messages[msg])
return render(request,
'main/register.html',
context={'form':form})
but still I get this error " 'dict' object is not callable
Request Method: POST Request
URL: http://127.0.0.1:8000/register/ Django Version: 3.0.7
Exception Type: TypeError
Exception Value: 'dict' object is not callable "
for msg in form.error_messages():
print(form.error_messages[msg])
First, no where in the Django documentation is using form.error_messages for the error messages, and if form.error_messages is a dict, then there is a python problem -> dict is not callable, get the list of keys by calling .keys() on your dict.
According to Newest Django's doc to get errors from your forms is using form.errors.
for field, msg in form.errors.items():
print(f'Field {key}: {msg}')

Even after dispatching, CSRF token won't work

So I followed the instructions from the answers on this thread:
#csrf_exempt does not work on generic view based class
However, when I send POST requests via Postman, it still keeps throwing 403 error and I wonder what I am missing here. I tried the last answer(using braces.views and CsrfExemptMixin) as well and it still wouldn't work. Below is my code so far
import json
import jwt
from psr.settings import SECRET_KEY
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth import views as auth_views
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from braces.views import CsrfExemptMixin
from .models import User
class LoginView(auth_views.LoginView):
#method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(LoginView, self).dispatch(request, *args, **kwargs)
def post(self, request):
form = AuthenticationForm(data = request.POST)
if form.is_valid():
user = authenticate(email=request.POST['email'], password=request.POST['password'])
if user is not None:
messages.add_message(request, messages.SUCCESS, "Welcome back, {}".format(user))
login(request, user)
token = jwt.encode({'id': user.id}, SECRET_KEY, algorithm='HS256').decode('utf-8')
return JsonResponse({'token': token}, status=200)
Am I missing something here?
Thanks a lot in advance!

login_required not working django even after cache clear

I want the user not to navigate back once he is logged out. I used login_required(login_url = "/login/") before my definition of logout view in my views.py. I am still able to navigate back after logging out. How can I ask the user to log in again? Also, If I type URL for my home page (say localhost:8000/home) directly in the browser, I am able to access the page without login. How can I correct this issue?
I have cleared browser cache too and still, no use.
my views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.views.decorators import csrf
from django.contrib.auth.decorators import login_required
def login(request):
c={}
# c.update(csrf(request))
return render(request,'login.html',c)
def auth_view(request):
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/home')
#login_required(login_url='/login/')
def logout(request):
request.session.flush()
auth.logout(request)
return render(request,'logout.html')
If you want to protect your home page or other pages with login, you should decorate them with login_required decorator. For example,
#login_required(login_url='/login/')
def home(request):
# Your code goes here

Categories

Resources