Django 127.0.0.1:8000/admin/ stopped working - python

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.

Related

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

Django - How to allow only the owner of a new post to edit or delete the post?

I will be really grateful if anyone can help to resolve the issue below.
I have the following Django project coding. The problem is: when the browser was given "/posts/remove/<post_id>/" or "/posts/edit/(<post_id>/" as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively.
How can I allow only the owner of a new post to edit or delete the post?
account.models.py:
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
posts.models.py:
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='posts_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique_for_date='created')
image = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
description = models.TextField(blank=True)
created = models.DateTimeField(default=timezone.now,
db_index=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='posts_voted',
blank=True)
status = models.CharField(max_length=10, default='published')
objects = models.Manager() # The default manager.
published = PublishedManager() # The Dahl-specific manager.
tags = TaggableManager()
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('posts:detail', args=[self.id, self.slug])
posts.view.py:
from django.views.decorators.http import require_POST
from django.shortcuts import render, redirect, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.core.context_processors import csrf
from .forms import PostCreateForm, EmailPostForm, CommentForm, SearchForm
from .models import Post
from actions.utils import create_action
#login_required
def post_create(request):
"""
View for creating a new post.
"""
if request.method == 'POST':
# form is sent
form = PostCreateForm(data=request.POST, files=request.FILES)
if form.is_valid():
cd = form.cleaned_data
new_item = form.save(commit=False)
# assign current user to the item
new_item.user = request.user
tags = form.cleaned_data['tags']
new_item.save()
for tag in tags:
new_item.tags.add(tag)
new_item.save()
create_action(request.user, 'created a post:', new_item)
messages.success(request, 'Post added successfully')
form = PostCreateForm()
else:
messages.error(request, 'Error adding new post')
else:
# build form
form = PostCreateForm(data=request.GET)
return render(request, 'posts/post/create.html', {'section': 'posts',
'form': form})
#login_required
def post_remove(request, post_id):
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.method == 'POST':
form = PostCreateForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('posts:mypost')
else:
form = PostCreateForm(instance=item)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('posts/post/post_edit.html', args)
posts.urls.py
from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeed
urlpatterns = [
url(r'^create/$', views.post_create, name='create'),
url(r'^remove/(?P<post_id>\d+)/$', views.post_remove, name='post_remove'),
url(r'^edit/(?P<post_id>\d+)/$', views.post_edit, name='post_edit'),
]
Add request.user == item.user check inside your method.
#login_required
def post_remove(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
...
//write your code here

How can I enable the users delete and edit post they create in Django?

I am trying to have users delete and edit post they create. I was told "Post.user needs to be an object instance what you wrote is incorrect." but I am still newer to django and would like to know the steps to do this as I created this project with some help.
here is my models
from django.db import models
from django.db.models import Count, QuerySet, F
from django.utils import timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from markdown_deux import markdown
from django.utils.safestring import mark_safe
from taggit.managers import TaggableManager
from comments.models import Comment
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 )
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
description = models.TextField()
tags = TaggableManager()
public = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-created", "-updated" ]
def get_markdown(self):
description = self.description
markdown_text = markdown(description)
return mark_safe(markdown_text)
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
Here is my views
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.core.exceptions import PermissionDenied
from comments.forms import CommentForm
from comments.models import Comment
from .forms import PostForm
from .models import Post
def post_main(request):
return render(request, "base2.html")
#login_required
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
#login_required
def post_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Post Saved")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form
}
return render(request, "post_form.html", context)
def post_user(request):
return HttpResponse("<h1>Users Post</h1>")
#login_required
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid() and request.user.is_authenticated():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user = request.user,
content_type= content_type,
object_id = obj_id,
content = content_data,
parent = parent_obj,
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
comments = instance.comments
context = {
"title": instance.title,
"instance": instance,
"comments": comments,
"comment_form":form,
}
return render(request, "post_detail.html", context)
#login_required
def post_feed(request):
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query)|
Q(tags__icontains=query)|
Q(content__icontains=query)|
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var,
}
return render(request, "post_feed.html", context)
#login_required
def post_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if request.user == Post.user:
instance.delete() # or save edits
messages.success(request, "Successfully Deleted")
return redirect("posts:feed")
else:
raise PermissionDenied # import it from django.core.exceptions
return redirect("posts:feed")
def privacy(request):
return render(request, "privacy.html")
def post_about(request):
return HttpResponse("<h1>About Page</h1>")
def home(request):
return render(request, "base2.html")
Let me know if any other information is needed.
You are almost there.
in delete, your check should be:
request.user == instance.user
instead of
request.user == Post.user
Similarly in post_update, you could do:
if instance.user == request.user:
#Now, allow update
Also, it might be a good idea to check for the request type. Example:
if request.method == "POST":
This way, this check would only happen if it is a POST type

