Adding a profile.html page on my project - python

I have put a section on my website to fill a form of userprofile called profile.html . I have on this moment this models.py to display this information on my admin panel:
from django.db import models
from django.contrib.auth.models import User
def url(self,filename):
ruta = "MultimediaData/Users/%s/%s"%(self.user.username,filename)
return ruta
class userProfile(models.Model):
name = models.CharField(max_length=30, default='')
user = models.OneToOneField(User)
photo = models.ImageField(upload_to=url)
email = models.EmailField(max_length=75)
def __unicode__(self):
return self.user.username
I want to enable the possibility of edit this information per user on their respective profile, thereby i can audit the user profile information per user in my admin panel (localhost:8000/admin) what is the good form to create the respective view and it url?
This is my urls.py actually (This isn't the main urls.py, is an especial urls.py for my app and lack the url for profile)
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$','dracoin.apps.home.views.index' ,name='vista_principal'),
url(r'^landing/$','dracoin.apps.home.views.landing' ,name='vista_aterrizaje'),
url(r'^shop/page/(?P<pagina>.*)/$','dracoin.apps.home.views.shop' ,name='vista_tienda'),
url(r'^card/(?P<id_tarj>.*)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
url(r'^contacto/$','dracoin.apps.home.views.contacto' ,name='vista_contacto'),
url(r'^login/$','dracoin.apps.home.views.login_view',name='vista_login'),
url(r'^logout/$','dracoin.apps.home.views.logout_view',name='vista_logout'),
url(r'^registro/$','dracoin.apps.home.views.register_view',name='vista_registro'),
This is my models.py for profile:
from django.db import models
from django.contrib.auth.models import User
def url(self,filename):
ruta = "MultimediaData/Users/%s/%s"%(self.user.username,filename)
return ruta
class userProfile(models.Model):
name = models.CharField(max_length=30, default='')
user = models.OneToOneField(User)
photo = models.ImageField(upload_to=url)
email = models.EmailField(max_length=75)
def __unicode__(self):
return self.user.username
My views.py (lack the userProfile view)
from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm,RegisterForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth.models import User
from dracoin.settings import URL_LOGIN
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.contrib.auth.decorators import login_required
def index(request):
return render_to_response('home/index.html',context_instance=RequestContext(request))
#login_required(login_url=URL_LOGIN)
def landing(request):
return render_to_response('home/landing.html',context_instance=RequestContext(request))
#login_required(login_url=URL_LOGIN)
def shop(request,pagina):
lista_tarj = card.objects.filter(status=True)
paginator = Paginator(lista_tarj,5)
try:
page = int(pagina)
except:
page = 1
try:
tarjetas = paginator.page(page)
except (EmptyPage,InvalidPage):
tarjetas = paginator.page(paginator.num_pages)
ctx = {'tarjetas':tarjetas}
return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))
#login_required(login_url=URL_LOGIN)
def singleCard(request,id_tarj):
tarj = card.objects.get(id=id_tarj)
ctx = {'card':tarj}
return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))
#login_required(login_url=URL_LOGIN)
def contacto(request):
info_enviado = False # Define si se envio la informacion o no
email = ""
titulo = ""
texto = ""
if request.method == "POST":
formulario = ContactForm(request.POST)
if formulario.is_valid():
info_enviado = True
email = formulario.cleaned_data['Email']
titulo = formulario.cleaned_data['Titulo']
texto = formulario.cleaned_data['Texto']
# Configuracion de enviado de correos vis hotmail
to_supp = 'elzipa25#gmail.com'
html_content = "Informacion recibida<br><br><br>***Mensaje***<br><h3>%s<h3><br><br>%s<br><br>%s"%(titulo,email,texto)
msg = EmailMultiAlternatives('Correo de Contacto',html_content,'from#server.com',[to_supp])
msg.attach_alternative(html_content,'text/html') # Contenido definido como html
msg.send()
else:
formulario = ContactForm()
ctx = {'form':formulario,'email':email, 'titulo':titulo, 'texto':texto, 'info_enviado':info_enviado}
return render_to_response('home/contacto.html',ctx,context_instance=RequestContext(request))
def login_view(request):
mensaje = ""
if request.user.is_authenticated():
return HttpResponseRedirect('/')
else:
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
next = request.POST['next']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
usuario = authenticate(username=username,password=password)
if usuario is not None and usuario.is_active:
login(request,usuario)
return HttpResponseRedirect(next)
else:
mensaje = "user or password aren't correct"
next = request.REQUEST.get('next')
form = LoginForm()
ctx = {'form':form,'mensaje':mensaje,'next':next}
return render_to_response('home/login.html',ctx,context_instance=RequestContext(request))
def logout_view(request):
logout(request)
return HttpResponseRedirect('/')
def register_view(request):
form = RegisterForm()
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
usuario = form.cleaned_data['username']
email = form.cleaned_data['email']
password_one = form.cleaned_data['password_one']
password_two = form.cleaned_data['password_two']
u = User.objects.create_user(first_name=first_name,username=usuario,email=email,password=password_one)
u.save()
return render_to_response('home/thanks_register.html',context_instance=RequestContext(request))
else:
ctx = {'form':form}
return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))
ctx = {'form':form}
return render_to_response('home/register.html',ctx,context_instance=RequestContext(request))
Thanks!!
def edit_profile(request):
user = request.user
user_profile = user.userprofile
if request.method == 'POST':
user_profile_form = userProfile(request-POST)
if user_profile_form.is_valid():
update user profile
else:
user_profile_form = userProfileForm(instance=user_profile)
variables = RequestContext(request,{'user_profile_form' : user_profile_form})
return render_to_response('home/edit_profile.html', variables)

