Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to deploy django project on aws?I already tried with nginx,gunicorn but it was not working.Need some help in this
While using aws to deploy django project with nginx,gunicorn but it was not working so how deploy it in properly.need some help. -
How to use django annotate to compare current date with other date in models
I want to get the days between the current time and another date. Here is the command what I used: employees = Employee.objects.annotate( duration=ExpressionWrapper(datetime.now().date() - F('start_working_date'), output_field=DurationField()) ) But the result I got( employee.duration) is 0. for employee in employees: employee.duration And here is my models: class Employee(models.Model): name = models.CharField(max_length=30) start_working_date = models.DateField() -
How to get uploaded file name from django id
I simply wanted the file exact file name which i have been uploaded so that i can read the whole file and show content on HTML page... class newcodes(models.Model): user_id = models.AutoField fullname = models.CharField(max_length=200) codefile = models.FileField(upload_to ='programs/')//her is my codefile location in models Here is my function for reading text but i cant get name of uploaded file so i can't read the file def showcode(request,id): programs=newcodes.objects.filter(id=id) print(programs) # f=open('media/') return render(request,"Codes.html") -
Django Modelviewset Filtering
I have two models Category & Post. In Post model there is foreign key of category. Based on category I want to filter the data to show the post category wise. Here's my code. models.py class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='news', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Category" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): NEWS_TYPE = (('Images','Images'),('Multi-Images','Multi-Images'),('Image-Text','Image-Text'), ('Audio-Video','Audio-Video'),('Audio-Video-Text','Audio-Video-Text'),('Audio','Audio'), ('Audio-Text','Audio-Text')) POST_STATUS = (('Pending','Pending'),('Verified','Verified'),('Un-Verified','Un-Verified'), ('Published','Published'),('Mint','Mint')) category = models.ForeignKey(Category, related_name='Category', on_delete=models.CASCADE) post_type = models.CharField(max_length=100, verbose_name='Post Type', choices=NEWS_TYPE) title = models.TextField(verbose_name='News Title') content = models.TextField(verbose_name='News Content') hash_tags = models.CharField(max_length=255, verbose_name='Hash Tags') source = models.CharField(max_length=255, verbose_name='News Source') author = models.ForeignKey(User, related_name='Post', on_delete=models.CASCADE) views = models.ManyToManyField(User,related_name='Views', blank=True) likes = models.ManyToManyField(User, related_name='Likes', blank=True) dislikes = models.ManyToManyField(User, related_name='Dislikes', blank=True) status = models.CharField(max_length=20, verbose_name='Status', choices=POST_STATUS, default='Pending') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return (self.post_type)+ '-' +self.title serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Post fields = ('category','post_type','title','content','hash_tags','source','author','views', 'likes','dislikes','status') views.py class CategoryAPI(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer class PostAPI(viewsets.ModelViewSet): serializer_class = PostSerializer def get_queryset(self): news_post = Post.objects.all() … -
Why is it going to anaconda how do I fix i
enter image description here I'm new so you have to press on the link. Pls help -
How get selected value in bootstrap V5 select with python
I am using Class Based Views in django... Then my model is: class Survey(Base): description = models.CharField('Description', max_length=50, unique=True) item1 = models.CharField('Item1', max_length=50) item2 = models.CharField('Item2', max_length=50) ... class Meta: verbose_name = 'Survey' def __str__(self): return self.description Now I am reading database data for fill in select and works fine. How I get this select item for fill table fields? info.html <div class="col-12"> <div class="card card-chart"> <div class="card-header "> <div class="row"> <div class="col-sm-4 text-left"> <h2 class="card-title">Informations</h2> <option selected>choose a option</option> {% for s in survey %} <option>{{s.description}}</option> {% endfor %} </select> </div> <!-- of course, in this moment variable [s] not exist --> <div class="col-sm-8 text-right"> <table class="table"> <tbody> <tr> <td>item 1</td> <td>item 2</td> </tr> <tr> <!-- want fill this fields with select item above--> <td>{{s.item1}}</td> <td>{{s.item2}}</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> -
How to send mail to the post author when got new comment in django rest framework through serializer?
I am trying to build an API where students will ask questions and the teacher will answer that question. For asking questions and answering I am using the blog post way. Now, my problem is I am trying to send mail from the serializer. But when I want to detect the post author I am unable to do that. I can send selected users but not from the model. If anyone can help me with that it will be so helpful. Thanks a lot. these are the add_question model and answer the question model --- class add_question(models.Model): title = models.CharField(max_length=250, blank=False) description = models.TextField(blank=True, null=True) is_answered = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) STATUS = ( ('Published', 'Published'), ('Suspended', 'Suspended'), ('Unpublished', 'Unpublished'), ) status = models.CharField(choices=STATUS, default='Published', max_length=100) RESOLUTION = ( ('Resolved', 'Resolved'), ('Unresolved', 'Unresolved'), ) resolution = models.CharField(choices=RESOLUTION, default='Published', max_length=100) def __str__(self): return self.title class add_questionFile(models.Model): question = models.ForeignKey(add_question, on_delete=models.CASCADE, related_name='files') file = models.FileField('files', upload_to=path_and_rename, max_length=500, null=True, blank=True) class submit_answer(models.Model): description = models.TextField(blank=False, null=False) is_deleted = models.BooleanField(default=False) rating = models.FloatField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) question_id = models.ForeignKey(add_question, blank=False, on_delete=models.CASCADE) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) class submit_answerFile(models.Model): answer … -
Django generic create view . Can we add conditions to save data from the form?
This is what my code looks like and I want to add some condition to the Borrower create view like if the stock method of book returns 0 then don't list that book in field while creating a new borrower or if it isn't possible at least throw some error while adding borrower to that book. models.py: class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=100) summary = models.TextField( max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN', max_length=13, help_text='13 Character https://www.isbn-international.org/content/what-isbn') genre = models.ManyToManyField( Genre, help_text="Select a genre for this book") language = models.ForeignKey( 'Language', on_delete=models.SET_NULL, null=True) total_copies = models.IntegerField() pic = models.ImageField(blank=True, null=True, upload_to='books') def stock(self): total_copies = self.total_copies available_copies = total_copies - \ Borrower.objects.filter(book=self).count() if available_copies > 0: return available_copies else: return 0 def __str__(self): return self.title class Borrower(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) student = models.ForeignKey('Account', on_delete=models.CASCADE) book = models.ForeignKey('Book', on_delete=models.CASCADE) issue_date = models.DateField( null=True, blank=True, help_text='YYYY-MM-DD', default=date.today) return_date = models.DateField( null=True, blank=True, help_text='YYYY-MM-DD') def __str__(self): return self.student.name.title()+" borrowed "+self.book.title.title() def fine(self): today = date.today() fine = 0 if self.return_date <= today: fine += 5 * (today - self.return_date).days return fine views.py: class BorrowerView(LoginRequiredMixin, ListView): model=Borrower context_object_name='borrowers' template_name … -
How to insert raw html into form when creating a page using django
I want to include things like hyperlinks, quoting, italicized text, etc. into my pages I post on the site I wrote with django but it seems to escape my code. What can I do to add this feature? Has someone else already done something I could just use? -
Error: Has No Attribute "Getlist" Error When Making Request in Django
When I run the tests to make requests to the webpage on Django, the tests run fine and have expected behavior. However, when the same code is run when I'm making a request outside of the testing environment in Django, running: request.data.getlist("insert_key_here") where "insert_key_here" is a key from a key-value pair where the value is a list, I get this error: 'dict' object has no attribute 'getlist' When I try to run this instead request.data["insert_key_here"] I get an error that a string's indices must be an int. Does this mean that the request.data is somehow a string? If it was just grabbing the first value in the list like how it would if you used .get() instead of .getlist(), I don't know that I'd be getting this error just from trying to fetch the value. To give some context, this is an example of the format of the request: { "insert_key_here" : [ "list_item1", "list_item2" ] } I'm not sure why it would work perfectly in the testing environment, but, then, when I run it outside the testing environment, I get that error on that specific line. -
I couldn't able to save my data in to admin. it just redirect me to Home page
This is my View.py code. hear it redirect me to home page and doesn't save my data in to admin panel. **if i indent back else condition Blockquote else: form = OrderForm() return redirect('home') Blockquote it gives me error - ValueError at /orders/place_order/ The view orders.views.place_order didn't return an HttpResponse object. It returned None instead.** def place_order(request, total=0, quantity=0,): current_user = request.user # if cart count is less then 0 or equel to 0, then redirect to shop cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price*cart_item.quantity) quantity += cart_item.quantity tax = (12 * total)/100 grand_total = total + tax if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # store all the information inside belling table data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.provence = form.cleaned_data['provence'] data.zone = form.cleaned_data['zone'] data.district = form.cleaned_data['district'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') data.save() # genarate order no yr = int(datetime.date.today().strftime('%y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = … -
Django how to import custom javascript?
I'm having the weirdest issue yet; I can't request a custom javascript (chart.js) the same way I do another one (main.js); This is how I request the scripts; notice how main.js is in the same folder as chart.js Now, the requests received by Django; notice how main.js is ok, while chart.js is 404: I've tried deleting the __pycache__ folders and restart the server but no go. What could be causing this? -
Protected routes using JWT tokens in NextJS + Django
I'm starting this new NextJS application where I'm using Django as an API. I'm using JWT tokens for authentication/authorization and I wanted to create protected routes. After following a bunch of tutorials, videos and other things online, here's what I came up with: I created an axios instance (api.js) (where I was trying to intercept requests to set the Authorization header): import axios from "axios"; import Cookies from "js-cookie"; const api = axios.create({ baseURL: "http://127.0.0.1:8000/api/", headers: { Accept: "application/json", "Content-Type": "application/json", }, }); api.interceptors.request.use((request) => { const token = Cookies.get("accessToken"); if (token) { api.defaults.headers.Authorization = `Bearer ${token.access}`; } return request; }); export default api; And an AuthService.js (where I set a cookie when l log in): import Cookies from "js-cookie"; import api from "./api"; export const AuthService = { login: async (email, password) => { const { data: token } = await api.post("token/", { email, password }); console.log(token); if (token) { console.log("Got token"); Cookies.set("accessToken", token.access, { expires: 60 }); api.defaults.headers.Authorization = `Bearer ${token.access}`; const { data: user } = await api.get("users/current/"); console.log("Got user", user); return user; } }, logout: async () => { Cookies.remove("accessToken"); delete api.defaults.headers.Authorization; }, getUser: async () => { try { const { data: user } = … -
Django Saving Model Method Property to the Database
I have ModelOne that has a model method, lets say method_that_does_stuff, with the @property decorator that calculates a boolean value, based on the value of ModelThree, which is a ForeignKey of ModelTwo, which is a ManyToMany of ModelOne. I'm trying to make it that when the value of method_that_does_stuff changes, due to changes in ModelThree, it saves the boolean value to ModelOne. Below is my implementation: from django.db import models class ModelThree (models.Model): some_input = models.TextField() model_two = models.ForeignKey(ModelTwo, on_delete=models.CASCADE) class ModelTwo (models.Model): name = models.CharField(max_length=200) class ModelOne (models.Model): name = models.CharField(max_length=200) boolean_field_to_change = models.BooleanField(default=False) model_twos = models.ManyToManyField(ModelTwo) @property def method_that_does_stuff(self): # It does some stuff and returns either True or False, but let's assume True # The True or False return depends on ModelThree's some_input field # If the some_input field doesn't change, then it will stay False return True def save(self, *args, **kwargs): self.boolean_field_to_change = self.method_that_does_stuff super(ModelOne, self).save(*args, **kwargs) However, for some reason, when I run in the Django shell and get all of the ModelOne objects, the method_that_does_stuff will be True, but the boolean_field_to_change will still be its default value of False. I found this solution: Django Model Method or Calculation as Field in Database which is … -
from autoslug import AutoSlugField Not working
please I need help with Python Django stuff I have installed pip install pillow and I need to import it in models.py. When I run this code in command prompt, I get this error[At line:1 char:1 from autoslug import AutoSlugField The 'from' keyword is not supported in this version of the language. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordEx ception + FullyQualifiedErrorId : ReservedKeywordNotAllowed]1 I am using Python 3.10 with Django 4.0.1 on Windows 10 64bits I will appreciate your help to solve this -
Query selector sort
Inbox = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) context['Inbox'] = Inbox Currently I am using this to grab all messages for the currently logged in user. I want to sort it by time and read status. So that the lastest unread message shows up first. models.py class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) subject = models.CharField(default='',max_length=100) text = models.CharField(default='',max_length=4096) time = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) def __str__(self): return '{} to {} :{}'.format(self.sender,self.receiver,self.text) -
I cannot get images to work on my django project(this is my first one and im having trouble)
I have an img folder in the same directory as my html files. I want to put images onto my site but I am doing something wrong. this is the code: {% block a %} <div class="row"> <div class="col-sm-4 center"> <img src="img/img01.jpeg"> </div> </div> {% endblock %} this is what happens when I run the local server. local server this is my file directory file directory -
Difficulty in partial update in DRF
I am learning Django and DRF, I am having issues updating the field expire_on. And there also I have to put the logic to prevent to put the value of expore_on no greater than 7 days from created_on. I am having trouble figuring out how to update the same and write the above logic. I have tried: update function in DRF viewset.Viewset Django Rest Framework not showing form fields for PATCH/PUT request Django REST Framework doesn't display value in PUT form Django form fields not showing up Models class Url_data(models.Model): uri_id = models.AutoField(primary_key=True) actual_url = models.URLField() created_on = models.DateTimeField( auto_now_add=True, editable=False, auto_now=False) expire_on = models.DateTimeField() short_url = models.URLField(max_length=200, editable=False) clicks = models.PositiveBigIntegerField( default=0, editable=True, blank=True) Serializer class Url_dataSerializer(serializers.ModelSerializer): class Meta: model = Url_data fields = '__all__' read_only_fields = ['short_url', 'created_on', 'clicks'] class ExpireDateUpdateSerializer(serializers.ModelSerializer): class Meta: model = Url_data fields = ('expire_on', ) View class UrlList(generics.ListCreateAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = Url_dataSerializer class UrlDetail(generics.RetrieveDestroyAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = Url_dataSerializer class ExpireDateUpdate(generics.UpdateAPIView): queryset = Url_data.objects.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = ExpireDateUpdateSerializer Error 405 Undocumented Error: Method Not Allowed **Response body** { "detail": "Method \"PATCH\" not allowed." } **Response headers** access-control-allow-origin: * allow: GET,DELETE,HEAD,OPTIONS content-length: 42 … -
Can't manage to post an object via axios to django - possibly due to AnonymousUser object?
I'm trying to add a button in React which posts an object to django via axios when a user clicks on it. However, it seems like something's wrong backend. Here's the button: <button id="add-rat" type="button" className="btn homeButton" onClick={ (e) => submit(e) } > Add rat </button> And here's the axios, in the same page: const submit = (e) => { const name = "namee"; const eyeColour = "Red"; const bodyColour = "White"; const bio = "hfff"; const image = "lineart.PNG"; const data = { name: name, eye_colour: eyeColour, body_colour: bodyColour, bio: bio, image: image, }; e.preventDefault(); console.log(data); const token = localStorage.getItem("token"); axios .post("http://127.0.0.1:8000/api/addObject", data, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); }; This is my console output: {name: 'namee', eye_colour: 'Red', body_colour: 'White', bio: 'hfff', image: 'lineart.PNG'} myRats.js:86 {res: 'Error Accured'} (myRats.js:86 btw, is console.log(res.data); ) Here's my view for the object: class AddRat(APIView): def post(self,request): data = request.data user = request.user print(data) try: user = rat( name = data['name'] , body_colour = data['bodyColour'] , eye_colour = data['eyeColour'],user= user, bio = data['bio'] , image = data['image']) user.save() return Response({'res':"Rat Saved Successfully"}) except: return Response({'res':"Error Accured"}) def get(self,request): user = … -
real time chat app with django workds with channels but not after using redis and deploy to heroku
hello I am working on chatting app with django channels works perfectly in localhost but once I used redis and deployed to heroku I can't send anymessage the websocket always close, my settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } I am using redis and postgresql addons, and my Procfile is like this web: daphne myproject.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker --settings=myproject.settings -v2 why it works perfectly in my localhost because I am using only this CHANNEL_LAYERS = { "default": { "BACKEND": 'channels.layers.InMemoryChannelLayer' } } -
Django Models, I have nested categories, what is the best way to make sure that each object will "respond" to it's category and the parent categories?
I have a model for nested categories that I found online and is working really nicely: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) class Meta: unique_together = ('title', 'parent') def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return '/'.join(full_path[::-1]) I also have an another model, "standard" model that has a category field (up to this moment it was simply foreign key). My problem is, what is the "proper" way to make sure that object will respond to more than one category here? I mean, if I have a Fiat/Opel/Ferrari object, and I have categories like that: Means of Transport Land Transport Cars Sea Transport Then I will assign to my "Fiat/Opel/Ferrari" object category "Cars" but I also want it to respond to categories "Land Transport" and "Means of Transport". I am wondering what is the best/most efficient way to do this. Currently I have ideas like: each category have by default empty fields like grandparent, grand-grandparent etc. that I will fill out and add to querying stuff. My Category could be ManytoMany instead of foreign key and I would manually set all the categories. I don't … -
Django rest framework - Foreign key - one to many relation
For my project I need to have a simple process a form => many questions => for each questions a response type => if the response type is a multiple choice, then possible response are in a uniq group. My goal is to be able to push though DRF/Django rest framework the whole initial form. Here are my models: class FormModels(models.Model): class Status(models.IntegerChoices): DRAFT = 1, _("DRAFT") PUBLISHED = 2, _("PUBLISHED") ARCHIVED = 5, _("ARCHIVED") form_name = models.CharField(unique=True, blank=False, null=False, max_length=255) form_model = models.CharField(unique=True, blank=False, null=False, max_length=255) status = models.IntegerField(choices=Status.choices, blank=False, null=False, default=1) def __str__(self): return self.form_name class FormResponseTypeModels(models.Model): class Type(models.IntegerChoices): TEXT = 1, _('TEXT') MULTICHOICE = 2, _('MULTI') type = models.IntegerField(choices=Type.choices, blank=False, null=False, default=1) group = models.IntegerField(blank=False, null=True, default=1) def __str__(self): return str(self.type) class Meta: constraints = [ UniqueConstraint(fields=['group'], name='unique_group') ] class MultipleChoiceDataModels(models.Model): text = models.CharField(blank=False, null=False, max_length=255) value = models.CharField(blank=False, null=False, max_length=255) order = models.IntegerField(blank=False, null=False, default=1) group_refid = models.ForeignKey(blank=False, null=False, default=1, to=FormResponseTypeModels, to_field="group", related_name="groups", on_delete=models.PROTECT) def __str__(self): return self.text class FormQuestionModels(models.Model): form_id = models.ForeignKey(to=FormModels, on_delete=models.PROTECT) form_response_type = models.ForeignKey(to=FormResponseTypeModels, on_delete=models.PROTECT, related_name="test") form_question = models.TextField(max_length=2000) def __str__(self): return self.form_question Here is my serializers.py class FormMultipleChoiceDataSerializer(serializers.ModelSerializer): class Meta: model = MultipleChoiceDataModels fields = "__all__" depth = 10 class FormResponseTypeSerializer(serializers.ModelSerializer): groups … -
Django mod_wsgi daemon mode touch wsgi.py not triggering refresh
I cannot reload django templates by touching the wsgi.py script located in my django application root/application name. The script and project are located under /var/www, so I need sudo to execute touch. I am running production apache2 server running a django website with mod_wsgi in daemon mode. I can collectstatics and make migrations, access database (without permission issues). I can also change the DEBUG flag in the settings. If I touch wsgi.py, it will put the production site into debug as expected, but the htmls are not loaded. Likewise I can update the static files, collectstatics, or modify the underlying models and see the changes live. Likewise I can use the commented code to retrieve what Daemon mode the swerver is running in. Its only the templates causing an issue. The settings file, wsgi.py, statics and python scripts are responded as expected. Has anyone got any idea how to debug this? virtualenv python3.8.12 apache2.4 mod_wsgi compiled for python3.8.12 wsgi.py import os import sys from django.core.wsgi import get_wsgi_application sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/"))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mb.settings') application = get_wsgi_application() #def application(environ, start_response): # status = '200 OK' # if not environ['mod_wsgi.process_group']: # output = u'EMBEDDED MODE' # else: … -
Made a simple blogging site with django, original posts that were made with manage.py exists and resolve, new posts with nginx/uwsgi do not resolve
I wrote a simple django website that seemed to completely work when running it with manage.py. I have since set up the site to run off of nginx/uwsgi and now new posts show up on the front page, but when I try to go to the page to reveal the blog post details I get a Not Found page. Can anyone help me figure out what I have done wrong? Here is my blog/urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.index, name='index'), path('<int:welcome_id>/', views.welcome_detail, name='welcome_detail'), path('blog/<int:category_id>/', views.category, name="category"), path('blog/<int:category_id>/<int:blog_id>/', views.blog_post_detail, name="blog_detail"), ] Here is my blog/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse, Http404 from .models import WelcomePage, BlogPost, Categories def index(request): latest_welcome_message = WelcomePage.objects.order_by('id') latest_blog_posts = BlogPost.objects.order_by('id') categories = Categories.objects.order_by('id') template = loader.get_template('blog/index.html') context = {'latest_welcome_message' : latest_welcome_message, 'latest_blog_posts' : latest_blog_posts, "categories" : categories} return render(request, 'blog/index.html', context) def welcome_detail(request, welcome_id): try: welcome_message = WelcomePage.objects.get(pk=welcome_id) except WelcomePage.DoesNotExist: raise Http404("Question does not exist") return render(request, 'blog/detail.html', {'welcome_message':welcome_message}) def category(request, category_id): try: category = BlogPost.objects.get(categories=category_id) blogs_of_category = BlogPost.objects.all() except BlogPost.DoesNotExist: raise Http404("Blog does not exist") return render(request, "blog/category.html", {"category_id":category_id, "category":category, "blogs_of_category":blogs_of_category}) def blog_post_detail(request, category_id, blog_id): try: blog_post_detail … -
Polymorphic queryset in a Django ListView renders the template as many time as objects have the queryset
I have a polymorphic model using the polymorphic library on Django with one ParentModel and several ChildModel and I want to use the parent model with all his children in a queryset the queryset that I am using in my ListView is something like this <PolymorphicQuerySet [<ChildModel1: model description>, <ChildModel2: model description>]> But when my list view render my template, it renders my template as many time as child objects have if I have one object from ChildModel1, one from ChildModel2, and one from ChildModel3 it renders my HTML three times on the same screen one below another