CSRF token missing or incorrect. Django 1.8 restaurant app

I am getting this error (on Chrome):
CSRF token missing or incorrect
What I am trying to do is make a restaurant application. I have my menu items and am trying to create a record in my orders table. Any time one button is clicked I want to add that entry into the orders table
Here are my files:
views.py
from django.shortcuts import render, render_to_response
from django.http import HttpRequest, HttpResponseRedirect
from django.template import RequestContext
from datetime import datetime
from app.models import *
def menu(request):
menus = Menu.objects.all()
return render_to_response('app/menu.html', {'menus':menus})
def menudetails(request,id):
menu = Menu.objects.get(pk = id)
return render_to_response('app/menudetails.html', {'menu':menu})
def myorders(request,id):
# if request.method == "POST":
#order = Order.createorder(Menu(pk=id))
# order.save()
if request.method == "GET":
form = OrderForm()
return render(request, 'app/menudetails.html',{ 'form':form })
elif request.method == "POST":
form = OrderForm(request.POST)
form.save()
return HttpResponseRedirect('/menu');
def addmenu(request):
if request.method == "GET":
form = MenuForm()
return render(request, 'app/addmenu.html',{ 'form':form })
elif request.method == "POST":
form = MenuForm(request.POST)
form.save()
return HttpResponseRedirect('/menu');
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/index.html',
context_instance = RequestContext(request,
{
'title':'Home Page',
'year':datetime.now().year,
})
)
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
context_instance = RequestContext(request,
{
'title':'Contact',
'message':'Your contact page.',
'year':datetime.now().year,
})
)
def about(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
context_instance = RequestContext(request,
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
})
)
urls.py
from datetime import datetime
from django.conf.urls import patterns, url
from app.forms import BootstrapAuthenticationForm
# Uncomment the next lines to enable the admin:
# from django.conf.urls import include
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^myorders$', 'app.views.myorders', name = 'myorders'),
url(r'^menu$', 'app.views.menu', name = 'menu'),
url(r'^addmenu$', 'app.views.addmenu', name = 'addmenu'),
url(r'^menu/(?P<id>\d+)$', 'app.views.menudetails', name = 'menudetails'),
url(r'^menu/(?P<id>\d+)/order$', 'app.views.myorders', name = 'myorders'),
url(r'^$', 'app.views.home', name='home'),
url(r'^contact$', 'app.views.contact', name='contact'),
url(r'^about', 'app.views.about', name='about'),
url(r'^login/$',
'django.contrib.auth.views.login',
{
'template_name': 'app/login.html',
'authentication_form': BootstrapAuthenticationForm,
'extra_context':
{
'title':'Log in',
'year':datetime.now().year,
}
},
name='login'),
url(r'^logout$',
'django.contrib.auth.views.logout',
{
'next_page': '/',
},
name='logout'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
models.py
from django.db import models
from django import forms
from datetime import datetime
class Menu(models.Model):
name = models.CharField("Menu Item", max_length = 50)
desc = models.CharField("Description", max_length = 100)
price = models.DecimalField(max_digits=6, decimal_places = 2)
class MenuForm(forms.ModelForm):
class Meta:
model = Menu;
fields = ['name','desc','price'];
class Order(models.Model):
menuItem = models.ForeignKey(Menu)
ordercreated = models.DateTimeField(auto_now_add = True)
orderupdate = models.DateTimeField(auto_now = True)
completed = models.BooleanField(default = False)
user = models.CharField(max_length = 30, blank = True)
def createorder(cls, menu):
order = cls(menuItem = menu)
return order
How to avoid this error, solutions as below:
Add {% csrf_token %} in your template
Link:csrf_token
Add #csrf_exempt on your view
Link:csrf_exempt

Issues with view.py

I am getting the following error: view_page() takes exactly 2 arguments (1 given)
The code of view.py is:
from wiki.models import Page
from django.shortcuts import render_to_response
def view_page(request, page_name):
try:
page = Page.objects.get(pk=page_name)
except PageDoesNotExist:
return render_to_response("create.html", {"page_name":page_name})
the url given in url.py is :
url(r'^wiki/$', 'wiki.views.view_page'),
But when I am giving the url as given below and delete the above one then i am getting the error of page not found.
url(r'^wiki/(?P<page_name>[^/]+)/$','wiki.views.view_page'),
This is because the second parameter for the view_page() is passed in the url
example
url(r'^wiki/(?P<page_name>[^/]+)/$','wiki.views.view_page')
something.com/wiki/2 #here 2 is the second parameter which is like
def view_page(request, 2)
if u use this
url(r'^wiki/$', 'wiki.views.view_page'),
something.com/wiki/ #The second parameter is not passed to the function
I think your queryset is wrong. If you're passing page_name in the URL, then it should look like:
Page.objects.get(name=page_name)
Maybe second argument should be optional?
def view_page(request, page_name="Default value"):
from django.shortcuts import render, redirect, HttpResponseRedirect
from django.http import HttpResponse
from .forms import loginForm, signUpForm, createBlog, blogcomment
from django.contrib.auth import authenticate, login as auth_login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.views.generic import View, TemplateView, ListView, DetailView, CreateView
from django.contrib.auth.decorators import login_required
from . import models
def login(request):
login_form = loginForm()
if request.method =='POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
auth_login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return render(request,'login.html',{'login_form':login_form,'message':'Please check the username and password'})
else:
return render(request,'login.html',{'login_form':login_form})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
def signup(request):
# print(request.method)
signup_form = signUpForm()
if request.method =='POST':
#print(request.POST)
signup_form = signUpForm(request.POST)
#print(signup_form)
# signup_form.firstname = request.POST['firstname']
# signup_form.lastname = request.POST['lastname']
# signup_form.email = request.POST['email']
# signup_form.username = request.POST['username']
# signup_form.dob = request.POST['dob']
# signup_form.my_photo = request.POST.get('my_photo',False)
# signup_form.password = request.POST['password']
if signup_form.is_valid():
user = signup_form.save()
user.set_password(user.password)
user.save()
return redirect('login')
else:
print(signup_form.errors)
else:
#print('hello1')
signup_form = signUpForm()
#print('hello2')
return render(request, 'signup.html',{'signup_form':signup_form})
class create_blog(LoginRequiredMixin,CreateView):
def get(self, request):
context = {'form':createBlog(),'title':'create'}
return render(request, 'create.html',context)
def post(self, request):
form = createBlog(request.POST)
if form.is_valid():
blog = form.save(commit=False)
blog.blogger = request.user
blog.save()
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'create.html',{'form':form})
# login_url = '/login/'
# redirect_field_name = 'index.html'
# template_name = 'create.html'
#
# form_class = createBlog
#
# model = models.blog
class index(ListView, LoginRequiredMixin):
def get(self, request):
#print(request.user)
blogs= models.blog.objects.filter(blogger= request.user).values('id','title','content','created_at','blog_photo')
#print(list(blogs))
return render(request, 'index.html',{'title':'index','blogs':list(blogs)})
def post(self, request):
#print(request.POST)
return user_logout(request)
class delete(LoginRequiredMixin, DetailView):
def get(self, request, id):
blog = models.blog.objects.filter(id=id)
blog.delete()
return HttpResponseRedirect(reverse('index'))
class blog(ListView, LoginRequiredMixin, CreateView):
def get(self, request, id):
#print(request.user)
blog= models.blog.objects.get(id=id)
#blog=list(blog)[0]
#print(blog)
comments = models.comment.objects.filter(blog=id).values('comment')
#print(comments)
'''
new_list=[]
print(list(comments))
for comment in list(comments):
new_dict={}
blogg= models.blog.objects.filter(id=comment.get('blog_id')).values()
blogg=list(blogg)[0]
print(blogg)
bloger = models.user.objects.filter(email=blogg['blogger_id']).values('username')
print(bloger)
bloger = list(bloger)[0]
new_dict['comment']=comment['comment']
new_dict['comment_user'] = bloger['username']
new_list.append(new_dict)
print(new_list)
'''
context = {'form':blogcomment(),'title':'blog','blog':blog,'comments':comments}
return render(request, 'blog.html',{'title':'blog','blog':blog,'comments':comments,'form':blogcomment()})
def post(self, request, id):
#print(request.POST)
if 'logout' in request.POST:
return user_logout(request)
else:
form = blogcomment(request.POST)
blog = models.blog.objects.get(id=id)
#print(blog)
if form.is_valid():
comment = form.save(commit=False)
comment.blog = blog
comment.save()
return HttpResponseRedirect(reverse('blogview', kwargs={'id':id}))
return render(request, 'blog.html',{'form':form})
class sr(ListView, LoginRequiredMixin):
def get(self, request, string):
print(request )
blogs= models.blog.objects.filter(title__contains=string).values('id','title','content','created_at')
print(blogs)
return render(request,'search-page.html',{'data':list(blogs),'title':'Search Results'})

Categories

Resources