Django Update AbstractUser - django

IntegrityError at /
NOT NULL constraint failed: pages_profile.username
Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.9
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: pages_profile.username
How do I update an abstractuser from a post request using a form that's already signed in?
from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile
def index(request):
context = {}
if request.method == "POST":
print(request.POST)
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
img = form.cleaned_data.get("avatar")
obj, created = Profile.objects.update_or_create(
username=form.cleaned_data.get('username'),
defaults={'avatar': img},
)
obj.save()
print(obj)
return redirect('home')
else:
form = UserProfileForm()
context['form']= form
return render(request, "home.html", context)
urls.py
from django.urls import path
from pages.views import index
urlpatterns = [
path('', index, name='home'),
]
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class Profile(AbstractUser):
avatar = models.ImageField(default='default.png', upload_to='',null=True, blank=True )
forms.py
from django import forms
from django.core.files.images import get_image_dimensions
from pages.models import Profile
class UserProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('avatar',)

from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile
def index(request):
context = {}
if request.method == "POST":
print(request.POST)
form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user)
if form.is_valid():
"""
img = form.cleaned_data.get("avatar")
print(img)
print(form.cleaned_data.get('username'))
print(request.user)
obj, created = Profile.objects.update_or_create(
username=form.cleaned_data.get('username'),
defaults={'avatar': img},
)
obj.save()
print(obj)
"""
form.save()
return redirect('home')
else:
form = UserProfileForm(instance=request.user)
context['form']= form
return render(request, "home.html", context)
I swapped it to this and it just works but it doesn't delete the old photo in the s3 bucket yet. It was instance=request.user which was needed.

Related

The view account.views.signup didn't return an HttpResponse object. It returned None instead

Trying to register user in Django. it keep giving me HttpResponse error
signup.html templates location is : templates/registration/signup.html
Here's what i tried:
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=50)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', )
views.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from .forms import SignUpForm
#login_required
def home(request):
return render(request, 'registration/home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
I did tried replacing redirect with HttpResponseRedirect but it did't work
Account urls.py
from django.contrib.auth import views as auth_views
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path("login/", auth_views.LoginView.as_view(template_name = "registration/login.html"), name='login'),
path("logout/", auth_views.LogoutView.as_view(), name='logout'),
path('home/', views.home, name='home'),
url('signup/', views.signup, name='signup'),
]
Error
ValueError at /accounts/signup/
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 3.0.3
Exception Type: ValueError
Exception Value:
The view account.views.signup didn't return an HttpResponse object. It returned None instead.
You need to support GET method e.g.:
def signup(request):
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
raw_password = form.cleaned_data.get('password1')
user = authenticate(email= email, password= raw_password)
login(request, user)
return redirect('registration/home')
return render(request, 'registration/signup.html', {'form': form})

how create a #username by taking username from registration form

i have setup the forms in the frontend what i want is that any User if gives his username for example username-> helloworld then it is interpreted as #helloworld and then this form with changed #username should be saved in the database so that i can use it afterwards.....
i am a noob in django framework .
i have been trying since last 2 days to find a answer here and by using google but unable to find a helpful answer
here is my ->forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
this is my -> views.py file
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import SignUpForm
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
UserModel = get_user_model()
#index and signin def have been removed because it is out of context of question
def signup(request):
if request.user.is_authenticated:
return redirect('index')
else:
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
User.username = "#{}".format(User.username)
user.is_active = False
user = form.save
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('activation_mail.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
Just override your form's save method to alter the data before saving.
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
def save(self, *args, **kwargs):
self.instance.username = f"#{self.instance.username}"
return super().save(*args, **kwargs)

User register page using (contrib.auth.models User) but facing Not Null Constraint Error

I am first to Django.
I am making a registeration form only to facing NOT NULL constraint failed: blog_userprofile.user_id.
i have been trying to figure out but i can not. Thank you for any help:)
This is my models.py file
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.PROTECT,blank=True)
def __str__(self):
return self.user.name
This is my forms.py file
from django import forms
from .models import Post,Comment,UserProfile
class UserProfileForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
username = forms.CharField(max_length=200)
email = forms.EmailField()
class Meta():
model = UserProfile
fields = ['username','email','password']
And this is my views.py file
from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect,HttpResponse
from django.urls import reverse_lazy,reverse
from django.views.generic import (TemplateView,ListView,DetailView)
from django.views.generic.edit import CreateView,UpdateView,DeleteView
from .models import Post,Comment,UserProfile
from .forms import PostForm,CommentForm,UserProfileForm
def register(request):
registered = False
if request.method == 'POST':
user_form = UserProfileForm(request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
return HttpResponseRedirect(reverse('blog:user_login'))
else:
print('unvalid imformation')
else:
user_form = UserProfileForm()
return render(request,'register/registration.html',{'user_form':user_form, 'registered':registered})
And this comment shows up
IntegrityError at /signup/
NOT NULL constraint failed: blog_userprofile.user_id
If you get an existing user from your database you can use
user_form = UserProfileForm(request.POST, instance=a)
Or you can try this code
if request.method == 'POST':
# If you get an existing user from your database you can use
#user_form = UserProfileForm(request.POST, instance=a)
user_form = UserProfileForm(request.POST)
if user_form.is_valid():
user = user_form.save(commit=False)
user.set_password(user.password)
user.save()
registered = True
return HttpResponseRedirect(reverse('blog:user_login'))

I am having an error that says "ModelForm has no model class specified."

I was just watching a tutorial in youtube and i was just following what was indicated buti still got those errors.
Forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(max_length = 50)
class Meta:
model : User
fields = ['username', 'password1', 'password2']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
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'Account created for {username}!')
return redirect('home')
else:
form = UserRegisterForm()
return render (request, 'users/register.html', {'form':form})

Attaching logged in user to a class based form and model

views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadDocument
from .models import Document
def upload_document(request):
if request.method == 'POST':
form = UploadDocument(request.POST, request.FILES)
if form.is_valid():
# file is saved
instance = Document(passport=request.FILES['passport'])
instance.save()
instance = Document(id_license=request.FILES['id_license'])
instance.save()
instance = Document(User=request.user)
instance.save()
# needs to add instance of User from cache
return HttpResponseRedirect('/success/url/')
else:
form = UploadDocument()
return render(request, 'verification/verificate.html', {'form': form})
forms.py
from django import forms
class UploadDocument(forms.Form):
passport = forms.ImageField()
id_license = forms.ImageField()
models.py
from django.conf import settings
from django.db import models
class Document(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
passport = models.ImageField()
id_license = models.ImageField()
Exception Value: NOT NULL constraint failed:
verification_document.user_id
I want to create a form that allows uploading documents, for verification purpose. How to attach a loged in User?
try this code:
views.py
def upload_document(request):
if request.method == 'POST':
form = UploadDocument(request.POST, request.FILES)
if form.is_valid():
instance=Document()
instance.passport=request.FILES['passport']
instance.id_license=request.FILES['id_license']
instance.User=request.user
instance.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadDocument()
return render(request, 'verification/verificate.html', {'form': form})