Page not found (404) in Django Output - python

Urls.py:
urlpatterns = [
path("", views.index, name="blogHome"),
path("blogpost/<int:id>/", views.blogpost, name="blogHome")
]
Views.py:
django.shortcuts import render
from .models import Blogpost
# Create your views here.
def index(request):
return render(request, 'blog/index.html')
def blogpost(request, id):
post.Blogpost.objects.filter(post_id = id)[0]
print(post)
return render(request, 'blog/blogpost.html')
Models.py:
from django.db import models
class Blogpost(models.Model):
post_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
head0 = models.CharField(max_length=500, default="")
chead0 = models.CharField(max_length=10000, default="")
head1 = models.CharField(max_length=500, default="")
chead1 = models.CharField(max_length=10000, default="")
head2 = models.CharField(max_length=500, default="")
chead2 = models.CharField(max_length=10000, default="")
pub_date = models.DateField()
thumbnail = models.ImageField(upload_to='blog/images', default="")
def __str__(self):
return self.title
Error
Error in cmd
Not Found: /blog/blogpost
[21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" 404 2678

The current error means Django doesn't find anything with the route blog/blogpost, it is because you have also defined an id to be pass in route, so kindly try http....blog/blogpost/1/ any id you can give.
Also, id is generally used to get a single object, and you are doing filtering on it. I think you should use get_object_or_404 if you want to retrieve single object.
As #lvanStarostin stated in the above comment that URL patterns should also have unique names. You should change one of the names.
Note: Models are classes of python so they must be written in PascalCase, so you may change your model name to BlogPost from Blogpost.

Related

How can I add two different slugs on two models in two different apps in Django?

I trying to add slugs to my service page and my project page, but whenever I try to run my project page I get the Page not found (404)
No service found matching the query
Request Method: GET
Request URL: http://127.0.0.1:8000/project/
Raised by: pages.views.<class 'pages.views.ServiceDetail'>
Here's my class-based code
models.py
class Service(models.Model):
title = models.CharField(max_length=50)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
alt = models.CharField(max_length=60, blank=True)
icon = models.CharField(max_length=20)
description = RichTextField()
shortdesc = models.CharField(max_length=255)
slug = models.SlugField(null=False, unique=True)
created_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('service_detail', kwargs={'slug': self.slug})
class Project(models.Model):
title = models.CharField(max_length=50)
category = models.CharField(max_length=50)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
alt = models.CharField(max_length=60, blank=True)
client = models.CharField(max_length=50)
launched = models.CharField(max_length=50)
demands = models.CharField(max_length=50)
description = RichTextField()
shortdesc = models.CharField(max_length=255)
slug = models.SlugField(null=False, unique=True)
video_link = models.URLField(max_length=100)
created_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('project_detail', kwargs={'slug': self.slug})
urls.py
path('<slug:slug>/', views.ServiceDetail.as_view(), name='service_detail'),
path('project/<slug:slug>/', views.ProjectDetail.as_view(), name='project_detail'),
views.py
def project(request):
return render(request, 'project/project.html')
class ProjectDetail (generic.DetailView):
model = Project
template_name = 'project/project_detail.html'
def service(request):
return render(request, 'pages/service.html')
class ServiceDetail (generic.DetailView):
model = Service
template_name = 'pages/service_detail.html'
how can I re-route so that my project page can work out? any help would be grateful
Your url path in urls.py is pointing to path('project/slug:slug/',...), however you are requesting a page without the /slug:slug/ part being passed http://127.0.0.1:8000/project/ (slug part missing). Request http://127.0.0.1:8000/project/slug-name (replace slug-name with a valid slug) and see if it works.
Also see Razensteins answer
The error message has the following reason:
you make a call to "http://127.0.0.1:8000/project/"
your path statement is routing it to 'pages.views.ServiceDetail' - with url parameter slug="project"
path('<slug:slug>/', views.ServiceDetail.as_view(),
Inheritance of ServiceDetail -> DetailView -> BaseDetailView -> SingleObjectMixin (among others..)
as you make a GET request, method get() in BaseDetailView is called:
def get(...)
self.object = self.get_object()
method get_object() in SingleObjectMixin
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
queryset.get() tries to find an item with slug="project" which does not exist in database and handles the resulting excpetin whit the 404 response that you get as error message
So to avoid that the call to "http://127.0.0.1:8000/project/" is going to be routed by
path('<slug:slug>/', views.ServiceDetail.as_view().....
you need to change the order of paths:
path('project/<slug:slug> ....
path('<slug:slug> ....
and make a call like "http://127.0.0.1:8000/project/your_project_slug"
With you current order, 'project' is interpreted as slug, because paths are matched one after the other.

How to call posts comments from an api

Currently I have the following Models:
class Post(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200, blank=False, null=False)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False)
text = models.TextField(max_length=1000)
and these ModelViewSets:
class PostViewSet(ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
class CommentViewSet(ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
my question is how can I retrieve comments from a post or add new comments in a post with urls like this:
GET /posts/{id}/comments
currently I get the comments this way:
GET /comments/{id} #comment Id, not post id.
current urls.py:
from rest_framework.routers import DefaultRouter
from .views import PostViewSet, CommentViewSet
router = DefaultRouter()
router.register(r'post', PostViewSet, basename='posts')
router.register(r'comments', CommentViewSet, basename='comments')
urlpatterns = []
The first step is to create your view, In this case, you will pass the postId on the URL, this argument will be available inside your view using self.kwargs[] . The get_queryset will return a queryset where you can write any logic, and serialize him.
class MessageList(generics.ListAPIView):
serializer_class = CommentSerializer
def get_queryset(self):
return Comment.objects.filter(post=self.kwargs['post_id'])
Another get_querysetoption is to get your post and then return the massages.
def get_queryset(self):
return Post.objects.get(pk=self.kwargs['post_id']).comment_set.all()
Map this view to an URL, note that the name of the variable are the same used on the view.
path('posts/<post_id>/comments/', MessageList.as_view()),

django.db.utils.IntegrityError: UNIQUE constraint failed:

I am making review api with django, but I have a problem.
models.py
from django.db import models
import uuid
# Create your models here.
from django.utils.text import slugify
class buildingData(models.Model):
building_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(unique=True, default=uuid.uuid1)
building_loc = models.CharField(max_length=50)
building_call = models.CharField(max_length=20)
building_time = models.CharField(max_length=50)
def save(self, *args, **kwargs):
self.slug = slugify(self.building_name)
return super().save(*args, **kwargs)
class reviewData(models.Model):
building = models.ForeignKey(buildingData, related_name='reviews', on_delete=models.CASCADE, null=False, blank=False)
review_content = models.TextField()
star_num = models.FloatField()
urls.py
from django.contrib import admin
from django.urls import path
from crawling_data.views import ReviewListAPI
from crawling_data.views import BuildingInfoAPI
urlpatterns = [
path('admin/', admin.site.urls),
path('api/buildingdata/', BuildingInfoAPI.as_view()),
path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view())
]
I am collecting data with crawling, but...
django.db.utils.IntegrityError: UNIQUE constraint failed: crawling_data_buildingdata.slug
This error occurs.
I've tried deleting migrate file and migration again, but still doesn't work.
Is there any problem on my code or is there other way to solve this?
That is because the uuid1 is generated from your machine ID and time stamp and the machine ID in your case remains constant, that's why they look pretty similar at the end. You may use uuid4() to get a random unique UUID.
Answer from #ZdaR in this answer
You should change the first model to this:
class buildingData(models.Model):
building_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(unique=True, default=uuid.uuid4)
building_loc = models.CharField(max_length=50)
building_call = models.CharField(max_length=20)
building_time = models.CharField(max_length=50)
Also you can use your slug as primary key with this:
slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Edited:
I see your save function. in your save function you should remove the slug assignment. Or change it to self.slug = None. If you want to have a slug from the building name you must use TextField or CharField in the model:
slug = models.TextField(unique=True, default=uuid.uuid4)

NOT NULL constraint failed: complaint_complaint.resident_id

I am writing an app in which people can submit their complaints related to some issues.
After the form is submitted, it is supposed to redirect to the page where the details of the complaint are mentioned like area of the complaint, title, description etc.
But after the form is submitted, it throws IntegrityError.
I read about it and went through some of the solutions:
Someone suggested that I delete some past migrations and run them again. I cleared the migrations, ran them again and made some posts through the admin but it is throwing the same error.
Some posts suggest that null=True, blank=True should be added but I do not understand where they should be added in my case. I also don't want to add null=True, blank=True because I don't want any field to be left blank.
Below is my models.py:
from django.db import models
from django.urls import reverse
# Create your models here.
class Complaint(models.Model):
""" Details of the complaint """
resident = models.ForeignKey('auth.User', on_delete=models.CASCADE)
AREA = [('PL', 'Plumbing'), ('EL', 'Electricity'), ('CP', 'Carpenter'), ('CO', 'Construction'), ('DS', 'Disputes'), ('OT', 'Other'),]
matter = models.CharField(max_length=2, choices=AREA)
title = models.CharField(max_length=200)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('comp_detail', args=[str(self.id)])
Below is my urls.py which I created in my 'complaint':
Note - I used class-based views in my views.py
from django.urls import path
from .views import CompListView, CompDetailView, CompCreateView
urlpatterns = [
path('comp/new/', CompCreateView.as_view(), name='comp_new'),
path('comp/<int:pk>/', CompDetailView.as_view(), name='comp_detail'),
path('', CompListView.as_view(), name='home'),
]
Some help will be appreciated.

how to create django web page similar to admin site

I am a beginner in django and i want to create a new web page which i can edit and add to a database model like the admin site page but this will be in the website to enable the user to control it and i can extend my base.html page in it, I search for it and i didn't find a simple solution like admin base site that enable me to control the models, i tried to send all objects of this model in the context but i cant add or edit it in the database model, just i can view it only.
can any one help me? thanks.
This is my models.py for this web page:
from django.db import models
class Email(models.Model):
type = models.CharField(max_length=200, null=True, blank=True)
subject = models.TextField()
from_email = models.CharField(max_length=200, null=True, blank=True)
to_email = models.CharField(max_length=200, null=True, blank=True)
reply_to_email = models.CharField(max_length=200, null=True, blank=True)
body_text = models.TextField()
body_html = models.TextField()
status= models.CharField(max_length=200, null=True, blank=True,default='waiting')
def __unicode__(self):
return self.to_email
class EmailTemplate(models.Model):
template_name=models.CharField(max_length=200)
subject = models.CharField(max_length=200)
from_email = models.CharField(max_length=200, null=True, blank=True)
reply_to_email = models.CharField(max_length=200, null=True, blank=True)
body_text = models.TextField()
body_html = models.TextField()
def __unicode__(self):
return self.template_name
my views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from survey.models import *
from user_management.models import Candidate
from django.contrib.auth.decorators import login_required
from django import forms
import settings
from emailtemplates import models
from email_sender.models import *
from report.pdf import DrawarmPDF,send_pdf_in_email
from decorators import superuser_required
#login_required
#superuser_required()
def home(request):
query_results = EmailTemplate.objects.all()
return render_to_response('emailtemplates/emailtemplates.html',
{"query_results":query_results},
context_instance=RequestContext(request))
you need add action for POST method:
def home(request):
if request.method == 'POST':
# ^^^^^^
# do save action code
query_results = EmailTemplate.objects.all()
return render_to_response('emailtemplates/emailtemplates.html',
{"query_results":query_results},
context_instance=RequestContext(request))
And you may use forms for save action, more details here: forms view
And it be good to read about form class view class-based-views

Categories

Resources