Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django staticfiles of app does not copying in production after manage.py collectstatic
I'm using Django + Nginx + uwsgi Settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] if DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, "static/") else: STATIC_ROOT = "/var/www/mysite/static/" STATIC_URL = '/static/' if DEBUG: MEDIA_ROOT = os.path.join(BASE_DIR, "media/") else: MEDIA_ROOT = "/var/www/mysite/media/" MEDIA_URL = '/media/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] After update a code (in DEBUG = True all works good, static files are loading correct) I'm using python manage.py collectstatic on DEBUG = False in production server and it's collect admin static, but it's not collecting static for "main" app. In debug mode all working good. Checked serving by Nginx - it's working correct. Why "collectstatic" doesn't collect static from "main" app? -
How to remove put method in RetrieveUpdateAPIView from drf-spectacular API documentation?
I have the following view: class PersonalInfos(generics.RetrieveUpdateAPIView): serializer_class = ClientSerializer permission_classes = [IsAuthenticated] def get_queryset(self): """ :return: A QuerySet Object """ return Client.objects.get(user=self.request.user) def get(self, *args): """ :param args: Handled by rest_framework views.dispatch :return: JSON object containing User Personal Data """ queryset = self.get_queryset() serializer = ClientSerializer(queryset) return Response(data=serializer.data) def patch(self, request): """ :param request: request object is sent by the client :return: Json response with the data sent of the body """ client = self.get_queryset() serializer = ClientSerializer(client, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=200) return Response(data="Unexpected Parameters", status=400) Everything works fine in the view, but the problem is that I am using drf-spectacular and it is showing me a PUT method in the documentation that we won't be needing in the API. My questions is, how can I customize drf-spectacular to not include a PUT method in the documentation? -
How can I perform a parse and edit function on an article when it's saved?
For a Django blog, I'm trying to find a way to parse the content of an article and automatically make edits when certain conditionals are met, then save the article to the db once the function is complete. Alternatively, I could do this from the view, but I figure it's more efficient and possibly easier to code if it's handled this way. What do I need to edit so I can pass this function when an article is saved? How can I parse the contents of the article and make changes when a conditional is met? Would something like the following work (pseudocode): ''' for line in object.content: line = line.rstrip() conditional: line = 'new line' object.content.save() ''' Sorry, not sure why codeblock isn't working. -
Django PWA - Session variables not updating
I am trying to convert a web application into a PWA using a service worker. I am using django session variables within the application for 'cart' functionality. As I add items to the cart session variable, it isn't getting updated while a service worker is running. I assume this is because of the caching. Is there anyway I can prevent this? the service worker being used (not my own): const PRECACHE = 'precache-v1'; const RUNTIME = 'runtime'; // A list of local resources we always want to be cached. const PRECACHE_URLS = [ '/home', '/base', '/menu' ]; // The install handler takes care of precaching the resources we always need. self.addEventListener('install', event => { event.waitUntil( caches.open(PRECACHE) .then(cache => cache.addAll(PRECACHE_URLS)) .then(self.skipWaiting()) ); }); // The activate handler takes care of cleaning up old caches. self.addEventListener('activate', event => { const currentCaches = [PRECACHE, RUNTIME]; event.waitUntil( caches.keys().then(cacheNames => { return cacheNames.filter(cacheName => !currentCaches.includes(cacheName)); }).then(cachesToDelete => { return Promise.all(cachesToDelete.map(cacheToDelete => { return caches.delete(cacheToDelete); })); }).then(() => self.clients.claim()) ); }); // The fetch handler serves responses for same-origin resources from a cache. // If no response is found, it populates the runtime cache with the response // from the network before returning it to the … -
How to include an argument while requesting for api in django?
I am trying to fatch live cricket score from sportsmonk cricket api and cricapi. using Django everything goes fine until I request for any endpoint with unique Id which is stored in a variable. sdd I gives key error always while doing so my request : resL = json.loads(requests.get( 'https://cricket.sportmonks.com/api/v2.0/fixtures/id?api_token').text) here 'id' is a variable for perticular fixture. It works fine while putting any numerical value instead of a variable. Same is the case with this url : resS = json.loads(requests.get('http://cricapi.com/api/fantasySummary/?apikey=123&unique_id=id).text) I not getting what I am doing wrong here. -
Django Rest Framework filter a calculated SerializerMethodField() in ViewSet using filterset_fields
I have a SerializerMethodField that calculates the next execution date adding hours to the last execution time Simplifying the code, a have this model: class Activity(BaseModel): name = models.CharField(max_length=250) last_execution = models.DateTimeField() def __str__(self): return self.name class Meta: ordering = ('name',) And to send to front-end the next excution time, I have this SerializerMethodField() in my Serializer class ActivitySerializer(serializers.ModelSerializer): next_execution = serializers.SerializerMethodField('get_next_execution') class Meta: model = Activity fields = ('id', 'name', 'last_execution', 'next_execution',) def get_next_execution(self, data): # last = ActivityExecute.objects.filter(activity_id=data.id).order_by('-executed_at').first() # time = data.periodicity_type.time_in_hour # if last: # if data.equipment.hour_meter > -1: # return last.executed_at + timedelta(hours=time - (data.equipment.hour_meter - last.hour_meter)) # return last.executed_at + timedelta(hours=time) # # return data.equipment.created_at + timedelta(hours=time) return data.last_execution + timedelta(hours=24) But when I try to add the calculated field to filterset_fields like this: class ActivityViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = ActivitySerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = { 'id': ['exact'], 'name': ['icontains', 'exact'], 'last_execution': ['exact'], 'next_execution': ['exact'], } def get_object(self): return super(ActivityViewSet, self).get_object() def get_queryset(self): return Activity.objects.all() I got this error: 'Meta.fields' must not contain non-model field names: next_execution There is a way to add the SerializerMethodField() to filterset_fields? Use the method get_queryset will make all my logic in that calculated field (commented) be duplicated. … -
javascript function doesnt work on other objects
I have a strange problem and I'm not sure what might be the problem. As you can see from the image, on click (...) dots another menu is showing up, however, this works only for the first card. The menu is not showing up on the other cards. Any help is appreciated. JS: // Profile Edit Profile Button - POST let cardEdit = document.getElementById('container-posts-card-edit'); cardEdit.addEventListener('click',function(){ let cardOP = document.getElementById('card-edit-options'); if(cardOP.style.display === "none"){ cardOP.style.display = "flex" }else{ cardOP.style.display = "none" } }) django card model: {% if user.post_author.all %} {% for post in user.post_author.all %} <div class="container-posts-card"> <img src = "{{ post.image.url}}" class = "container-post-card-img">s <p class = "container-post-card-caption">{{ post.title }}</p> <div id="container-posts-card-edit"> <span class = "ellipsis-edit"><i class="fas fa-ellipsis-v"></i></span> </div> <div id="card-edit-options"> <a href= "{% url 'update_post' pk=post.pk %}" >Edit</a> <a href= "{% url 'delete_post' pk=post.pk %}" >Delete</a> </div> </div> {% endfor %} {% endif %} -
Not using Promise returned by fetch()
Is (3) a correct way of using then()? I don't need the Promise returned by fetch(), I just want obtain an updated array of emails once fetch() is done. Are my comments for (1) (2) and (3) correct? I tested them by running another then() after each of them, and they seem right. I just want to be sure. function setArchive(email_id, boolArchive) { fetch(`/emails/${email_id}`, { method: 'PUT', body: JSON.stringify({ archived: boolArchive }) }) ##### (Using just one of these at a time) (1) .then(load_mailbox('inbox')) // doesn't wait for fetch() to resolve, returned Promise accessible by the next then() (2) .then((response) => load_mailbox('inbox')) // waits for fetch(), returned Promise NOT accessible by the next then() (3) .then(() => load_mailbox('inbox')) // waits for fetch(), returned Promise NOT accessible by the next then() ##### .then(response => console.log(response)) // (2) and (3) logs 'undefined' Thanks for your help. -
Django with MongoDB without using ORM
I want to do CRUD app with authorization using DJango and MongoDB without using ORM. How can I implement this in my project and do it with some buttons on my page? Now im using DJongo but i wont using ORM. I have no idea how to do it. For example - after click button you will add or delete something to database without using ORM. -
How to clear cloned django form data before inserting to template
I have two forms. One modelform (static) and second modelformset (dynamic). I am trying to let users add an arbitrary number of addresses but I am struggling with cloning process. This code works fine. Adds and deletes addresses, but the thing is, whenever a new addressform gets created it contains all the data from the last. I want to clear cloned form before inserting it back to the template, but don't know how to achieve this. I don't have much experience with jquery and was unable to find any solution to my problem. Would greatly appreciate any help. <form id=forms method="post"> <div id="form"> {{ form.non_field_errors }} {% csrf_token %} <div class="row"> <div class="col-md-4"> {{ form.old_password|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-4"> {{ form.new_password1|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-4"> {{ form.new_password2|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-6"> {{ form.username |as_crispy_field }} </div> <div class="col-md-6"> {{ form.email |as_crispy_field }} </div> <div class="col-md-4"> {{ form.first_name |as_crispy_field }} </div> <div class="col-md-4"> {{ form.middle_name |as_crispy_field }} </div> <div class="col-md-4"> {{ form.last_name|as_crispy_field }} </div> <div class="col-md-4"> {{ form.company_name |as_crispy_field }} </div> <div class="col-md-4"> {{ form.personal_id|as_crispy_field }} </div> <div class="col-md-4"> {{ form.title |as_crispy_field }} </div> <div class="col-md-4"> {{ form.phone|as_crispy_field }} </div> {{ address_forms.management_form|crispy … -
How can i login from Axios/Ajax in Django?
I'm building a Vue SPA where Django will be the backend of the Vue app and will communicate with the frontend only usinsg JSON. I'm trying to handle authentication now, and i'm trying to login from the Vue app using Axios (i'm using the standard session authentication), the Django backend uses django-allauth, so basically the Vue app should send a POST request to accounts/login/ which is a Django-Allauth URL in my backend. The problem with my code is that when i send the request with Axios nothing happens, and instead of logging in the response will be HTML instead of a valid response, Django-Allauth supports AJAX calls so that should not be a problem. Here is my code: authenticate() { axios.post('http://127.0.0.1:8000/accounts/login/', { username: 'root', password: 'test', }, { headers: { 'Content-Type': 'application/json', 'X-CSRFTOKEN': this.csrf_token, }, }) .then(function (response) { console.log(response) }.bind(this)) }, The response is HTML, while this is what i see in the terminal: [23/Mar/2021 20:04:37] "POST /accounts/login/ HTTP/1.1" 200 1607. What am i doing wrong? -
Check whether int value of string is zero, positive or null in Python
I am saving the form data into a model instance. There are fields where the user can enter values from 0 and above or leave them empty. Now I should assign them to a field. Eg code def update(self, my_val): self.my_val = my_val or None This above code works fine for values of 1 and above. But not for 0. How can I allow for 0 and positive numbers and if my_val is an empty string then I should store it as None. How can I do that? -
Uploading a picture in django to a unique folder
I'm fairly new to Django and am having a bit of trouble trying to upload images So broadly, I have a user class: class User(AbstractBaseUser): user_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) And a profile class: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to=<PATH>, blank=True, default=get_default_profile_image) For the above PATH in profile, I tried to upload it to: 'profiles/' + user.user_id + '/image.png' But if I try to do that, it says "AttributeError: 'OneToOneField' object has no attribute 'user_id'" Is there any way to set the upload_to path as profiles/user_id/image.png where the user_id will be the unique id of that user? -
Error while running pip install -r requirements.txt , Could not find a version that satisfies the requirement django-filters==2.4.0
Here is the command line output that I have got when I tried installing my requirements.txt inside a virtual env. It seems that there is some error with the django-filters version, but not sure what! I am so stuck with this, please help me. Thanks! Using cached asgiref-3.2.7-py2.py3-none-any.whl (19 kB) Collecting Babel==2.8.0 Using cached Babel-2.8.0-py2.py3-none-any.whl (8.6 MB) Collecting dj-database-url==0.5.0 Using cached dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Requirement already satisfied: Django==3.0.6 in e:\..\..\venv\lib\site-packages (from -r requirements.txt (line 4)) (3.0.6) Collecting django-crispy-forms==1.9.0 Using cached django_crispy_forms-1.9.0-py2.py3-none-any.whl (107 kB) ERROR: Could not find a version that satisfies the requirement django-filters==2.4.0 ERROR: No matching distribution found for django-filters==2.4.0 -
How do I add a filepath to a React project? (DRF)
I'm building a hybrid Django/DRF - React website. I'd like the react section to have a filepath as its only a part of the website (so .com/app instead of just .com/). Currently react renders correctly without the filepath, however when I add a subdomain to urls.py, index.html renders but without the components. React is in a django app, and the API is in another django app. This is the code with the filepath of 'app' added: src/components/App.js <Route path="app/join" component={RoomJoinPage} /> <Route path="app/info" component={Info} /> <Route path="app/create" component={CreateRoomPage} /> (react app) frontend urls.py from django.urls import path from .views import index app_name = 'frontend' urlpatterns = [ path('', index, name=''), path('info', index), path('join', index), django project urls.py django project urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('spotify/', include('spotify.urls')), path('app/', TemplateView.as_view(template_name='frontend/index.html')), path('main/', include('main.urls')), ] -
Should i have one django view that has lots of children or just lots of views
I have an api in django with a User class, this class has all CRUD operations and then I have children classes that inherit from this and on get or post requests they call x function e.g BaseUser(APIView): CRUD CreateUser(BaseUser): def post(self, request): BaseUser.create_user(request) then i have another for delete or get info etc but should these be this pattern where its one top user class and lots of children that inherit and call the CRUD operations or should these classes be broken out into their own thing e.g. one with all create logic then one with all delete logic for user. -
Template inheritance error in Django with TemplateDoesNotExist
base.html and child html file are in one directory app/templates/app: lead_list.html {% extends "leads/base.html" %} {% block content %} <a href="{% url 'leads:lead-create' %}">Create a new Lead</a> <hr /> <h1>This is all of our leads</h1> {% for lead in leads %} <div class="lead"> <a href="{% url 'leads:lead-detail' lead.pk %}">{{ lead.first_name }} {{ lead.last_name }}</a>. Age: {{ lead.age }} </div> {% endfor %} {% endblock %} base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DJCRM</title> <style> .lead { padding-top: 10px; padding-bottom: 10px; padding-left: 6px; padding-right: 6px; margin-top: 10px; background-color: #f6f6f6; width: 100%; } </style> </head> <body> {% block content %} {% endblock %} </body> </html> views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Lead, Agent from .forms import LeadForm, LeadModelForm def lead_list(request): leads = Lead.objects.all() context = { "leads": leads } return render(request, "lead_list.html", context) settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I am getting the error with django.template.exceptions.TemplateDoesNotExist: lead_list.html I think I have done everything right and compared with documentation but could not find my error. Thanks in advance! -
Google map integration for website through django
I'm using django(python) to code the page. is it possible to add a Google map feature, that specifically searches for nearby supermarkets based on user location? I see how changing the api adresss to change the search results in the Google document but in all the examples you need to have location as a latitude and longitude. can the webpage just prompt the user for location permissions and the code uses that location? I'm not exactly sure if I made the question clear but I will be grateful if anyone could point me in the right direction. -
What is the ideal way to store comments to a blog?
I am making a demo website using django and in the website you have blogs. What im trying to add is a way to add comments for every blog and what im trying to figure out is how to arrange the database. I thought about 3 options either you store with every blog a list of the comments or you store a list of all comments and the blog they belong to or you create a table for every blog with the comments. Which of these is the best in terms of how dificult it is to implement and how memory consuming it is? -
Instance continues to Fail Health check after python3 and Ubuntu 18.04 update (Django+Nginx+Uwsgi)
My Django + uwsgi + Nginx app has failed for days now and I am not sure what is happening. It seems that my Nginx health check seems to be okay and my Django App is functioning correctly. I am starting to have a feeling it is my uwsgi config. I have a shadow server running the exact same configuration and it started up perfectly. Any tips here? uwsgi.ini chdir = /opt/django/www/src module = my_site.wsgi:application master = true processes = 10 pidfile = /tmp/my_site.pid socket = /tmp/my_site.sock vacuum = true max-requets = 5000 daemonize = /var/log/django/uwsgi.log req-logger = file:/var/log/django/req.log logger = file:/var/log/django/err.log nginx.conf upstream django { server unix:///tmp/my_site.sock; # for a file socket } server { listen 443 ssl; ssl_certificate /opt/django/www/ssl/my_site.com.crt; ssl_certificate_key /opt/django/www/ssl/my_site.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; send_timeout 100s; proxy_read_timeout 500; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /opt/django/www/src/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { proxy_read_timeout 500; uwsgi_read_timeout 500; uwsgi_pass django; include /opt/django/www/src/uwsgi_params; # the uwsgi_params file you installed } } server { # the port your site will be served … -
I need to upgrade me code for DRY and easy refactoring in future
I need to move api/ prefix to main urls.py, cause it'll be easy to rename in one place later. Plus my reviewer ask me don't duplicate version in router, and write 'v1'once. my main urls: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('posts.urls')), ] if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT from django.urls import include, path from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from .views import CommentViewSet, PostViewSet router = DefaultRouter() router.register('v1/posts', PostViewSet) router.register(r'v1/posts/(?P<post_id>\d+)/comments', CommentViewSet, basename='Comment') urlpatterns = [ path('api/v1/api-token-auth/', views.obtain_auth_token), path('', include(router.urls)), ] i tried: router = DefaultRouter() router.register('posts', PostViewSet, basename='posts') router.register(r'posts/(?P<post_id>\d+)/comments', CommentViewSet, basename='comments') urlpatterns = [ path('api/v1/api-token-auth/', views.obtain_auth_token), path('api/v1/', include(router.urls)), but its wrong/ -
AttributeError on <module '__main__' when deploying app on Heroku via Gunicorn
I am new to Django/Heroku but am trying to launch my first project with these tools that includes a pre-trained SK model and custom Pipelines. I've got everything working fine locally but when I try to push to Heroku I keep receiving 500 errors and my log tail is posted below. I can't seem to solve it. My custom transformer pipeline that I wrote has a class called FeatureSelector as well as CategoricalTransformer, which I've pasted into the manage.py file (as someone suggested doing that, and I didn't know where else they might go). Heroku, or gunicorn, or something seems to have issues with this. AttributeError: Can't get attribute 'FeatureSelector' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> I've tried renaming the apps.py file, putting the pipeline in WSGI, moving the joblibs etc. but nothing seems to work for me. Thanks to anyone who's able to help out. Also I've posted the entire log file at the very bottom for anyone who needs it. File structure: project --app -- ml_models -- model.joblib -- transformer.joblib -- apps.py -- views.py apps.py from django.apps import AppConfig from django.conf import settings import os from joblib import load import warnings warnings.filterwarnings("ignore") class PredictorConfig(AppConfig): # create path to models … -
Using context name in django is not working Dataframe.to_html()
I have a problem following one tutorial on displaying dataframes in django web page my Views.py is as follows from django.shortcuts import render from products.models import Product import pandas as pd def chart_select_view(request): product_df = pd.DataFrame(Product.objects.all().values()) context = { 'Products': product_df, } return render(request, 'main.html', context) I have two errors the first is unable to import pandas as pd and I've already installed it in my venv the second is not important but here it is "object has no members" and I know it's a pylint error when I want to show Products in the main.html it displays error "Invalid block tag on line 9: 'Products', expected 'endblock'. Did you forget to register or load this tag?" the main.html is {% extends 'base.html' %} {% block title %} {% endblock title %} {% block content %} <h1>Hello World</h1> {% Products %} {% endblock content %} Can somebody help I'm following the tutorial perfectly but it shows an error to me when it's working fine in the video. -
Django: How to efficiently add objects to ManyToManyFields of multiple objects?
We have a student and class many to many relation, where a student can take multiple classes, and a class can be taken by multiple students. class Class(models.Model): name = models.CharField(null=False, max_length=128) class Student(models.Model): first_name = models.CharField(null=False, max_length=64) classes = ManyToManyField(Class) What is the fastest way to add some object or a whole QueryList (in our case: all classes with Biology in their name), to the ManyToManyField of each object in another QueryList (in our case: all students whose first name is Linus)? The current way I am doing it is: biology_classes = Class.objects.filter(name__contains='Biology') linuses = Student.object.filter(first_name='Linus') for linus in linuses: linus.classes.add(*biology_classes) Which I guess hits the db for each student. I wonder if there is maybe some way to do it all "at once". Maybe something that looks something like this: linuses.classes.add(*biology_classes) # (this does not work) -
I can't loop over my ids params, how can i receive and loop over
I'm working on a small project using Django and VueJS, i would like todo a bulk delete, i'm sending an array object of my IDs, using Axios in the body like that : [1,2,3] this is my code : getAPI({ method: 'DELETE', url: 'api/contact/delete/', data:{ ids: this.selected } }).then((response) => { console.log(response.data) }) how can i loop over my ids in django this is my function : @action(methods=['delete'], detail=False) def delete(self, request): for i in request.body: print(request[i])