how to exclude admin user from my user list - python

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).

Related

Django - details of one account showing up on another account

I've have a pet registration system where the customer can log into their account and register their animals. However once you have registered the animal and log out and another user logs in that user can see all the pets of all users. I'm not sure what's causing this.
my views.py
def customer_profile(request):
if request.method == "GET":
if request.user.is_authenticated:
get_pets = PetRegistration.objects.filter()
context = {
"pets": get_pets,
}
return render(
request, "registration/customer-profile.html", context=context
)
return redirect("login")
if request.method == "POST":
context = {}
return render(request, "registration/customer-signup.html", context=context)
def pet_register(request):
if request.method == "GET":
if request.user.is_authenticated:
form = PetRegistrationForm()
context = {
"form": form,
}
return render(request, "registration/pet-register.html", context=context)
return redirect("login")
if request.method == "POST":
form = PetRegistrationForm(request.POST, request.FILES)
context = {
"form": form,
}
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return redirect("customer_profile")
return render(request, "registration/pet-register.html", context=context)
model.py
class PetRegistration(models.Model):
user = models.ForeignKey(Account, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
image = models.ImageField(null=True, blank=True)
age = models.CharField(max_length=30)
animal_type = models.CharField(max_length=30)
vaccination_status = models.CharField(choices=STATUS, max_length=20)
def __str__(self):
return self.name

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})

getting error while saving a data into database in django using .save() method

I have created 2 models.
from django.db import models
from django.contrib.auth.models import User
class categories(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class tasks(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
category = models.ForeignKey(categories, on_delete=models.CASCADE)
def __str__(self):
return self.title
and have created the forms from these models.
the view.py is
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from .forms import CategoriesForm,TaskForm
from .models import categories,tasks
from django.utils import timezone
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'user/home.html')
def signupuser(request):
if request.method == 'GET':
return render(request, 'user/signupuser.html', {'form':UserCreationForm()})
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect('currentcategories')
except IntegrityError:
return render(request, 'user/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'})
else:
return render(request, 'user/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'})
def loginuser(request):
if request.method == 'GET':
return render(request, 'user/loginuser.html', {'form':AuthenticationForm()})
else:
user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
if user is None:
return render(request, 'user/loginuser.html', {'form':AuthenticationForm(), 'error':'Username and password did not match'})
else:
login(request, user)
return redirect('currentcategories')
#login_required
def logoutuser(request):
if request.method == 'POST':
logout(request)
return redirect('home')
#login_required
def createcategories(request):
if request.method == 'GET':
return render(request, 'user/createcategories.html', {'form':CategoriesForm()})
else:
try:
form = CategoriesForm(request.POST)
newcategory = form.save(commit=False)
newcategory.user = request.user
newcategory.save()
return redirect('currentcategories')
except ValueError:
return render(request, 'user/createcategories.html', {'form':CategoriesForm(), 'error':'Bad data passed in. Try again.'})
#login_required
def currentcategories(request):
categ = categories.objects.filter(user=request.user)
return render(request, 'user/currentcategories.html', {'categories':categ})
#login_required
def viewcategory(request, categories_pk):
categ = get_object_or_404(categories, pk=categories_pk, user=request.user)
if request.method == 'GET':
form = CategoriesForm(instance=categories)
return render(request, 'user/viewcategory.html', {'categories':categ, 'form':form})
else:
try:
form = CategoriesForm(request.POST, instance=user)
form.save()
return redirect('currentcategories')
except ValueError:
return render(request, 'user/viewcategory.html', {'categories':categ, 'form':form, 'error':'Bad info'})
#login_required
def deletecategories(request, categories_pk):
categ = get_object_or_404(categories, pk=categories_pk, user=request.user)
if request.method == 'POST':
categ.delete()
return redirect('currentcategories')
#login_required
def task(request,categories_pk):
categ = get_object_or_404(categories, pk=categories_pk, user=request.user)
if request.method == 'GET':
form = TaskForm(instance = tasks)
return render(request, 'user/task.html', {'categories':categ, 'form':form})
else:
try:
form = TaskForm(request.POST, instance=tasks)
form.save()
return redirect('currentcategories')
except ValueError:
return render(request, 'user/viewcategory.html', {'categories':categ, 'form':form, 'error':'Bad info'})
#login_required
def createtask(request, categories_pk):
if request.method == 'GET':
return render(request, 'user/createtask.html', {'form':TaskForm()})
else:
try:
form = TaskForm(request.POST)
newtask = form.save(commit=False)
newtask.user = request.user
newtask.category_id = request.POST.get('categories_pk')
newtask.save()
return redirect('currenttask')
except ValueError:
return render(request, 'user/createtask.html', {'form':TaskForm(), 'error':'Bad data passed in. Try again.'})
#login_required
def currenttask(request):
tasks = task.objects.filter(categories=request.user.category)
return render(request, 'user/currenttask.html', {'categories':categ})
i am getting error at newtask.save()
Error is:
IntegrityError at /categories/16/createtask/
null value in column "category_id" violates not-null constraint
DETAIL: Failing row contains (10, low, asdfgh, null).
how to procede with this?
Try :
category = models.ForeignKey(categories, null=True, on_delete=models.CASCADE)
You need to use the keyword argument passed to the view categories_pk:
#login_required
def createtask(request, categories_pk):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.instance.category_id = categories_pk
newtask = form.save()
return redirect('currenttask')
else:
form = TaskForm()
return render(request, 'user/createtask.html', {'form':TaskForm()})
Note: Instead of passing 'error':'Bad data passed in. Try again.'
into the context use the forms errors. form.field_name.errors
contains a fields errors and form.non_field_errors contain non-field
errors.

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.

Adding a profile.html page on my project

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>

Categories

Resources