try this:
1- Add this to urls.py:
url(r'^edit_profile/$', 'dracoin.apps.home.views.edit_profile', name='edit_profile'),
2- create a form and user_profile view in views.py:
# form
class userProfileForm(forms.ModelForm):
class Meta:
model = userProfile
#view
def edit_profile(request):
user = request.user
user_profile = user.userprofile
if request.method == 'POST':
user_profile_form = userProfileForm(request.POST)
if user_profile_form.is_valid():
#update user profile
user_profile.name = request.POST['name']
user_profile.user = user
user_profile.email = request.POST['email']
user_profile.save()
else:
user_profile_form = userProfileForm(instance=user_profile)
variables = RequestContext( request, {
'user_profile_form': user_profile_form}
)
return render_to_response( 'edit_profile.html', variables )
3- Add edit_profile.html template:
<div>
<form method="POST" action=".">
{% csrf_token %}
{{ user_profile_form.as_p }}
<input type="submit" name="edit_profile" value="Done">
</form>
</div>

Related

Problems when the user wants to modify his data / The view didn't return an HttpResponse object. It returned None instead

I am new to programming, and I am having a problem with modifying user data.
The user registers, logs in and a profile is created; but when the user wants to access "my profile", modify something and save it, it throws an error and does not make the corresponding update.
I think this is where the code breaks down. It does not consider the form as valid
views.py
view.py:
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from users.forms import Edit_profile_form
from django.contrib.auth.forms import AuthenticationForm
from users.models import User_profile
from users.forms import User_registration_form
#login_required
def my_profile(request):
if request.user.is_authenticated:
try:
user = User_profile.objects.get(user=request.user)
except:
user = User_profile.objects.create(user=request.user)
user.save()
if request.method == "POST":
form = Edit_profile_form(request.POST, request.FILES)
if form.is_valid():
user.name = form.cleaned_data['name']
user.last_name = form.cleaned_data ['last_name']
user.description = form.cleaned_data['description']
user.image = form.cleaned_data['image']
user.website = form.cleaned_data['website']
user.save()
return redirect('inicio')
elif request.method == "GET":
form = Edit_profile_form(initial = {
'name':user.name,
'last_name':user.last_name,
'description':user.description,
'image': user.image,
'website':user.website,
})
context = {'form':form,'user':user}
return render(request, 'users/my_profile.html', context=context)
def register(request):
if request.method == 'POST':
form = User_registration_form(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
context = {'errors':form.errors}
form = User_registration_form()
context['form'] = form
return render(request, 'users/register.html', context)
elif request.method == 'GET':
form = User_registration_form()
return render(request, 'users/register.html', {'form': form})
def login_request(request):
if request.method == 'POST':
form = AuthenticationForm(request=request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
print('login request estoy aca 002')
login(request, user)
context = {'message':f'Bienvenido {username}!! :D'}
return render(request, 'inicio.html', context = context)
form = AuthenticationForm()
return render(request, 'users/login.html', {'error': 'Formulário inválido', 'form': form})
elif request.method == 'GET':
form = AuthenticationForm()
return render(request, 'users/login.html', {'form': form})
urls.py:
from django.urls import path
from users.views import login_request, register,my_profile
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('login/', login_request, name='login'),
path('register/', register, name='register'),
path('logout/', LogoutView.as_view(template_name = 'users/logout.html'), name='logout'),
path ('profile/', my_profile, name='my_profile'),
models.py:
from django.db import models
class User_profile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE, related_name='profile')
is_active=models.BooleanField(default=True)
name = models.CharField(max_length=50, blank=True, verbose_name='Nombre')
last_name = models.CharField(max_length=50, blank=True, verbose_name='Apellido',default='')
email = models.EmailField(blank=False)
description = models.CharField(max_length=350, blank=True, verbose_name='Descripción')
image = models.ImageField(upload_to='profile_image/', blank=True, verbose_name='Imagen')
website = models.CharField(max_length=300, blank=True,null=True)
def __str__(self):
return self.user.username + ' - profile'
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class User_registration_form(UserCreationForm):
email = forms.EmailField(required=True)
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
class Edit_profile_form(forms.Form):
name = forms.CharField (required=False, label='Nombre', widget=forms.TextInput(attrs={'placeholder':'Ingresa tu Nombre'}))
last_name = forms.CharField(required=False, label='Apellido', widget=forms.TextInput(attrs={'placeholder':'Ingresa tu Apellido'}))
description = forms.CharField(required=False, label='Descripción', widget=forms.TextInput(attrs={'placeholde': 'Contanos algo de vos'}))
image = forms.ImageField()
website = forms.CharField(required=False, label='WebSite', widget=forms.TextInput(attrs={'placeholder':'Ingresa tu website'}))
admin.py
from django.contrib import admin
from .models import User_profile
#admin.register(User_profile)
class User_profileAdmin(admin.ModelAdmin):
list_display = ['name','last_name', 'email', 'description', 'image', 'website']
html my_profile
{% extends "padre.html" %}
{% block bloqueQueCambia %}
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<table>
<div class="card" style="width: 25rem;">
{% if user.image %}
<img src="{{user.image.url}}" class="card-img-top" style="width: 18rem;" alt="Card image cap">
{% else %}
<img class="card-img-top" src="https://cdn.icon-icons.com/icons2/1378/PNG/512/avatardefault_92824.png" style="width: 18rem;"alt="Card image cap">
{% endif %}
{{form.as_table}}
<div class="card-body">
<p></p>
Borrar
</div>
</div>
</table>
<p></p><input type="submit" name="enviar"></p>
</form>
{% endblock %}
I leave attached two images.
One is of the VS terminal when the user enters his profile, modifies it and wants to save that change (when it breaks).
And the other one is the error that shows me on the screen.
Error displayed on screen
Errors displayed by console VS
I hope the post can be read correctly, it is the first time I make one.
The code is not for real application, it is to be presented in a course.
Thank you very much for the help
You forget one return in your view:
def my_profile(request):
... # some staff
if request.method == "POST":
... # some staff
if form.is_valid():
... # some staff
print('my profile estoy aca 005')
return redirect('inicio')
else:
print('la sentencia else se ejecutara')
# WHERE is RETURN something?
I think it should be:
else:
print('la sentencia else se ejecutara')
context = {'form':form,'user':user}
return render(request, 'users/my_profile.html', context=context)

how to exclude admin user from my user list

how to exclude admin users from my user list? the below image shows the problem. I don't want to show the admin user in the friend list of a user.
I don't want to show the main_admin user on this user list as it is my admin user of the site
views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Profile
from feed.models import Post
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.conf import settings
from django.http import HttpResponseRedirect
from .models import Profile, FriendRequest
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
import random
User = get_user_model()
#login_required
def users_list(request):
users = Profile.objects.exclude(user=request.user)
sent_friend_requests = FriendRequest.objects.filter(from_user=request.user)
sent_to = []
friends = []
for user in users :
friend = user.friends.all()
for f in friend:
if f in friends:
friend = friend.exclude(user=f.user)
friends += friend
my_friends = request.user.profile.friends.all()
for i in my_friends:
if i in friends:
friends.remove(i)
if request.user.profile in friends:
friends.remove(request.user.profile)
random_list = random.sample(list(users), min(len(list(users)), 10))
for r in random_list:
if r in friends:
random_list.remove(r)
friends += random_list
for i in my_friends:
if i in friends:
friends.remove(i)
for se in sent_friend_requests:
sent_to.append(se.to_user)
context = {
'users': friends,
'sent': sent_to
}
return render(request, "users/users_list.html", context)
# def queryset(self, request):
# if request.user.is_superuser:
# return User.objects.filter(is_superuser=False)
# return User.objects.all()
def friend_list(request):
p = request.user.profile
friends = p.friends.all()
context = {
'friends': friends
}
return render(request, "users/friend_list.html", context)
#login_required
def send_friend_request(request, id):
user = get_object_or_404(User, id=id)
frequest, created = FriendRequest.objects.get_or_create(
from_user=request.user,
to_user=user)
return HttpResponseRedirect('/users/{}'.format(user.profile.slug))
#login_required
def cancel_friend_request(request, id):
user = get_object_or_404(User, id=id)
frequest = FriendRequest.objects.filter(
from_user=request.user,
to_user=user).first()
frequest.delete()
return HttpResponseRedirect('/users/{}'.format(user.profile.slug))
#login_required
def accept_friend_request(request, id):
from_user = get_object_or_404(User, id=id)
frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first()
user1 = frequest.to_user
user2 = from_user
user1.profile.friends.add(user2.profile)
user2.profile.friends.add(user1.profile)
if FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first():
request_rev = FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first()
request_rev.delete()
frequest.delete()
return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug))
#login_required
def delete_friend_request(request, id):
from_user = get_object_or_404(User, id=id)
frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first()
frequest.delete()
return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug))
def delete_friend(request, id):
user_profile = request.user.profile
friend_profile = get_object_or_404(Profile, id=id)
user_profile.friends.remove(friend_profile)
friend_profile.friends.remove(user_profile)
return HttpResponseRedirect('/users/{}'.format(friend_profile.slug))
#login_required
def profile_view(request, slug):
p = Profile.objects.filter(slug=slug).first()
u = p.user
sent_friend_requests = FriendRequest.objects.filter(from_user=p.user)
rec_friend_requests = FriendRequest.objects.filter(to_user=p.user)
user_posts = Post.objects.filter(user_name=u)
friends = p.friends.all()
# is this user our friend
button_status = 'none'
if p not in request.user.profile.friends.all():
button_status = 'not_friend'
# if we have sent him a friend request
if len(FriendRequest.objects.filter(
from_user=request.user).filter(to_user=p.user)) == 1:
button_status = 'friend_request_sent'
# if we have recieved a friend request
if len(FriendRequest.objects.filter(
from_user=p.user).filter(to_user=request.user)) == 1:
button_status = 'friend_request_received'
context = {
'u': u,
'button_status': button_status,
'friends_list': friends,
'sent_friend_requests': sent_friend_requests,
'rec_friend_requests': rec_friend_requests,
'post_count': user_posts.count
}
return render(request, "users/profile.html", context)
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 can now login!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
#login_required
def edit_profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('my_profile')
else:
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/edit_profile.html', context)
#login_required
def my_profile(request):
p = request.user.profile
you = p.user
sent_friend_requests = FriendRequest.objects.filter(from_user=you)
rec_friend_requests = FriendRequest.objects.filter(to_user=you)
user_posts = Post.objects.filter(user_name=you)
friends = p.friends.all()
# is this user our friend
button_status = 'none'
if p not in request.user.profile.friends.all():
button_status = 'not_friend'
# if we have sent him a friend request
if len(FriendRequest.objects.filter(
from_user=request.user).filter(to_user=you)) == 1:
button_status = 'friend_request_sent'
if len(FriendRequest.objects.filter(
from_user=p.user).filter(to_user=request.user)) == 1:
button_status = 'friend_request_received'
context = {
'u': you,
'button_status': button_status,
'friends_list': friends,
'sent_friend_requests': sent_friend_requests,
'rec_friend_requests': rec_friend_requests,
'post_count': user_posts.count
}
return render(request, "users/profile.html", context)
#login_required
def search_users(request):
query = request.GET.get('q')
object_list = User.objects.filter(username__icontains=query)
context = {
'users': object_list
}
return render(request, "users/search_users.html", context)
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone
from django.db.models.signals import post_save
from django.conf import settings
from autoslug import AutoSlugField
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField("Profile", blank=True)
def __str__(self):
return str(self.user.username)
def get_absolute_url(self):
return "/users/{}".format(self.slug)
def post_save_user_model_receiver(sender, instance, created, *args, **kwargs):
if created:
try:
Profile.objects.create(user=instance)
except:
pass
post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL)
class FriendRequest(models.Model):
to_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='to_user', on_delete=models.CASCADE)
from_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='from_user', on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "From {}, to {}".format(self.from_user.username, self.to_user.username)
Here as you can see main_admin is my superuser and I don't want it to appear in the add new friend list, so please help me out to solve this problem as I'm new to django, Thank you
You just have to exclude the admin from the returned friends list :
def friend_list(request):
p = request.user.profile
friends = p.friends.exclude(user__is_staff=True)
context = {
'friends': friends
}
return render(request, "users/friend_list.html", context)
p.friends.all().exclude(is_superuser=True)
Make sure your user class parameter is using (AbstractUser).

