Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I Create A Django Tracking System For Tracking Packages?
I'm trying to create a Food Ordering Site using Django. One of the features that I'm thinking of is a tracking system where users can track and get the exact location of where their package is from where they are. I thought of using Google Maps but unfortunately, I have no idea of getting what I want from their API Documentation. I will appreciate the answer. Thank you -
Are django formsets really slow for medium traffic websites? What is a substitute for formsets? Can anyone provide an example?
Hey guys are django formsets really slow for medium to heavy traffic websites? What is a substitute for formsets? I am a beginner and am working with formsets now..but I heard from a lot of people that they are too slow and won't render properly if the traffic increases. If that's the case, then are there any substitutes of which is the best way to do it? Thank you -
Django CSRFToken Validation
Trying to create a POST request by providing csrftoken in headers to the server (as -> X-CSRFToken: _csrf_token_value). However the CsrfViewMiddleware rejects the request and returns back with Forbidden (CSRF token missing or incorrect.) The request fails both for an ajaxrequest from client and POSTMAN. Using Django 3.0.x for this project. EDIT- getting csrftoken from _get_new_csrf_token() -
Django, Default file icon is missing after download of file
I have written code for downloading a file through an API. It works fine as I can see. The file size is the same. But the file has no longer a default file icon. I am pretty new at this and maybe I am doing something wrong. I am reading the file as I would for a standard textfile and saving it in the same way with the binary option. So how can the files be same size and still something seems to be missing in the downloaded file? Is there a better way to download files? This is the code on the server: file_location = 'static/File.pkg' try: with open(file_location, 'rb') as f: filex_data = f.read() response = HttpResponse(filex_data, content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename="File.pkg"' return response This is the code on my local computer: url = 'http://myServer/waprfile/' x = requests.get(url, data=data, headers=headers) f = open("TheNewFile.pgk", "ab") f.write(x.content) f.close() -
django css doesn't load from the index url and not any other url
why css loads from the index url and not any other url? urls: urlpatterns = [ path("", views.index, name="index"), path("product/<slug>", views.product, name="product"),] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: def index(request): return render(request, "product.html") def product(request, slug): product = Product.objects.get(slug='iphone-11') print(product.image1.url) context = {'product': product} return render(request, "product.html", context) product.html: {%load static%} <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Nakahaty</title> <meta name="keywords" content="HTML5 Template"> <meta name="description" content="Molla - Bootstrap eCommerce Template"> <meta name="author" content="p-themes"> <!-- Favicon --> <link rel="apple-touch-icon" sizes="180x180" href="static/assets/images/icons/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="static/assets/images/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="static/assets/images/icons/favicon-16x16.png"> <link rel="manifest" href="static/assets/images/icons/site.html"> <link rel="mask-icon" href="static/assets/images/icons/safari-pinned-tab.svg" color="#666666"> -
Django admin panel not visible in some cases
Websites like instagram ,pintrest are made on django. i tried to change their url and added a suffix '/admin' and it showed me an error like url not found. When i make django projects and host it on WWW i get to see /admin page but not in the case of these big websites,is there a way to hide it? I am a noobie so please don't judge my question and give me a downvote -
django_tenants: Best way to check for reserved subdomains/schemas?
We are using django-tenants, and in it, I see a regex for "reserved" schema names (or partial names) - like anything starting with pg_, for example, to avoid conflicts with the Postgresql schema(s). But even so, it doesn't have information_schema in its regex, which we certainly wouldn't want users to use. The regex is: SQL_SCHEMA_NAME_RESERVED_RE = re.compile(r'^pg_', re.IGNORECASE) We're going to have more reserved words than just the two examples above. Like our own company name, and other subdomains we will use for our site, like getting-started, and probably several others we haven't thought of yet. My question is concerning performance. If we end up with a dozen (or more) reserved words, will that work ok in a regex, or is it better to put them in a list? -
Django passing data into Google Charts
I have a view in views.py like the below. I am passing data in as it is required in the graph def home(request): posts = [['day', 'ic'], ['Fri', 3601326.0], ['Mon', 1450340.0], ['Sat', 2094946.0], ['Sun', 2373750.0], ['Thu', 3116066.0], ['Tue', 729403.0], ['Wed', 1934780.0]] return render(request, 'kodey/home.html', {'data': posts}) in the HTML I have the below but that chart doesn't show. It does if I pass the same data in within the document, so I am a bit confused, Can anyone help me? Thanks <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'bar']}); google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data2 = google.visualization.arrayToDataTable( {{ data }} ); var options = { chartArea: { left: 50, top: 5, right: 5, bottom: 50, width: 500, height: 300 }, hAxis: { title: 'Average Interactions', minValue: 0 }, }; var days = new google.visualization.BarChart(document.getElementById('days_div')); days.draw(data2, options); }</script> -
Django ModuleNotFoundError No module named 'home_page.apps.HomePageConfigdjango'
I created a new app using python manage.py startapp home_page and inside INSTALLED_APPS I have added 'home_page.apps.HomePageConfig' but when I ran the server I get this error ModuleNotFoundError: No module named 'home_page.apps.HomePageConfigdjango'; 'home_page.apps' is not a package and OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' Why is this happening? Please help me I am new to Django -
Django force Python3
I have a view in Django that i've written & it works only in Python3 as the library I am using isn't available in Python2. In the terminal, I can run the same script python3 scriptname.py and it works, whereas python scriptname.py does not. so when I run the app, the view fails, because it's trying to run it in Python2. How do I force Django to try and run it in Python3? -
Django Css file unresponsive after first loading of webpage
I can't figure out why my main.css isn't loading in my django project. I am using skeleton boilerplate and trying to change the background color but nothing is happening. It is strange because when i run python3 manage.py runserver it will compute my first original main.css values i put in at the begining of my project, but when i alter my main.css values the webpage just shows my original values. First i create a static folder in my project (outside my app). I then add a css folder. I then add my skeleton.css, normalise.css and my main.css In my index.html I link my static folder and I link my skeleton css files and my main css files in my head tags. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'css/normalize.css' %}"/> <link rel="stylesheet" href="{% static 'css/skeleton.css' %}"/> <link rel="stylesheet" href="{% static 'css/main.css' %}"/> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <meta charset="UTF-8"> <title>index</title> </head> perfect it makes sense so far. Now is where I get confused. I put in some code into my main.css to make background color values and play around with the layout etc. body { background: #505f73; } .container { background: #FF0000; margin-bottom: 50px; margin-top: 50px; padding: … -
Disable/Skip a custom Django Middleware for certain type of request
So i have two django apps, one for my full site and the other for the mobile version. The main site has a custom middleware that checks if the device is a mobile device - and if so, it redirects to the mobile site using HttpResponseRedirect. Same redirection happens on the mobile site, but for non-mobile devices. The main site and the mobile one both share the same MEDIA directory - contained at the main site server; the mobile site's MEIDA_URL just points to the main site's media directory. Which worked fine, up until I added the redirection middlware on both sites - due to which, the media queries being made to the main site (by the mobile site template) are redirected back to the mobile site. So my question is this - do i really have to manually check each incoming request at the main site (by parsing the request path in the redirection middleware) to see if it is a media request and then not redirect it if it is, or is there a possible alternative - such as disabling/bypassing the middleware for media queries or an easier way to check if the request is for a media … -
Django Models inheritance and avoid using multiple django.setup() calls
We are using Django's ORM portion of the framework. We have 1 Shared app, and a couple of Apps, without relationship between themselves. the Shared app defines an abstract BaseModel that all other models from all other apps inherit from, along with a few shared models, that may be referenced as a foreign key in the other apps. We are using a monorepo, so no different repositories or anything like that. These models can be used in various applications, from (non django) web apps, and to processing units that are deployed when needed and gets destroyed when done with their processing. I'm trying to understand if there's a single place we can call import django django.setup() and remove the need to call it in the top of every app that imports one of the models, and that will comply with both of our unittests and service run. This is the shared models.py file import json import uuid from datetime import datetime import common.db.enums as shared_enums from django.db import models from django.db.models import CASCADE MAX_VARCHAR_LENGTH = 255 def generate_uuid(): return uuid.uuid4().hex class UUIDString(models.UUIDField): # pragma: no cover def from_db_value(self, value, expression, connection): if isinstance(value, uuid.UUID): return value.hex else: return value class … -
Django Rest Framework - Restrict queries to entire database
I do have a large database (>50K rows) that contains metadata. There are also four endpoints for an API. API requests can be parameterized but the problem starts when the user does not add parameters, ending to query the entire database. Is there any way to restrict this? Or let's say if the number of the results is > 200,000 return an error message? -
Django rest framework, query user's nested data
I have a model in my API which is related to another which is related to the user. class User(AbstractUser): pass class ModelA(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='model_a') class ModelB(models.Model): model_a = models.ForeignKey(ModelA) I want to know if there's a way to return ModelA in my view's queryset based on the user. class PastureYearsView(ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): return ModelB.objects.filter(model_a=self.request.user # how to get model a associated with user here) I tried using prefetch related: return ModelB.objects.filter(model_a=self.request.user.prefetch_related('model_a')) But it fails: 'CustomUser' object has no attribute 'prefetch_related' -
how to add data in my db for using django and DRF
I'm producing an API that uses DRF to receive Arduino's data and send it to Android. First of all, we succeeded in creating an API that shows the values stored in DB. However, there is a problem in producing an API that sends Arduino's data to DB. Data is normally input, but this data is not stored. Can you tell me the problem of my code? here is my codes views.py from .models import arduino from .serializers import arduinoSerializers from rest_framework.viewsets import ViewSet, ModelViewSet from rest_framework.response import Response class arduinoToAndroidViewSet (ViewSet) : def dataSend (self, request) : user = self.request.user queryset = arduino.objects.filter(name=user) serializer = arduinoSerializers(queryset, many=True) return Response(serializer.data) class arduinoToDatabaseViewSet (ModelViewSet) : serializer_class = arduinoSerializers def get_queryset(self) : user = self.request.user return arduino.objects.filter(name=user) def dataReceive(self, request) : queryset = get_queryset() serializer = arduinoSerializers(queryset, many=True) serializer.save() return Response(serializer.data) serializers.py from rest_framework import serializers from .models import arduino class arduinoSerializers (serializers.ModelSerializer) : name = serializers.CharField(source='name.username', read_only=True) class Meta : model = arduino fields = ('name', 'temp', 'humi') models.py from django.db import models from django.contrib.auth.models import User class arduino (models.Model) : name = models.ForeignKey(User, related_name='Username', on_delete=models.CASCADE, null=True) temp = models.FloatField() humi = models.FloatField() def __str__ (self) : return self.name.username -
Good solution for creating multiple user types with Django registration package?
I'm using the following approach to extend "django-registration-redux" package for multiple users. The solution is for creating Student and Professor objects as the user submits the registration forms. Stundent and Professor will have different model-fields/form-fields but are not defined here for simplicity. Is the following a good solution ? Please argument. urls.py path('accounts/register/student/', StudentRegistrationView.as_view(template_name='registration/registration_form_student.html'), name='registration_register_student'), path('accounts/register/professor/', ProfessorRegistrationView.as_view(template_name='registration/registration_form_professor.html'), name='registration_register_professor'), models.py class UserProfile(models.Model): def __str__(self): return '%s' % self.user user = models.ForeignKey(User, on_delete=models.CASCADE) class Student(models.Model): def __str__(self): return '%s' % self.userProfile userProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) class Professor(models.Model): def __str__(self): return '%s' % self.userProfile userProfile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) regbackend.py class StudentRegistrationView(RegistrationView): def register(self, form): new_user = super(StudentRegistrationView, self).register(form) new_profile = UserProfile.objects.create(user=new_user) new_profile.save() new_student = Student.objects.create(userProfile=new_profile) new_student.save() return new_user class ProfessorRegistrationView(RegistrationView): def register(self, form): new_user = super(ProfessorRegistrationView, self).register(form) new_profile = UserProfile.objects.create(user=new_user) new_profile.save() new_professor = Professor.objects.create(userProfile=new_profile) new_professor.save() return new_user -
I've a problem for Django File Upload with inline css editing
<p class="lead" style="color: whitesmoke;"></p> <p style="color: whitesmoke;">{{article.content|safe}}</p> I have this problem with developing django web framework. I use dark background so my article contents doesnt wiew with dark fonts therefor I must use another color style however I can't use and my articles fonts are always stay default style Please Help Me thank you so much for now -
How to implement DRM (Digital Rights Management) in python/django web app to protect video?
I am working on web app and I want to upload and stream videos. But I want to protect the videos and want to make difficult to download videos from my web app. I have heard about DRM but don't know how to use and implement it in my project. Is there anyone who might help me? Suggestions and Positive answers are highly appreciated. -
Convert DetailView to APIView in Django
I am converting Django to Django REST API. Now I am facing error with self.object in APIView. How can I use self.object or substitute option in APIView? Here is my DetailView... class ChapterDetail(DetailView): model= Chapter context_object_name = 'chapter' def get_context_data(self, **kwargs): context = super(ChapterDetail, self).get_context_data(**kwargs) user = self.request.user user_practice_game = UserPracticeGame.objects.filter(user=user).filter(practice_game__chapter=self.object).first() context['user_practice_game'] = user_practice_game return context Here is my APIView... class ChapterDetailAPIView(APIView): # need review def get(self, request, *args, **kwargs): context = {} qs_user_practice_game = UserPracticeGame.objects.filter(user=self.request.user).filter(practice_game__chapter= upg_serializer = UserPracticeGame(qs_user_practice_game, many=True) context['user_practice_game'] = upg_serializer.data return Response(context, status=200) In APIView, I can't use practice_game__chapter=self.object in the query! This is my model... class UserPracticeGame(DateMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='User', related_name='user_practice_game') practice_game = models.ForeignKey(PracticeGame, on_delete=models.CASCADE, verbose_name='Practice Game', related_name='user_practice_game') total_answered = models.IntegerField(verbose_name='Total Answered', default=0, blank=True, null=True) -
I would like to create pictorial presentation of network including labels for links and nodes using python over HTML page using django
I would like to create a pictorial network diagram using python, django, HTML. For example as below DUTA, DUTB, DUTC src {DUTA port1 tengig} {DUTB port3 tengig} {DUTC port2 tengig} dst {DUTB port1 tengig} {DUTC port1 tengig} {DUTA port2 tengig} ixia {DUTA port3 tengig} {DUTA port4 tengig} {DUTC port3 tengig}{DUTC port4 tengig} for this network is it possible to create diagram as below -
Initializing form by alternating between request.POST and arguments
I have a form as following: from django import forms def get_quantity_choices(avail_qty): return [(i, str(i)) for i in range(1, avail_qty)] class QuantityForm(forms.Form): def __init__(self, avail_qty=0, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'] = forms.TypedChoiceField(choices = get_quantity_choices(avail_qty), coerce=int)) In my views.py, I have two situations to render the form: render the form for the first time to the user; after the user enters form data, render it again in a different template, carrying all the data that has been entered. If the form is rendered for the first time, I can do this form = QuantityForm(avail_qty = avail_qty) where avail_qty is a variable generated elsewhere in my app. However, when re-rendering the form with full data, if I do this form = QuantityForm(request.POST) the __init___ function throws an error QueryDict cannot be coerced to 'int'. So, the problem is that I do not want the form to reset the choices by __init__ when being re-rendered. How do I turn off __init___ if I am re-rendering a form that is bound with full data? -
is need to use seprated Authontication system in django for ecommerce website?
I am create a e-commerce website,back-end with Django and front-end with reactjs how sprate website admin user from eCommerce customer user in Django ? i use firebase auth for e-commerce frontend -
What are the best alternatives to AJAX in Django?
What are the best alternatives to AJAX -
Django filter function on HTML template
I'm stuck on a problem. I need to filter all of the listings using the list.id in the for loop. Unfortunately, the filter function in Django could not be parsed. Is there another solution or is there a way to work around it? How can you run a function in Django HTML template. Thanks! index.html {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% if not listing %} <h3>Nothing listed...</h3> {% endif %} {% for list in listing %} <h3>Listing: {{ list.title }}</h3> {% if list.photo != "" %} <img src="{{ list.photo }}"> {% endif %} <p>{{ list.description }}</p> {% if not bids.filter(listing=list.id) %} #This line could not be parsed <h5>${{ list.price }}</h5> {% else %} <h5>${{ bids.filter(listing=list.id).order_by(-bids).first().bids }}</h5> #This line could not be parsed {% endif %} <p> {% if not bids.filter(listing=list.id).count() %} #This line could not be parsed 0 {% else %} {{ bids.filter(listing=list.id).count() }} #This line could not be parsed {% endif %} bid(s) so far. {% if bids.filter(listing=list.id).order_by(-bids).first().bidder == user.username %} #This line could not be parsed Your bid is the current bid. {% elif not bids.filter(listing=list.id).order_by(-bids).first().bidder %} #This line could not be parsed There is no bid. {% elif bids.filter(listing=list.id).order_by(-bids).first().bidder != user.username %} …