How to view (the same) data (of User) in UserProfile in Django - python

So I've got this situation.
-models.py
from django.db import models
from django.utils import timezone
from autoslug import AutoSlugField
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
def __unicode__(self):
return self.user.username
-forms.py
from django import forms
from django.forms import ModelForm
from tentagarden.models import UserProfile
from django.contrib.auth.models import User
from parsley.decorators import parsleyfy
#parsleyfy
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
-views.py
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from tentagarden.forms import UserForm, UserProfileForm
def home(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render_to_response(
'tentagarden/home.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
-admin.py
from django.contrib import admin
from .models import File, Post, UserProfile
admin.site.register(File)
admin.site.register(Post)
admin.site.register(UserProfile)
And I'd like to have the User data (so First name, Last name and Email) visualized in "User profiles" (in the Admin page), other than in "Users" only.
What should I do?
Thank you!

Put this is in your admin.py
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('email', 'first_name', 'last_name', 'website')
search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email')
# list_filter = ('some_field_to_filter')
readonly_fields = ('email', 'first_name', 'last_name')
def email(self, obj):
return obj.user.email
def first_name(self, obj):
return obj.user.first_name
def last_name(self, obj):
return obj.user.last_name
admin.site.register(UserProfile, UserProfileAdmin)
Use fieldsets to control the order of displayed fields in edit view.

Related

Cannot edit user profile and change password of the custom user in django

I have a custom user model in my django project. I can create users using the form based on this model but I'm unable to edit and change the passwords. How can I make this possible?
Created the custom user models as shown below.
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
class Role(models.TextChoices):
ADMIN = 'ADMIN', 'Admin'
DEVELOPER = 'DEVELOPER', 'Developer'
TESTER = 'TESTER', 'Tester'
base_role = Role.ADMIN
role = models.CharField(max_length=20, choices= Role.choices)
def save(self, *args,**kwargs):
if not self.pk:
self.role = self.base_role
return super().save(*args, **kwargs)
I tried to edit the user the profile and change password using this form.
from django.contrib.auth.forms import UserCreationForm
from .models import User
from django import forms
class RegisterUserForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=50)
last_name = forms.CharField(max_length=50)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email','role', 'password1', 'password2')
class EditUserForm(forms.ModelForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=50)
last_name = forms.CharField(max_length=50)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
corresponding views.py file
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.views.decorators.cache import never_cache
from .forms import RegisterUserForm, EditUserForm
from django.views import generic
from django.urls import reverse_lazy
from django.contrib.auth.views import PasswordChangeView
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.messages.views import SuccessMessageMixin
class EditProfileView(generic.UpdateView, SuccessMessageMixin):
form_class = EditUserForm
template_name = 'edit_profile.html'
success_url = reverse_lazy('home')
def get_object(self):
return self.request.user
def form_valid(self, form):
messages.success(self.request, 'Updated Successfully!')
return super().form_valid(form)
class PasswordsChangeView(PasswordChangeView):
form_class = PasswordChangeForm
template_name = 'change_password.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
messages.success(self.request, 'Password changed successfully')
return super().form_valid(form)
The forms are working fine with the templates but it's not getting updated based on the input I've given.

How to make a local form to stored in Django admin

i tried for make Django project and make a local form to stored in django admin here is my "view.py" file code
from django.http import request
from django.shortcuts import render,redirect
from templates.forms import Registrationform
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
def home(request):
numbers = [1,2,3,4,5]
name = 'max'
args = {'myName': name,'numbers':numbers}
return render(request, 'accounts/home.html',args)
def register(request):
if request.method == 'POST':
form = Registrationform(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = Registrationform()
args = {'form':form}
return render(request,'accounts/reg_form.html',args)
def view_profile(request):
args ={'user':request.user}
return render(request,'accounts/profile.html',args)
def edit_profile(request):
if request.method == 'POST':
form = UserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = UserChangeForm(instance=request.user)
args={'form':form}
return render(request,'accounts/edit_profile.html')
there is my another file that named forms.py and the errors came with registrationform
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.db import models
from django.db.models import fields
class Registrationform (UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit=True):
user = super(Registrationform, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
and another error is: module 'accounts.views' has no attribute 'profile' and sometimes can't import views also!!
Where is your Registrationform? You say it is living inside your 'templates' app/module, but Django can't find 'templates'. If it's inside the same directory as your views.py you can just import it with:
from .forms import Registrationform

NameError at /register/ name 'user' is not defined

I am currently developing a blogging webapp and I tried to extend my Django User Framework With a One To One Field, everything is working fine, but when I'm trying to register a new user, it's throwing a NameError. It is also worth noting that the user is being created and stored(I checked it from the admin page). It is saying that this statement profile.user = user in my views.py is creating the problem. Can anyone please help me with this?
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, ProfileForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
profile_form = ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
profile_form = ProfileForm
return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form})
#login_required
def profile(request):
return render(request, 'users/profile.html')
my models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
CHOICES = (
('AB+', 'AB+'),
('AB-', 'AB-'),
('A+', 'A+'),
('A-', 'A-'),
('B+', 'B+'),
('B-', 'B-'),
('O+', 'O+'),
('O-', 'O-'),
)
bloodgroup = models.CharField(max_length=100, choices= CHOICES)
bio = models.TextField(max_length=300)
def __str__(self):
return f'{self.user.username} Profile'
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']
def save(self, commit=True):
user = super().save(commit=False)
if commit:
user.save()
return user
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('image', 'bloodgroup', 'bio')
profile.user = user change to profile.user = request.user
Just add
from django.contrib.auth.models import User
instead of
from django.contrib.auth import User

UNIQUE constraint failed: new__users_profile.user_id. Python Django

django.db.utils.IntegrityError UNIQUE constraint failed
sqlite3.IntegrityError: UNIQUE constraint failed: new__users_profile.user_id
The above exception was the direct cause of the following exception:
new__users_profile.user_id
Error occurs when I'm trying to register new user, login to an existing user and when I am trying to migrate. I've tried to delete all migrations and migrate once again but it didn't help
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
class Media(models.Model):
image_name = models.CharField(max_length=50)
image_description = models.CharField(max_length=80)
image_image = models.ImageField(upload_to='media', default='default.jpg')
views
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import UserRegisterForm, MediaForm
from .models import Media
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'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
#login_required
def profile(request):
if request.method == 'GET':
media_images = Media.objects.all()
context = {
'media_images':media_images,
}
return render(request, 'users/profile.html', context)
#login_required
def add_media(request):
if request.method == 'POST':
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('http://127.0.0.1:8000/')
else:
form = MediaForm()
return render(request, 'users/add_media.html', {'form':form})
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import *
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class MediaForm(forms.ModelForm):
class Meta:
model = Media
fields = ['image_name', 'image_description', 'image_image']
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
I think you need primary_key=True,
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, null=True)
In class profile, add primary_key=True and remove null=True
user = models.OneToOneField(User,primary_key=True, on_delete=models.CASCADE)
I hope it will work!

NOT NULL constraint failed

Could someone smart explain me please where I have a bug?
I get this error when I would like to send a profile user form
NOT NULL constraint failed: userprofile_userprofile.godzina_id
I have an app "userprofile"
forms.py
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('imie', 'godzina')
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from django.conf import settings
#login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'user_profile.html', args)
models.py:
from django.db import models
from django.contrib.auth.models import User
from godzina.models import Godzina
class UserProfile(models.Model):
user = models.OneToOneField(User)
imie = models.CharField(max_length=150)
godzina = models.ForeignKey('godzina.Godzina')
User.profile = property(lambda u:UserProfile.objects.get_or_create(user=u)[0])
You could add null=True to your godzina attribute:
godzina = models.ForeignKey('godzina.Godzina', null=True)

Categories

Resources