Saving username to model in Django

I am creating a donation app that allows donors to create listings. This data is stored in a Django Model and is going to be displayed on a page. I want to save the user's username to the Django model and display it on the page. My code is down below
Models.py
class Donation(models.Model):
title = models.CharField(max_length=30)
phonenumber = models.CharField(max_length=12)
category = models.CharField(max_length=20)
image = models.CharField(max_length=1000000)
deliveryorpickup = models.CharField(max_length=8)
description = models.TextField()
Views.py
from django.contrib.auth.models import User
from django.http.request import RAISE_ERROR
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import forms, inlineformset_factory
from django.contrib.auth.forms import UserCreationForm, UsernameField
from .forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from home.models import Donation
# Create your views here.
def index(request,*args, **kwargs):
return render(request, "index.html", {} )
#login_required(login_url='/login/')
def dashboard(request,*args, **kwargs):
return render(request, "dashboard.html", {} )
def register(request, ):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been successfully created, {username} ')
return redirect('loginpage')
context = {'form': form}
return render(request, "register.html", context )
def loginpage(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/dashboard')
else:
messages.error(request, 'Username OR password is incorrect')
context = {}
return render(request, 'login.html', context)
def logoutuser(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
image = request.POST['imagelink']
deliveryorpickup = request.POST['deliveryorpickup']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, image = image, deliveryorpickup = deliveryorpickup, description = description )
ins.save()
return render(request,'donate.html')
Forms.py (This is where the user is created)
class CreateUserForm(UserCreationForm):
username = forms.CharField(required=True, max_length=30, )
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True, max_length=50)
last_name = forms.CharField(required=True, max_length=50)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',]
#function to display errors
def clean(self):
cleaned_data=super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if User.objects.filter(username=cleaned_data["username"]).exists():
raise ValidationError("This username is taken, please try another one")
elif password1 != password2:
raise forms.ValidationError("2 password fields do not match")
elif len(password1) < 8 or len(password2) < 8:
raise forms.ValidationError("Passwords must be at least 8 characters long")
To associate the user with the Donation model, you should first add a ForeignKey field to the model class:
from django.conf import settings
class Donation(models.Model):
... # your other donation fields
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
)
Once you've made this change, and run the migrations, in your views.py you'll pass the currently signed in user to the Donation model creation:
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
ins = Donation(
title=request.POST["title"],
... # all of the other fields
user=request.user, # 👈 This adds the user
)
ins.save()
return render(request,'donate.html')
Notes
Using settings.AUTH_USER_MODEL allows your class to use a custom user model, or django's default user model, based on your project's settings.
To understand what on_delete=models.CASCADE does, you should read django's documentation about it.
Also, instead of manually passing all of the request.POST[...] values to the Donation model, I recommend that you use a ModelForm. It will handle errors and validation for you, as well as generate the HTML displayed in the template. Using a model form here would make your view code change to this:
from django.forms import ModelForm
class DonationForm(ModelForm):
class Meta:
model = Donation
exclude = ["user"]
#login_required(login_url="/login/")
def donate(request):
if request.method == "POST":
form = DonationForm(request.POST)
if form.is_valid():
donation = form.save(commit=False)
donation.user = request.user
donation.save()
# Use a redirect to prevent duplicate submissions
# https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/#redirect
return redirect(request, ...)
else:
form = DonationForm()
return render(request, "donate.html", {"form": form})

