Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django Page loading issue
Why my Python Django WebApp always loads the same page but with different URLs ? I have templates for the requested url too . But Django loads only my home page . Why ? -
CSRF cookies not set - React, JWT, Django
I'm rather confused regarding the following error: "Forbidden (CSRF cookie not set.)". This error is received during attempting to logout, login, signup. The problem is similar to this post which was never answered: Django (DRF) & React - Forbidden (CSRF cookie not set) I used axios and JWT for handling authentication. I have two git branches to track this error. On the master branch I have the original authentication setup. It works just fine, no errors. On a second branch (we'll call it branch2), I get the error specified above. The only difference between the two branches is that I ran the cmd django-admin startapp books. I then proceeded to setup the model, serialization, views, and urls for the books app on branch2. I also added it to the settings.py installed apps. Other than that, nothing has changed. Therefore the authentication process should remain the same. React handles the looks of the website but the default django ip is used for development: http://127.0.0.1:8000/ I run npm run build in order to update react's current build. Book View (branch2) # Book Imports from .serializers import BookSerializer from .models import BookModel ##### Book API ##### # A Complete List of ALL Projects … -
Django image css
I can't get django to use my css file. I've done a lot of sifting through various sites and tutorials but with no luck. Most of them say to change your STATICFILES_DIRS while some don't mention it at all. I've tried changing it to about every variant that could match my style.css location as well as copying and pasting the css file into a bunch of locations which might match '/static' but nothing works! for STATICFILES_DIRS I have tried: os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static/store'), os.path.join(BASE_DIR, 'staticfiles'), os.path.join(BASE_DIR, 'staticfiles/store'), I also found the file manually and copied the location into a string like so: '...Desktop/project/staticfiles/store', I have also tried similarly playing around with the STATIC_URL and STATIC_ROOT to no avail. My tree looks like this: project static store style.css staticfiles store style.css store static store style.css staticfiles store style.css and my template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block head %} <link rel='stylesheet' type='text/css' href='{% static "store/style.css" %}'> {% endblock %} </head> <body> {% block body %} {% endblock %} </body> </html> I also tried changing static in the template to staticfiles I already wasted hours on this problem and am tired and frustrated, please help! -
Avoid repeating queries in several SerializeMethodFields using Django REST Framework
I'm trying to optimize database queries in my DRF app. To do that I'm trying to avoid repeating queries in my serializers. Supose I have a ModelSerializer like this: class BookSerializer(serializers.ModelSerializer): genres = serializers.SerializerMethodField(read_only=True) out_of_stock = serializers.SerializerMethodField(read_only=True) price = serializers.SerializerMethodField(read_only=True) class Meta: model = Recipe fields = ['id', 'title', 'genres', 'out_of_stock', 'price'] def get_genres(self, obj): # Complex query here ... location_id = self.context['request'].query_params.get('location', None qs = Book.objects.annotate(min_price=Min('price')).filter( (Q(supplier__location_id=location_id) | Q(supplier_id__isnull=True)) & Q(name__in=collection_names), min_price__lte=F('price')).order_by() genres_ids = qs.filter(is_out_of_stock=False).values_list('genres__id', flat=True) genres = Genre.objects.filter(id__in=genres_ids) return GenreSerializer(genres, many=True).data def get_is_out_of_stock(self, obj): # Same complex query here ... location_id = self.context['request'].query_params.get('location', None qs = Book.objects.annotate(min_price=Min('price')).filter( (Q(supplier__location_id=location_id) | Q(supplier_id__isnull=True)) & Q(out_of_stock=False) & Q(name__in=collection_names), min_price__lte=F('price')).order_by() return qs.filter(is_out_of_stock=True).exists() def get_price(self, obj): # Another same complex query here ... location_id = self.context['request'].query_params.get('location', None qs = Book.objects.annotate(min_price=Min('price')).filter( (Q(supplier__location_id=location_id) | Q(supplier_id__isnull=True)) & Q(out_of_stock=False) & Q(name__in=collection_names), min_price__lte=F('price')).order_by() ........ ........ return ...... As you can see I need to pass some query_params to filter the queryset. Do you know what could I do to avoid repeating each query to retrieve all the serializer fields? Thank you in advance. -
Creating simple like button
Hi im developping a blog app and i am creating a simple like button for the post idintified by it's pk where the link is located in a form but it ran into an error. NoReverseMatch at /single_post/8/ Reverse for 'like_post' not found. 'like_post' is not a valid view function or pattern name. my views.py for the detail view and the like button view def post_detail(request, pk): post = Post.objects.get(id=pk) context = { 'post': post, } return render(request, 'news/post_detail.html', context) def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return(HttpResponseRedirect(reverse('single_post', args=[str(pk)] ))) models.py class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='img/', default='img/default.jpg') author = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) credit = models.URLField(blank=True, null=True) likes = models.ManyToManyField(User, related_name='daily_posts') def __str__(self): return self.title in the detail views the form and the link <form action="**{% url 'like_post' post.pk %}**" method="POST"> {% csrf_token %} <button class="btn btn-primary btn-sm" type="submit", name="post_id", value="{{ post.id }}">Like</button> </form> and the error i run to everytime i hit like. NoReverseMatch at /single_post/8/ Reverse for 'like_post' not found. 'like_post' is not a valid view function or pattern name. i cannot identify what seems to be the issue here anyone can help please? -
How to get the username of the current user and assign it to a certain field in a form in django?
This is my models.py file from django.db import models from django.contrib.auth.models import User # Create your models here. class Book(models.Model): category_choices =( #("Undefined","Undefined"), ("Action", "Action"), ("Romance", "Romance"), ("Horror", "Horror"), ("Comedy", "Comedy"), ("Adventure", "Adventure"), ("Dramatic", "Dramatic"), ("Crime","Crime"), ("Fantasy","Fantasy"), ) name = models.CharField(max_length=100) author = models.CharField(max_length=100, null=True) content = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) image = models.ImageField(upload_to= 'photos/%y/%m/%d', blank = True) category = models.CharField( max_length = 20, choices = category_choices, #default = 'Undefined' ) publication_year = models.CharField(max_length=4, null=True) ISBN = models.CharField(max_length=13, null=True, unique=True) active = models.BooleanField(default= True) def __str__(self): return self.name class Borrow(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL) period = models.PositiveIntegerField(default=0) id = models.IntegerField(primary_key=True) def __str__(self): return str(self.book) and this is my forms.py file from django import forms from .models import Borrow class BorrowForm(forms.ModelForm): class Meta: model = Borrow fields = ('name', 'book', 'period') and this is the function in my views.py file that renders the form @login_required def borrowing(request): momo = BorrowForm() if request.method == 'POST': momo = BorrowForm(request.POST) if momo.is_valid(): instacne = momo.save(commit=False) instacne.user = request.user.username instacne.save() return redirect('profile') return render(request, 'books/book.html', {'momo': momo}) The role of this function is to render that form and to save the data that user will enter and … -
User created from a custom serializer built for django default user model can't log in to django admin site
I have a serializer, which was built for Django's default model as defined below. However, users created cannot login to the admin site, even when I make the user a staff using the superuser. The error says "incorrect username and password". Is there anything I'm not doing right. I have the serializer,viewset and the url defined below. Any help will be much appreciated. # serializer.py class CreateUserSerializer(serializers.ModelSerializer): password1 = serializers.CharField( style={'input_type': 'password'}, write_only=True ) password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True ) def validate(self, data): """Check if password1 and password2 are the same""" if data['password1'] != data['password2']: raise ValidationError('passwords do not match') try: """Check if valid password was provided""" validators.validate_password(data['password1']) except ValidationError as e: errors = list(e.messages) raise ValidationError(errors) return data class Meta: model = User fields = ( 'username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) def save(self): """Create user and sets password""" password = self.validated_data['password1'] self.validated_data.pop('password1') self.validated_data.pop('password2') user = User.objects.create_user(**self.validated_data) user.is_active = False user.set_password(password) user.save() return user class UserViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() def get_serializer_class(self): if self.action == 'create': return serializers.CreateUserSerializer return serializers.UserSerializer router = routers.DefaultRouter() router.register( 'users', views.UserViewSet, basename='user' ) urlpatterns = router.urls -
Displaying data from a specific page in django
I am creating a donation application that allows donors to donate stuff. I have a screen, called available supplies.html which renders out all of the donations from the database using a for loop. Each donation is displayed in a user-friendly way, and contains a button that allows them to see details about that specific donation. When the button is clicked, the user is redirected to a page, and on this page I want to render out detail about the donation they clicked on. For example if the user clicked on the donation titled Apple, it would bring up data from my model with details about that particular apple. Can someone please help me accomplish this? My code is down bellow. Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (this is where I want to render out the model data): {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> … -
module parse failed: Unexpected token (10:11)
I'm new to programming and i'm following a tutorial (https://www.youtube.com/watch?v=YEmjBEDyVSY&t=589s) However, i keep getting the following error: ERROR in ./src/components/app.js 10:11 Module parse failed: Unexpected token (10:11) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | | render() { > return <h1>{this.props.name}</h1>; | } | } @ ./src/index.js 1:0-38 webpack 5.45.1 compiled with 1 error in 103 ms When i run: npm run dev App.JS import React, { Component } from "react"; import { render } from "react-dom"; export default class App extends Component { constructor(props) { super(props); } render() { return <h1>{this.props.name}</h1>; } } const appDiv = document.getElementById("app"); render(<App name='matt' />, appDiv); -
How to set max length on integerfield Django Rest
Okay so I need to have my field have a maximum of 10 integers allowed to be entered. I tried MaxValueValidator but i figured out that this just needs a value thats lower than the set value. I want to be able to enter a maximum of 10 numbers, so it should work if i enter just one number, but also if I enter 10. Code ex: class Random(models.Model): code=models.IntegerField -
Annotate + Distinct Not Implemented, Count a Distinct Subquery
I have two models, RetailLocation and Transaction, which share a one-to-many relationship respectively. I trying to annotate the total number of days (Count) a RetailLocation has any number of Transactions for. In doing so, I am filtering the Transaction.date field to just Date instead of Datetime, and trying to SELECT DISTINCT dates, but am running into an error "NotImplementedError: annotate() + distinct(fields) is not implemented." Models class RetailLocation(models.Model): name = models.CharField(max_length=200, null=True) class Transaction(models.Model): date = models.DateTimeField(null=True) r_loc = models.ForeignKey(RetailLocation, null=True, on_delete=models.SET_NULL) Attempted Code test = RetailLocation.objects.annotate( days_operating=Subquery( Transaction.objects.filter(r_loc=OuterRef("pk")) .distinct('date__date') .annotate(count=Count('pk')) .values('count') ) ) I tried to reference this solution in combination with an earlier post solved by Willem, but using distinct seems to cause the NotImplementedError referenced above. I believe there also might be a solution using Count( , distinct=True), but it wouldn't help unless I could distinct on date__date, as I am only trying to find days that any number of Transactions occurred on. Thank you very much for your time. -
Stop Celery caching Django template
I have Django 3.24, celery 4.4.7 and celerybeat 2.2.0 setup via the RabbitMQ broker. I have have a celery task that renders a Django template and then sends it to a number of email recipients. The Django template is dynamic in as much as changes can be made to it's content at any time, which in turn rewrites the template. The trouble is that on occasions, I have to restart celery to get it to re-read the template. My question is, is there any way of forcing celery to reread the template file, without requiring a full celery restart? celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backoffice.settings') app = Celery('backoffice') default_config = 'backoffice.celery_config' app.config_from_object(default_config) app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) celery_config.py from django.conf import settings broker_url = "amqp://someusername:somepassword@webserver:5672/backoffice" worker_send_task_event = False task_ignore_result = True task_time_limit = 60 task_soft_time_limit = 50 task_acks_late = True worker_prefetch_multiplier = 10 worker_cancel_long_running_tasks_on_connection_loss = True -
How to Improve IFrame Loading Speed?
I am working on a project for a client who is using Square booking and would like that embedded into their website. I have added an IFrame on the site which points to their booking page on Square's website, however this IFrame loads painfully slow. I am using Django templates for the front end of the website. Is there any way to make this IFrame load faster? Is there a way to load it in the background of the homepage so that it is cached when the user goes to the booking page? -
Issue with Django blog tutorial on youtube, class view and GET method not clear
Was following a youtube tut regarding a django blog but ran into an issue. Link to video: https://www.youtube.com/watch?v=CnaB4Nb0-R8&t=607s The tut says to use the following code in the blog app's view.py file: from django.views.generic. import ListView, DetailView from .models import Post from django.views import View class Blogview(ListView): model = Post template_name = 'blog.html' When I tried to implement the code this way, I was given an error referencing something to do with GET. Looking into it, I modified my code to look like the following: from django.shortcuts import render from .models import Post from django.views import View class Blogview(View): model = Post template_name = 'blog.html' def get(self, request): return render(request,'blog.html') The above version of code works now for me. I find it frustrating why I couldn't figure out why the youtube tutorial code seemed to be much simlified and worked just as expected, whereas when I tried it word for word it failed and had to include a reference to the get method. I'll let you know I did simplify my version of the template file 'blog.html' to be something as simple as a single line of text whereas the tutorial had a template file which took all the posts … -
(index):217 Uncaught TypeError: Cannot read property 'innerHTML' of null
receving error message. Ive tried everything i can think of and being a novice im at a loss. please help DisplayCart(cart); function DisplayCart(cart){ var cartString = ""; cartString += "<h5>This is your cart</h5>"; var cartIndex = 1; for(var x in cart){ cartString += cartIndex; cartString += document.getElementById("nm"+x).innerHTML + "QTY:" + cart[x]; cartIndex += 1; } -
Rendering django model data in html
I am creating a donation application that allows donors to donate stuff. I have a screen, called available supplies.html which renders out all of the donations from the database using a for loop. If someone wants the stuff in the donation, they can click on a view button and are redirected to a page that contains details about the donation. I am struggling with rendering these details out, because I need specific data. Is there any way I can do this? Basically, I want to display data for the donation the user clicked on. My code is down bellow. Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (I want the donation data that the user clicked on to render here) {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Category</strong></div> <div style="flex:1"><strong>Quantity</strong></div> </div> <div class="cart-row"> <div style="flex:2"><img class="row-image" src=""></div> <div style="flex:2"><p>Title</p></div> <div style="flex:1"><p>$20</p></div> <div style="flex:1"> … -
How does one count a foreign key item, esp 'author' created with Django's User model?
Need help getting a better grip with 1) accessing and counting foreign key items in Django and 2) counting foreign key item that is created through Django's built-in User: #1) The answer here suggests using Django's annotate function: eg. questions = Question.objects.annotate(number_of_answers=Count('answer')) (question being a foreign key item to answer). But it is not clear to me where this line belongs to (in the case of the example, question or answer), or which part of an app-models.py or views.py. I tested in both models.py and views.py Here are my models (only the essential lines here): class Post(models.Model): post = models.TextField(max_length=1000) author = models.ForeignKey(User, related_name="author", on_delete=models.CASCADE) class Comment(models.Model): comment = models.TextField(max_length=1000) commenter = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, related_name='posts', on_delete=models.CASCADE, default=None, null=True) #2) How does one access a foreign key item created using Django's built-in model, User? Should I have created a model called "Author" first? -
How do I make the django admin site rely on my custom Django Rest Framework Token Authentication?
Throughout development of my application, the authentication has worked great. Using DRF I overrode DRF's TokenAuthentication to provide an expiring token, and then overrode ObtainAuthToken to create the authentication post request view. Now I'm trying to launch the application into production with DEBUG=False. The application seems to be running fine, but the django admin site will not let me log in to my super user (yes I created it with createsuperuser and have verified it exists in the database). The error I get back is: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This confused me because I'm using Token authentication and not Sessions. In my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'custom_auth.authentication.ExpiringTokenAuthentication' ] } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I believe the django.middleware.csrf.CsrfViewMiddleware was put in there by default when I created the application, and I assume this … -
customer Select a valid choice. That choice is not one of the available choices
please i want someone to help me solve this problem. if there's a better way i can write the codes, i will really appreciate. what i want is for the user to make order and get redirected to a page where the user will see all his orders . please someone should help out error message : customer Select a valid choice. That choice is not one of the available choices client model file from django.db import models # Create your models here. class ClientJob(models.Model): STATUS = ( ('Pending', 'Pending'), #('On-going', 'On-going'), ('Completed', 'Completed'), ) customer = models.ForeignKey('accounts.Customer', null=True,blank=True, on_delete= models.SET_NULL,related_name='client') job_name = models.CharField(max_length=50,unique =False) text_description = models.CharField(max_length=150,null=True) location = models.ForeignKey('accounts.Area' ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=200,unique =False) phone =models.CharField(max_length=15,unique =False) email = models.EmailField(unique = False) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS,default='Pending') def __str__(self): return self.job_name class Meta: verbose_name_plural = "Client Job" client forms.py file from django.db.models import fields from django.forms import ModelForm from django import forms from django.contrib.auth.models import User from .models import * class ClientJobForms(ModelForm): class Meta: model = ClientJob fields = ['job_name','text_description','location','address','phone','email','status','customer'] #fields ="__all__" def __init__(self, *args, **kwargs): super(ClientJobForms, self).__init__(*args, **kwargs) self.fields['location'].empty_label ='Your location' client admin file from django.contrib import admin from .models import … -
SimpleJwtAuthentication django
Does simplejwt authentication works with custom user model .if not ,is there any way to achieve. models.py class user_model(models.Model): username=models.CharField(max_length=200,blank=True,unique=True) email=models.CharField(max_length=200,blank=True) password=models.CharField(max_length=200,blank=True) age=models.CharField(max_length=200,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username -
Is there a way to submit multiple forms with a single button and unique hidden values?
Note: I have seen some posts that are quite similar to mine but I don't think those solutions help in my use case. My website (made using Django) has a page for collecting dues payments. There is one page per family, in which there will be multiple dues to be paid by each member. Currently, I have one submit button to each due as you can see in the code below. {% for due in dues %} <tr> <td>{{due.0}}</td> <td>{{due.1}}</td> <td>{{ due.3}}</td> <td>{{ due.4 }}</td> <td>{{ due.5 }}</td> <td><form action="/dues/?family-dues={{ familyprofile }}" method="POST" id= "dues-payment"> {% csrf_token %} <input type="text" placeholder="Enter Amount" name="amount"> <input type="hidden" value="{{due.2}}" name="due-id"> <input type="hidden" value="{{due.0}}" name="member-id"> <input type="hidden" value="{{duefamily.0}}" name="family-id"> <button id="submit-payment">Pay</button></form></td> </tr> {% endfor %} The issue with this is that, only one payment can be done at a time. Is there a way where I can instead submit all the forms in one go. So that the cashier can just enter the appropriate payments in each textbox and when its submitted all the textbox values(paid amount) along with the due id be returned in one go? Current Scenario Due ID 1 textbox(Value is 40) Pay Button Due ID 2 textbox(Value is 80) Pay … -
How can I access an attribute of a model which is a foreignkey to another model in the views.py file
For example I have two models .Brand model which is a foreign key to another model Item. The Brand model has an attribute best_seller which is a boolean field recording whether a certain brand of items is a best seller. In my views I want to filter only the items whose brand is a best seller.How can I do this This is how my models.py looks like class Brand(models.Model): title = models.CharField(max_length=100) best_seller = models.BooleanField(default=False) def __str__ (self): return self.title class Item(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) new_price = models.DecimalField(max_digits=7, decimal_places=2) image = models.ImageField(upload_to='static/images') old_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) slug = models.SlugField() description = models.TextField() featured = models.BooleanField(default=False) def __str__ (self): return self.title Then this the views.py file def home(request): brand = Brand.objects.filter(best_seller=True) bests = Item.objects.filter(brand=True).order_by('-id')[:12] context = { 'items': items, 'bests': bests } return render(request, 'home.html', context) After doing this there's nothing being rendered on the browser -
Nested fields/objects creation with DRF
It's me again with questions about the polls API I'm working on. I have three models: Poll, Question and Choice. from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Poll(models.Model): title = models.CharField(max_length=200, verbose_name="Naslov ankete") description = models.TextField(verbose_name="Opis ankete") author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polls", verbose_name="Autor") pub_date = models.DateTimeField(auto_now_add=True, verbose_name="Datum objavljivanja") class Meta: ordering = ["pub_date", "title"] verbose_name = "Anketa" verbose_name_plural = "Ankete" def __str__(self): return self.title class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions", verbose_name="Anketa") question_text = models.CharField(max_length=200, verbose_name="Tekst pitanja") class Meta: # ordering = ["question_text"] verbose_name = "Pitanje" verbose_name_plural = "Pitanja" def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices", verbose_name="Pitanje") choice_text = models.CharField(max_length=200, verbose_name="Tekst opcije") votes = models.IntegerField(default=0, verbose_name="Glasovi") class Meta: # ordering = ["-votes"] verbose_name = "Opcija" verbose_name_plural = "Opcije" def __str__(self): return self.choice_text Whatever I put in the serializers, I can't achieve the creation of questions and choices at the same time with the poll. How should my serializers look like if I want to use the following JSON, but still be able to create questions and choices independently? { "title": "Favorite destinations", "description": "A few questions about traveling", "questions": [ {"question_text": "Which destination seems better for you?", "choices": [{"choice_text": "London"}, {"choice_text": … -
admin-path is removed from url, but can still be accessed (Django)
I have a django application of which I want to remove the Admin-access in production. Because of that I've removed the admin-url from the url.py file, but if I go to myapp.com/admin/login it still allows me to log in. Is there a way to disable admin-login in production?` -
Django Changing HTML Template Not Reflecting
I'm new to Django, I have created a webportal and recently came to know their is an issue in the portal. After changing the html content, its not reflecting the content in portal, still displaying old html data. Could someone please tell me, what needs to be done. Note: I have reloaded django from command prompt and verified, but getting the same issue, Thank You!!