Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a variable in a {% url %} when `app_name` has been defined
I am having issues trying to use a Django template variable to form a URL in combination with the app_name attribute. Currently, I am using a template variable to form a URL <a href={% url variable_name %}>On our page about {{ variable_name }}.</a> Though I am aware that it is seen as good practice to make a URL more accurate by defining app_name in URLs. e.g. app_name = "name_of_app" Meaning that URLs are then written like: <a href={% url "name_of_app:about" %}>About</a> Is it possible for me to combine my current code with this approach? To use a variable and the app_name attribute? I have experimented with this {% url 'NameOfApp:'this_is_a_variable %}, by putting the quote marks in different places, but no success yet. -
django rest-framework. Expand fields. AttributeError
I have expand fields in my serializers. I send request api/drivers/?expand=tractors__drivers__driver and get error: "Got AttributeError when attempting to get a value for field make on serializer TractorSerializer. The serializer field might be named incorrectly and not match any attribute or key on the TractorDriver instance. Original exception text was: 'TractorDriver' object has no attribute 'make'." Models: class Tractor(BaseModel): ... make = models.CharField("Make", max_length=32) ... class TractorDriver(BaseModel): tractor = models.ForeignKey( Tractor, verbose_name="Tractor", on_delete=models.CASCADE, related_name="drivers", ) driver = models.ForeignKey( Driver, verbose_name="Driver", on_delete=models.CASCADE, related_name="tractors", ) ... Serializers: class DriverSerializer(BaseModelSerializer): class Meta: model = Driver expandable_fields = dict( ... tractors=dict( serializer="safety.api.serializers.TractorSerializer", many=True, ), ... class TractorDriverSerializer(BaseModelSerializer): class Meta: model = TractorDriver expandable_fields = dict( tractor=dict(serializer="safety.api.serializers.TractorSerializer", read_only=True), driver=dict(serializer="safety.api.serializers.DriverSerializer", read_only=True), ) class TractorSerializer(BaseModelSerializer): class Meta: model = Tractor expandable_fields = dict( ... drivers=dict( serializer="safety.api.serializers.TractorDriverSerializer", many=True, ), ... Views: class DriverStatusViewSet(BaseModelViewSet): queryset = DriverStatus.objects.all() serializer_class = DriverStatusSerializer class TractorViewSet(BaseModelViewSet): queryset = Tractor.objects.all() serializer_class = TractorSerializer class TractorDriverViewSet(BaseModelViewSet): queryset = TractorDriver.objects.all() serializer_class = TractorDriverSerializer TractorDriver instance does not have make field. Tractor instance contains make field. I do not understand why it trys to find make field in TractorDriver instance. -
django-websocket-redis development server not working in server
I'm using your lib in so many project, thanks for your serious and robust job. This problem occured on server ubuntu 20.04 We tested with Firefox, and Chrome, and same problem with all navigators. I can't reproduce on my machine, which is a ubuntu 20.04. Disable firewall: no change Adding a setTimeout of 1 sec for Faye client connect on the JS code: no change While transport down message occured in the screenshot, i only see handshake debug message server side. At the moment of the screenshot, we were only 2 using the web application. Server side: dedicated server with python django, latest lib. I would tend that it's NOT a problem with your libs, i'm just trying to find where come this problem. I'd like to know if you got a debug method suggestion, this could be a nice page in the wiki (trouble shooting steps) Do you have any suggestions please ? -
I want to select multiple allowances options on front end it shows me error
i just want to try select a multiple options but the thing is on front end i selected but on back end it shows me error and the data is not passed. i did allowance model manytomanyfield in create contract for select multiple allowances models.py class allowances(models.Model): enName = models.CharField(max_length=200, blank=True, null=True) value = models.FloatField() def __str__(self): return "{}".format(self.enName) class CreateContracts(models.Model): allowance = models.ManyToManyField(allowances) def __str__(self): return "{}".format(self.ContractsReference) views.py def savecontract(request): allowance = request.POST['allowance'] if cid == "": CreateContracts.objects.create(allowance=allowance) res = {"status": "success"} return JsonResponse(res) else: contract.allowance = allowance contract.save() res = {"status": "success"} return JsonResponse(res) js function savecontract(){ allowance = $('#allowance').val(); data.append("allowance", allowance) var r = false; $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", contentType: false, processData: false, url: '/Employee/savecontract/', data: data, async: false, success: function (response) { if(response.status == "success"){ $('#cid').val(response.id) r=true; } else{ swal("Error","Something Went Wrong!","error") } }, error: function () { swal("Error","Something Went Wrong!","error") } }); return r; } }); HTML Template <select class="form-control new-create selectpicker" multiple data-actions-box="true" id="allowance"name="allowance"> {% for d in allowance %} <option value="{{d.id}}">{{d.enName}}</option> {% endfor %} </select> -
How do I get object
Views.py I am trying to get genre id but i got none class IndexView(View): def get(self , request): books = None language = Language.objects.all() genre = Genre.objects.all() print(genre) genre_id = request.GET.get('genre') print(genre_id) language_id = request.GET.get('language') if genre_id: books = Book.get_books_by_genre_id(genre_id) elif language_id: books = Book.get_books_by_language_id(language_id) else: books = Book.objects.all() return render(request , "index.html" , {"all_books":books , 'lan':language , 'gen':genre} ) models.py I made a staticmethod for the get genre id but i failed to get it class Book(models.Model): b_name = models.CharField(max_length=150) b_author = models.CharField(max_length=150) b_genre = models.ForeignKey(Genre ,on_delete=models.CASCADE) b_language = models.ManyToManyField(Language) @staticmethod def get_books_by_genre_id(genre_id): if genre_id: return Book.objects.filter(b_genre = genre_id) else: return Book.objects.all() @staticmethod def get_books_by_language_id(language_id): if language_id: return Book.objects.filter(b_language = language_id) else: return Book.objects.all() I get this in command I am getting this objects but not get id <QuerySet [<Genre: fiction>, <Genre: novel>, <Genre: narrative>, <Genre: non-fiction>]> None Html here is my html code <ul class="list-group"> <h3><b>Languages</b></h3> <a class="list-group-item " href="/">All Books</a> {% for lan in lan %} <a class="list-group-item" href="/?language={{lan.id}}">{{lan.name}}</a> {% endfor %} </ul> <ul class="list-group"> <h3><b>Genre</b></h3> {% for gen in gen %} <a class="list-group-item" href="/?Genre={{gen.id}}">{{gen.book_genre}}</a> {% endfor %} </ul> -
Django Datatable view using POST rather than GET
https://django-datatable-view.readthedocs.io/en/latest/index.html Does anybody know how to use POST requests rather than GET? The issue is the AWS loadbalancer doesnt seem to like the length of URL generated in the GET request (3000 chars) and so i am not able to use on live server (after spending days building and working fine locally). -
django - Upload file to models on existing form
i'm trying to upload a file inside an existing form, the idea is to send a buy request with a transaction receipt attached. i need to upload the input type="file" to receipt on models i tried with forms, but couldn´t get it to work (it gave me an error with amount from models), i think it is because there is a form inside a form... i guess any idea? .html <div> <form action="{%url 'buying' %}" method="post" name="f"> {% csrf_token %} <div class="form-group h1color"> <label for="">USD Amount</label> <input type="number" class="form-control" name="amount" placeholder="$" value={{values.amount}} onchange="cal()" onkeyup="cal()" > </div> <div class="form-group h1color"> <label for="">Price in UF</label> <p><input class="form-control" type="text" name="amount_uf" value="UF 00" readonly="readonly" /></p> </div> <div class="form-group h1color"> <Label for="">Attach Receipt</Label> <input type="file" class="form-control-file border"> </div> <button type="submit" class="btn whitecolor bgcolorgraay" style="width: 100%;">Send</button> </form> </div> models class Transactions(models.Model): STATUS = [ ('pending', 'pending'), ('aproved', 'aproved'), ] amount = models.FloatField() date = models.DateField(default=now) owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(default='Payment', max_length=255) status = models.CharField(max_length=255, choices=STATUS, default='pending', ) receipt= models.FileField(upload_to='documents/%Y/%m/%d') amount_uf=models.FloatField(default=0) account = models.CharField(default="n/a" , max_length=255) def __str__(self): return str(self.owner) + " | " + self.category + " | " + str(self.date) -
Djnago Pagenation not working for filter and showing all items in every page
I want to display only one item per page but it's displaying all items in every page and just increasing only page numbers after added new item. see the picture: here is my views.py def ShowAuthorNOtifications(request): user = request.user notifications = filters.NotificationFilter( request.GET, queryset=Notifications.objects.all() ).qs paginator = Paginator(notifications, 1) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) notification_user = Notifications.objects.filter(user=user).count() Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True) template_name ='blog/author_notifications.html' context = { 'notifications': notifications, 'notification_user':notification_user, 'page_obj':response, } print("##############",context) return render(request,template_name,context) filters.py import django_filters from .models import * class NotificationFilter(django_filters.FilterSet): class Meta: model = Notifications fields = ['notification_type'] models.py: NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved') notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250,default="New Comment") html {% for notification in notifications %} {% if notification.notification_type == "New Comment" %} #my code...... {%endif%} {%endfor%} first I tried to use this Function based views pagenations but getting same result. It's just adding page number and showing all items every page. -
How to access Django manage.py from Docker
I am using Django as my Web-Framework. As a database I use PostgresSQL. To start my Postgres Database and the Webserver I use Docker. When I start the server and db with docker-compose up, everything works fine. The database loads properly into Django and I dont get any errors. But when I run for example python3 manange.py makemigrations django throws an error: could not translate host name "db" to address: Name or service not known Where "db" is the name of my postgres database. This is even then when server and database are running on a different window. What I find very weird is that the Database is found when I start with docker. How do I access commands like python3 manage.py [...]? So for example I need to create a superuser and dont know where to create that because if I use the normal python3 manage.py createsuperuser I get the same error as above. The console window from starting docker I also cannot use because there the Django Server runs and just displays the incoming http posts and requests. -
Dynamic queryset in django sitemap
I have more than 100,000,000 page URLs, how can I make the QuerySet be dynamic in the sense that each class will have 10,000 unique URLs without manually creating the integers in 10,000 classes? # sitemap.py account_ from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from appname.models import Page import datetime from appname.sitemaps import Page000001 from appname.sitemaps import Page000002 ps_dict_01 = { "ps_file_000001": Page000001, "ps_file_000002": Page000002, { class Page000001(Sitemap): def items(self): return Passage.objects.all()[:10000] lastmod = datetime.datetime.now() changefreq = 'hourly' priority = 1.0 protocol = 'http' class Page000002(Sitemap): def items(self): return Passage.objects.all()[10000:20000] lastmod = datetime.datetime.now() changefreq = 'hourly' priority = 1.0 protocol = 'http' -
How to define a 'IsOwner' custom permission for a many-to-many field in Django rest framework?
I'm very new in Django especially in Django-rest-framework. So in this project exercise of mine. And I want to have an object level permission, a IsOwner custom permission where authors are the only one who can modify it. My Model looks like this: #imports class Book(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=400) publisher = models.CharField(max_length=400) release_date = models.DateField() authors = models.ManyToManyField('Author', related_name='authors', blank=True) def __str__(self): return self.title class Author(models.Model): user= models.ForeignKey( User, on_delete=models.CASCADE, default=1) biography = models.TextField() date_of_birth = models.DateField() #books = models.ManyToManyField('Book', related_name='authors', blank=True) def __str__(self): return self.user.username And this is the serializers #imports here class BookSerializer(serializers.ModelSerializer): class Meta: ordering = ['-id'] model = Book fields = ("id", "title", "description", "publisher", "release_date", "authors") extra_kwargs = {'authors': {'required': False}} class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(many=True, read_only=True) class Meta: ordering = ['-id'] model = Author fields = ("id", "user", "biography", "date_of_birth", "books") extra_kwargs = {'books': {'required': False}} and views.py is like this: #imports here class IsAnAuthor(BasePermission): message = 'Editing book is restricted to the authors only.' def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True # I need to filter who can only edit book in this part but # obj.authors when print is none return obj.authors == request.user class … -
the "Select all" header checkbox in django 2.7.6 version?
How to get header checkbox in python version 2.7.6? -
how to filter based on created an object for froingkey django
i have two models (tables) Ticketing and Cancel class Ticketing(models.Model): a= models.CharField(max_length=40) b = models.DecimalField(max_digits=10,decimal_places=2) #others class Cancel(models.Model): ticket = models.ForeignKey(Ticketing,on_delete=models.CASCADE) #others views.py , i have to make a query to show all active Ticketing Ticketing.objects.filter()#how to filter all objects which `cancel` not created for thank you , i know make a boolean field then whenver cancel created BooleanField in Ticketing will be False , but i dont want to use it , is it possible please ?! -
Showing data and charts corresponding to buttons in Django frontend
I am taking 15 files from users as input and I am running an algorithm in views.py on those files. I make lists of all the information which I want to show on dashboard for all 15 files. Now on the frontend, I want to give users 15 buttons corresponding to each file and onclicking each button, respective data and charts must be shown. I am using chart.js for charts but I am not sure how I can add the functionality of showing charts and data from clicking corresponding buttons. -
Django .save() method is not appearing in Visual Studio Code
I am relatively new to python and currently exploring django. I am facing this problem in Visual Studio Code where the save() method is not reflected in my main app. The method reflects in other apps and I am not sure how to go about solving this. The codes are situated in the views.py of the respective applications. For this image, form.save() does not return any method which results in not saving any information. This is situated in my main app For this image, form.save() returns a method that allows the saving of information. This is situated in my register app. -
Create A model In Django Which Accept Value For A Specific Choice
I Am Working In Django & DRF(Django-Rest-Framework) In Which I have A Choices In which if Video Is Paid Video , Now I'm creating another Model which Stores all Paid Video's Information from django.db import models from userapi.models import User # from taggit.managers import TaggableManager import datetime class post(models.Model) : Public = 'Pub' Private = 'Pri' Paid = 'Paid' selection = [ (Public, 'Public'), (Private, 'Followers'), (Paid, 'Paid'), ] username = models.ForeignKey(User, on_delete=models.CASCADE) post_description = models.TextField(max_length=500) post_timestamp = models.DateTimeField(auto_now = True) post_selection = models.CharField(max_length=10,choices=selection) def __str__(self): return self.username This is userpost.py now I want to create model named paid_videos in which If post_selection is Paid then It takes amount of it I'm NEW TO DJANGO -
Pagination on Pandas Dataframe in Django
I Have data in Postgresql and getting that data through ORM query into my dataframe named as data, My view.py is given below: view.py from operator import index from django.shortcuts import redirect, render from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.shortcuts import render from bar_chart.models import AirQuality from django.core.paginator import Paginator #from django.views.generic import TemplateView #from django.shortcuts import render #from django.db.models import Sum from django.db.models import Avg from django.http import JsonResponse from bar_chart.models import AirQuality #from .models import * import pandas as pd # Create your views here. def authenticate(request): count= User.objects.count() data= AirQuality.objects.all().values() print(data) df= pd.DataFrame(data) df1= df.tail(10) mydic = { "df": df1.to_html() #"count": count } return render(request, 'auth_home.html', context=mydic) #, {'count':count} I want to render those pages of pandas dataframe (All data not just the tail of data) in my auth_home.html. What would be the way out (code) to apply django pagination on my pandas dataframe? -
Django: How to use same abstract class twice with same fields but different names?
I have an abstract model called Address with fields such as address_line, postcode etc. Now I want to create a model Person which has multiple types of addresses like residential_address, office_address etc. How can I achieve that in Django? My Address model: class Address(Model): address_line_one = CharField( blank=True, null=True, max_length=255, ) address_postcode = CharField( blank=True, null=True, max_length=50, validators=POSTCODE_VALIDATORS ) class Meta(GlobalMeta): abstract = True My Person class: class Person(Address, Model): name = CharField( blank = True max_length = True ) class Meta: app_label = "person" ) forms class PersonForm(forms.ModelForm): class Meta: model = Person exclude = [] widgets = {} form.html <div> {% form.name %} </div> -
Bootstrap Modal doesn't popup
Below is the code which I copied from the Bootstrap website. I can't understand why is it not working, even though it works on its website as a demo. <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter"> Launch demo modal </button> <!-- Modal --> <div class="modal" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> Below is my script and link tags for bootstrap <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> How should I debug this? -
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. Django ecommerce website ajax
views.py def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) return JsonResponse('Item was added', safe=False) cart.js function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:',data) }); } script getCookie, I heard that this script can solve this problem. But, it didn't help. function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string besgin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); Still Error: POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) updateUserOrder Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 -
Django email sending but not received
In my django project I am trying to send a message. There is a message in the sent ones, but I do not receive it. The letter is not in spam. This my settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 I tried to do what is written here Django email sending, but not received -
How can I dynamically reference the fields in a Django query set object in a template?
I have a model that is referenced by a generic ListView, and feeds into a template. Attempts to create a table in the template give me a TypeError: not iterable - what am I doing wrong? Sample code Class bookmodel(models.Model): Book = models.CharField(max_length=255) Author = models.CharField(max_length=255) Views Class bookview(generic.ListView): model = bookmodel template = “books.html” Which generates an object_list something like: <Queryset [<bookmodel: Grapes of Wrath >, <bookmodel: I, Robot>]> The template is laid out as follows: {% extends ‘base.html’ %} {% block content %} <table> <thead> <tr> <th> book </th> <th> author </th> </tr> </thead> <tbody> {% for object in object_list %} <tr> {% for field in object %} <td> {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endblock %} But this fails with the aforementioned error. -
What is the error in my syntax of javascript in django website?
See i am making a basic e commerce website in django for my django practice and i dont know javascipt really well. Can you please find problem in my javascript. Code in my checkout page's checkout.js checkout.js Error coming in this part image My views.py checkout function views.py Please help me out -
config sendgrid and django
hello despite my trying I can not configure sendgrid here is the code thank you for your help SENDGRID_API_KEY = 'password' EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER='API Key ID' EMAIL_HOST_PASSWORD=SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Python ecommerce <API Key ID>' BASE_URL = 'sitename' DEFAUT_FROM_EMAIL='API Key ID' MANAGERS = ( ('mohamed aymen hssen', "API Key ID"), ) ADMINS = MANAGERS error HTTP Error 401: Unauthorized -
python How to force download generated pdf?
I am using `xhtml2pdf` library in a django project to generate pdf file from html, and I would like to know how to force download the generated pdf to the server. If you need more information, please comment below. Thank you in advance.