i'm trying to create a product and save to database but isn't working

I'm trying to create a product and save it.
The page redirects where it's supposed to but doesn't save the date.
recently I had some problem registering a user and when I fixed it now this problem occurred.
views.py
from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from .models import myUser,Listings,Bid
from django.http import HttpResponseRedirect
from django.urls import reverse
from .form import registerForm,loginForm,createListingForm
from django.db import IntegrityError
from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.
def index(request):
if not request.user.is_authenticated:
message = f"please sign in"
else :
message = f"signed in as {request.user}"
return render(request, "auctions/index.html",{
"listings": Listings.objects.all(),
"message": message
})
def login_view(request):
if request.method == "POST":
form = loginForm()
email = request.POST["email"]
password = request.POST["password"]
user = authenticate(request,username=email,password=password)
if user is not None:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return render(request, "auctions/login.html",{
"form": form ,
"message": "username/password not valid"
})
return render(request, "auctions/login.html",{
"form": loginForm()
})
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
def register(request):
if request.method == "POST":
form = registerForm()
email = request.POST["email"]
# check passwords are same
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render (request, "auctions/register.html",{
"form": form,
"message": "Passwords does not match"
})
# Attempt to create new user
try:
user = myUser.objects.create_user(email,password)
user.save()
except IntegrityError:
return render(request, "auctions/register.html", {
"form":form,
"message": "Username is already taken"
})
login(request,user)
return HttpResponseRedirect(reverse('index'))
return render(request, "auctions/register.html", {
"form": registerForm()
})
#login_required(login_url='login')
def createListing(request):
if request.method == "POST":
form = createListingForm(request.POST or None,request.FILES or None)
if form.is_valid():
obj = form.save(commit=False)
obj.listed_by = request.user
obj.save()
# messages.success(request,"Creation successful")
return HttpResponseRedirect(reverse('index'))
else:
form = createListingForm()
return render(request, "auctions/create.html", {
"form": form
})
def itemPage(request,listing_id):
return render(request, "auctions/item.html", {
"item" : Listings.objects.get(pk= listing_id)
})
#login_required(login_url='login')
def bid(request):
if request.method == "POST":
new_bid = request.POST["new_bid"]
return HttpResponseRedirect('itemPage')
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser,BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
# Create your models here.
class myUserManager(BaseUserManager):
"""
custom user model manager where email is unique indentifiers for authenticaton
instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff',True)
extra_fields.setdefault('is_superuser',True)
extra_fields.setdefault('is_active',True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff= True'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email,password, **extra_fields)
class myUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = myUserManager()
def __str__(self):
return f'{self.email}'
class Listings(models.Model):
listing_name = models.CharField(max_length=50)
price = models.IntegerField(default=1)
date_listed = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
item_image = models.ImageField()
description = models.TextField(max_length=200, default="Description Not Available")
listed_by = models.ForeignKey(myUser,on_delete=models.CASCADE, default=1,null=True)
def __str__(self):
return f'{self.listing_name}'
class Bid(models.Model):
item_name = models.ForeignKey(Listings,on_delete=models.CASCADE)
bid_by_user = models.ForeignKey(myUser,on_delete=models.CASCADE)
new_bid = models.IntegerField()
forms.py
from django.forms import ModelForm
from django.db import models
from django import forms
from django.forms import Form,PasswordInput
from .models import Listings,myUser
from django.contrib.auth.mixins import LoginRequiredMixin
class loginForm(forms.ModelForm):
class Meta:
model = myUser
fields = ['email', 'password']
widgets = {
# telling Django your password field in the mode is a password input on the template
'password': forms.PasswordInput()
}
class registerForm(forms.ModelForm):
confirmation = forms.CharField()
class Meta:
model = myUser
fields = ['email', 'password']
widgets = {
# telling Django your password field in the mode is a password input on the template
'password': forms.PasswordInput()
}
class createListingForm(forms.ModelForm):
class Meta:
model = Listings
fields = ['listing_name', 'price', 'item_image', 'description']
create.html
{% extends 'auctions/layout.html' %}
{% load static %}
{% block body %}
<div>
<form action="{% url 'create' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-primary" type="submit" value="Submit">
</form>
</div>
{% endblock%}
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
path('register/', views.register, name='register'),
path('create_listing/', views.createListing, name='create'),
path('item/<int:listing_id>', views.itemPage, name='item'),
path('bid/', views.bid, name='bid')
]
I would also like to request some other suggestions on my code. Thank you.
When you are uploading any files, use multipart/form-data when your form includes any <input type="file"> elements.
Currently, when you are submitting the form, the form is invalid since it does not contain the multipart/form-data in the create.html file. Hence, it is not getting saved.
Replace
<form action="{% url 'create' %}" method="post">
with
<form action="{% url 'create' %}" method="post" enctype="multipart/form-data">
I'm assuming you're talking about creating a listing. Can you try this way instead?
#login_required(login_url='login')
def createListing(request):
if request.method == "POST":
form = createListingForm(request.POST or None,request.FILES or None)
if form.is_valid():
listing_name = form.cleaned_data.get("listing_name")
price = form.cleaned_data.get("price")
# get the image from the form
item_image = request.FILES['item_image']
description = form.cleaned_data.get("description")
listed_by = request.user
# here is where the saving happens
Listings.objects.create_user(
listing_name=listing_name,
price=price,
item_image=item_image,
description=description,
listed_by=listed_by)
# then do your redirections or whatever you want done after save
# messages.success(request,"Creation successful")
return HttpResponseRedirect(reverse('index'))
else:
form = createListingForm()
return render(request, "auctions/create.html", {
"form": form
})

Django 127.0.0.1:8000/admin/ stopped working

Not sure what I've done to break the admin site, but going to 127.0.0.1:8000/admin/ is not working and gives me the error in the screenshot below:
Here's the two urls.py files:
myproject/urls.py
from django.conf.urls import include, url
from django.contrib import admin
import product_app.urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(product_app.urls)),
]
and the product_app urls.py:
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
from . import views
from .views import *
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^subscribe/$', views.subscribe, name='subscribe'),
url(r'^products/$', views.products, name = 'products'),
url(r'^product/$', ProductListView.as_view(), name='product_list'),
url(r'^user/(\w+)/$', views.profile, name='profile'),
url(r'post_url/', views.post_product, name='post_product'),
url(r'^([0-9]+)/$', views.detail, name = 'detail'),
url(r'^login/$', views.login_view, name='Login'),
url(r'^logout/$', views.logout_view, name='Logout'),
url(r'^like_product/$', views.like_product, name='like_product' ),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='product-edit'),
url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='product-delete'),
]
if settings.DEBUG:
urlpatterns += [
url(r'^product/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
...and just in case, the models.py:
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
def get_image_path(instance, filename):
return '/'.join(['product_images', str(instance.name), filename])
class Product(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
price = models.DecimalField(max_digits=10, decimal_places=2)
url = models.CharField(max_length=200)
product_type = models.CharField(max_length=100)
image = models.ImageField(upload_to='product_images', blank=True, null=True)
image_url = models.CharField(max_length=200, blank=True)
likes = models.IntegerField(default=0)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index', kwargs={})
...finally, my views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from .models import Product #, HashTag
from .forms import ProductForm, LoginForm, ContactForm, SubscribeForm, EditProfileForm
from django.views import generic
# edit / delete views
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import UpdateView, DeleteView
# contact and subscribe forms
from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth import get_user_model
from . import forms
from django.shortcuts import render
from django.views.generic.list import ListView
class HomePage(generic.TemplateView):
template_name = "index.html"
def get_context_data(self, *args, **kwargs):
context=super(HomePage, self).get_context_data(*args, **kwargs)
context['form'] = ContactForm
return context
def products(request):
username = request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
else:
products = Product.objects.all()
form = ProductForm()
return render(request, 'products.html', {'products': products, 'form':form})
class ProductListView(ListView):
template_name = 'product_list.html'
context_object_name = 'product_list'
paginate_by = None
def get_queryset(self):
username = self.request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
return Product.objects.none()
def post_product(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProductForm(data = request.POST, files = request.FILES)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
product = form.save(commit = False)
product.user = request.user
product.likes = 0
product.save()
# redirect to a new URL:
return HttpResponseRedirect('/products')
def detail(request, product_id):
product = Product.objects.get(id=product_id)
#hashtags = HashTag.objects.filter(product=product_id)
return render(request, 'detail.html', {'product': product})
def profile(request, username):
user = get_object_or_404(User, username=username)
products = Product.objects.filter(user=user)
if not request.user == user:
return render(request, 'no.html')
else:
return render(request, 'profile.html', {'user':user,'products': products})
def edit_profile(request):
user = request.user
products = Product.objects.filter(user=user)
form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.save()
return render(request, 'profile.html', {'user':user,'products': products})
context = {"form": form}
return render(request, "edit_profile.html", context)
def like_product(request):
product_id = request.POST.get('product_id', None)
likes = 0
if (product_id):
product = Product.objects.get(id=int(product_id))
if product is not None:
likes = product.likes + 1
product.likes = likes
product.save()
return HttpResponse(likes)
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
print("User is valid, active and authenticated")
login(request, user)
products = Product.objects.filter(user=user)
return render(request, 'profile.html', {'user':user,'products': products})
else:
print("The password is valid, but the account has been disabled!")
else:
# the authentication system was unable to verify the username and password
print("The username and password were incorrect.")
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def logout_view(request):
logout(request)
return HttpResponseRedirect('/')
class PostUpdateView(UpdateView):
model = Product
form_class = ProductForm
template_name = 'edit_product.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# Any manual settings go here
self.object.save()
# return HttpResponseRedirect(self.object.get_absolute_url())
return redirect ('products')
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostUpdateView, self).dispatch(request, *args, **kwargs)
class PostDeleteView(DeleteView):
model = Product
template_name = 'product_confirm_delete.html'
def get_success_url(self):
return reverse ('products')
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
User = get_user_model()
def subscribe(request):
form_class = SubscribeForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
# Email the profile with the
# contact information
template = get_template('contact/subscribe_template.txt')
context = dict({'contact_name': contact_name, 'contact_email': contact_email,})
content = template.render(context)
email = EmailMessage(
"New subscribe form submission",
content,
"Your website" +'',
['steve#steve-shead.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'contact/thank_you_subscribe.html')
return render(request, 'contact/subscribe.html', {
'form': form_class,
})
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact/contact_template.txt')
context = dict({'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content,})
content = template.render(context)
email = EmailMessage(
"New contact form submission",
content,
"Your website" +'',
['steve#steve-shead.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'contact/thank_you.html')
return render(request, 'contact/contact.html', {
'form': form_class,
})
I have no clue what I changed to make the admin site not work - any help gratefully received!
Check your ROOT_URLCONF setting - it needs to be set to myproject.urls but looks like it is currently set to product_app.urls.

Categories

Resources