Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extract values from requests?
I would like to extract the division data from the URL path("company/<division>/authenticate", views.user_info, name="user_info") I tried to do it like this but it doesn't work @api_view(["GET", "POST"]) def user_info(request): if request.method == "GET": data = { "username": request.GET.get("username"), "password": request.GET.get("password"), "division": request.GET.get("division"), } return JsonResponse(data) Can you please help? -
How do I make a decorator for Django management command processing locking?
I have a Django project that has many custom management commands that get executed from crontab. I need to implement locking in these commands to prevent cron from starting multiple instances of the command executions. So I am going through each of my custom management commands and changing: def handle(self, *args, **options): ... to: from lockmgr.lockmgr import LockMgr, Locked ... def run_handle(self, *args, **options): ''' I renamed handle() to run_handle(). ''' ... def handle(self, *args, **options): command = sys.argv[1] try: with LockMgr(f'{command}_lock') as l: self.run_handle(*args, **options) except Locked as e: errmsg = f'{command} failed to lock. Reason: {e}.' self.stdout.write(errmsg) self.logger.error(errmsg) Then I started thinking that I should probably use a "decorator" here, but I am not quite sure how to do that. Any help would be great. Thanks. -
Put Django view return data into response data
I have a function based view and it has many checks in it and returns data based on check results. So I don't want to wrap my data into Response object every time manually. Is there a way to put function return value into OK response data automatically in Django Rest Framework? For example to have a valid view like this: @api_view(['GET']) def pre_reg_countries(request): if some_condition: return data_1 # instead of returning Response(data=data_1) else: if another condition: return data_2 else: return [] P.S. The idea is to me from Java Spring framework. -
SyntaxError: invalid syntax manage.py except ImportError as exc:
I have created a django project called tictoctoe but when I run "py manage.py runserver" it gives me following error. File "manage.py", line 11 except ImportError as exc: ^ SyntaxError: invalid syntax it used to work fine earlier. here is manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tictactoe.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
setting debug false,static files are appearing by --insecure command but images from database are not appearing in django
Here is my settings.py My urls.py corresponding to desired app Here is my image url -
Serializer data returns blank?
I was able to get the fields before enabling author but now i can't get them.They all return blank but id and author returns fine.I tried other various ways but that causes problems on author or so. I enter data to caption,details field if anyone asks about that. class ArticleCreateSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) caption = serializers.CharField(required=False) details = serializers.CharField(required=False) class Meta: model = Post fields = ('id','author','caption','details') def create(self, validated_data): author=self.context['request'].user.profile article = Post.objects.create(author=author,**validated_data) return article Views.py class ArticleCreateView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def create(self, request): serializer_context = { 'request': request } serializer_data = request.data.get('article',{}) serializer = self.serializer_class( data=serializer_data, context=serializer_context ) serializer.is_valid(raise_exception=True) serializer.save() response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'Article Created Successfully!', } status_code = status.HTTP_200_OK return Response(serializer.data, status=status.HTTP_201_CREATED) Returning data: { "id": "3677676c-f155-494f-9926-8cdb68765a2c", "author": { "first_name": "John", "last_name": "Smith", "phone_number": "0123", "gender": "M", "birth_date": "1964-04-12" }, "caption": "", "details": "" } Did i do a mistake in the codes or so? -
How to validate the email field of UserCreationForm using the built-in EmailValidator in Django?
Right now, if I enter invalid data into my UserCreationForm and submit it, the page reloads but doesn't show any error. I would like the EmailValidator validator in Django to show the error. I have tried adding the validators attribute to the email field, but it didn't do anything. Here are my views: from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render from django.urls import reverse from .models import CustomUserCreationForm # Create your views here. def register(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('index')) elif request.method == 'GET': form = CustomUserCreationForm() elif request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() context = { 'user': request.user, } return HttpResponseRedirect(reverse('index'), context) else: return HttpResponseRedirect(reverse('register')) else: return HttpResponse("Project 3: TODO") context = { 'form': form, } return render(request, 'registration/signup.html', context) def logout_view(request): logout(request) return HttpResponseRedirect(reverse('login')) And here are my models: from django.contrib.auth.models import AbstractUser, AbstractBaseUser from django import forms from django.contrib.auth.models import User from django.db import models from django.contrib.auth.forms import UserCreationForm from django.core.validators import EmailValidator # Create your models here. # Customer class. class CustomUser(User): REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] # Create user registration form class. class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(required=True, max_length=150, help_text='Required.') last_name = forms.CharField(required=True, max_length=150, help_text='Required.') … -
how to kill gunicorn server inside request response cycle
i have one Django application and one flask application. it's running with two Gunicorn servers inside the docker containers. my goal is if the database connection was failed (if db was down), i want to kill the Django app and flask app. how could i do this ? -
Cannot access manage.py using command 'python manage.py runserver'
This is the response I got: Directory of C:\Users\Administrator\Xraddock 11-05-2020 18:48 <DIR> . 11-05-2020 18:48 <DIR> .. 11-05-2020 18:48 <DIR> Krack1 0 File(s) 0 bytes 3 Dir(s) 49,271,885,824 bytes free (test2) C:\Users\Administrator\Xraddock>python manage.py runserver python: can't open file 'manage.py': [Errno 2] No such file or directory I did everything right but don't know what went wrong -
Dynamically creating new URL in Django base on counter
I created a website include 2 pages: index.html and status.html. In index.html I create a new task and when I click execute the page move to status. The page status.html is refreshed every 30 seconds and display csv table base other process. urlpatterns = [ url(r'^$', v.index), url(r'^execute', v.execute), url(r'^status', v.status, name='status'), ] I want to run multiple task in the same time but the status.html page is the same page. How can I create multiple tasks with other urls? -
Debug toolbar and includes in urlpatterns
Django==3.0.6 django-debug-toolbar==2.2 urlpatterns = [ path('', HomeView.as_view(), name='home'), path('{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls), # Change admin url for security reasons. path('post/', include('post.urls')), path('author/', include('post.urls')), ] if DEBUG: import debug_toolbar urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns Problem At http://127.0.0.1:8000/ the debug toolbar shows. But at http://127.0.0.1:8000/post/1 it doesn't show. Could you help me? -
Django m2m check in pre/post_save signal
I want to be able to check if at least one of n many-to-many fields has been set before saving. I am using DRF alongside Django 3.0. I have a lot of models with many ManyToMany fields and I want to be able to check if at least one of certain fields is set. Also being tied to a certain serializer is not really an option since I want this rule to be checked even while updating etc. At first I wanted to do this with signals - post_save and m2m_changed. But whenever a model is saved with no m2m field set, the signal doesn't fire and I am unable to know if that field had been set in the request. The only option which I can think of is to set up some other thread that will fire up when post_save signal is received and will wait for m2m_changed signal. However I am not sure if these signals are fired up asynchronously or one by one. Could you please help me? -
Django Vue Js Axios has been blocked by CORS policy
Im using Django as backend and Vue as frontend, i use axios to make a request from Vue to Django. I know there is so many question about this, i've tried it all and wouldn't post a question if im not, i have been Googling it about 4 hours and yet still have the blocked by cors policy. I've tried: Django-cors-header, with its middleware Vue-axios-cors, got new error with this one Adding header Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials Adding / at the end of the url When i inspect it using fiddler, the POST request become OPTIONS, i have no idea whats happening. main.js import Axios from 'axios' Vue.config.productionTip = false Vue.prototype.$http = Axios const csrf = localStorage.getItem("csrftoken") if (csrf){ Vue.prototype.$http.defaults.headers.common['X-CSRFToken'] = csrf } Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*" Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET, POST, PATCH, PUT, DELETE, OPTIONS" Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, access-control-allow-origin, Authorization" Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Credentials'] = "true" Login.vue login(){ const header = { headers:{ 'Access-Control-Allow-Origin' : "*", 'Access-Control-Allow-Methods' : "GET, POST, PATCH, PUT, DELETE, OPTIONS", 'Access-Control-Allow-Headers' : "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, access-control-allow-origin, Authorization", 'Access-Control-Allow-Credentials' : "true", } } this.$http.get('http://127.0.0.1:8000/api/dashboard/login/',{ username: this.username, password: this.password, },header).then(function(response){ console.log(response) }).catch(function(error){ console.log(error) }) }, -
how to submit two forms in one go depend on the foreignkey
i have two tables(models) one for product name and features and the other for prices i normalized to database tables like this class Computer(models.Model): pc_model = models.CharField(max_length=60) Serial_number = models.CharField(max_length=60) quantity = models.IntegerField(default=0) and one for prices and features class Feature(models.Model): laptop = models.ForeignKey(Computer) price = models.IntegerField(default=1) Ram= models.IntegerField(default=0) Hard = models.IntegerField(default=0) how to submit this two models in one go (one submit button for both ) but Feature get the same laptop name as filled in Computer pre_save signals work in such cases ? -
Django - Select option from two dropdown menu and display filtered result in a third dropdown menu
I have got two dropdown options, country and number service location. Options for both can be selected from their respective dropdown. My objective is to display correct telephone number based on the selected country and number service location. You will also see my attempt to implement this functionality using Ajax in views below. Model created here - class DID_Number_Assignment_Model(models.Model): #DID Number Assignment country = models.ForeignKey(Country_Model, on_delete=models.CASCADE) number_service_location = models.ForeignKey(Number_Service_Location_Model, on_delete=models.CASCADE) did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE) Views.py def did_assignment_form(request, id=0, *args, **kwargs): if request.method =="POST": if id==0: form = DID_Number_Assignment_Model_Form(request.POST) if request.is_ajax(): country = request.GET.get('country') number_service_location = request.GET.get('number_service_location') filters = {'country': country, 'number_service_location': number_service_location} dids_searched = DID_Definition_Model.objects.filter(**filters) data = [] for dids in dids_searched: data.append({ 'country': dids.country, 'number_service_location': dids.number_service_location}) return HttpResponse({ 'success': True, 'data': data, }, content_type=content_type) else: return HttpResponse({ 'success': False, 'message': 'Only AJAX method is allowed.' }, content_type=content_type) template html file here - <form action="" method="post" autocomplete="off"> {%csrf_token%} <!--{{form|crispy}} !--> <div class="row", style = "position:relative; left:57px; top:100px"> <div class="col-md-7"> {{ form.country | as_crispy_field }} </div> <div class="col-md-7"> {{ form.number_service_location | as_crispy_field }} </div> <script type="text/javascript"> $(document).on('change', '.filter-dropdown', function() { var country = $('#countryDropdown').children('option:selected').val(); var number_service_location = $('#number_service_locationDropdown').children('option:selected').val(); if (country !== "" && number_service_location !== "" ) { var data = … -
Unable to encode context with utf8
I'm trying to get some objects for my javascript from my DB but I get the response with weird characters: const rules = JSON.parse("&quot;[{\&quot;model\&quot;: \&quot;rules.rule\&quot;, \&quot;pk\&quot;:... This is the view i'm using def import_consumptions(request): try: rules = Rule.objects.all() rules = serializers.serialize('json', rules) rules = json.dumps(rules) context = {} context['rules'] = rules return render(request, "import_consumptions.html", context) except: template = loader.get_template( 'pages/error-404.html' ) return HttpResponse(template.render(context, request)) And in my template javascript this is they way I get it: const rules = JSON.parse("{{rules}}") I know that must be something about encoding UTF-8 but i'm totally unable to get this. How can I get all those objects without those characters? Thanks in advance -
How to update primary key of and exsiting object in Django (with Postgresql)?
I need to change some of objects primary key in my django app, I wonder how can I achieve that? Also my model has relations with other models. -
refused to execute script from '<url>' its mime type ('text/plain') is not executable, and strict mime type checking is enabled
I am newbie in Django, and i was working on a Django app. And i used "media" folder to keep my css and javascript files (i know it's not a good practice) but it was working. Some lines of code <link href="/media/shop/bootstrap//css/bootstrap.min.css" rel="stylesheet"> <link href="/media/shop/bootstrap//css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="/media/shop/themes/css/bootstrappage.css" rel="stylesheet" /> <script src="/media/shop/themes/js/jquery-1.7.2.min.js"></script> <script src="/media/shop/bootstrap//js/bootstrap.min.js"></script> <script src="/media/shop/themes/js/superfish.js"></script> However what happened i don't know after somedays(today) when i opened this project again and tried to run on local host then i am getting error in console like this . After clicking on the link present in error it displays my javascript file but not executing it. And the most weired thing is that when i executed the same file in other system(also on local host) after transferring the same folder then it is working, no any such error in console. And the same project(website) is also hosted on internet and when i open that site online in my system again then also no any such error. However when i replace <script src="/media/shop/themes/js/jquery-1.7.2.min.js"></script> with <script type="javascript" src="/media/shop/themes/js/jquery-1.7.2.min.js"></script> then error not comes in console but it is still not working. I don't think there is any problem with browser setting because i checked in … -
Python Django URL render incorrect template
Sorry for my english. Have some problem with rendering template in Dgango. URLs is correct, but incorrect template returns. Screenshot: enter image description here So URL is correct, but it return me TASK-LIST, i expect TASK-DETAIL. Can't find the problem by myself.. VIEWS.PY from django.shortcuts import render from .models import Task from django.views import generic # Create your views here. def index(request): num_tasks = Task.objects.all().count() num_workers = Task.objects.all().filter(status='N').count() return render(request, 'index.html', context={'num_tasks':num_tasks,'num_workers':num_workers},) class TaskListView(generic.ListView): model = Task paginate_by = 2 def get_context_data(self, **kwargs): context = super(TaskListView, self).get_context_data(**kwargs) context['some_data'] = 'This is just some data' return context class TaskDetailView(generic.ListView): model = Task MODELS.PY from django.db import models from django.utils import timezone from django.urls import reverse #Used to generate URLs by reversing the URL patterns # Create your models here. class Task(models.Model): STATUS_CHOICES = ( ('A', 'Active'), ('R', 'Ready'), ('H', 'Hold'), ('N', 'Dont start') ) task_name = models.CharField(max_length = 200, help_text = 'Укажите наименование задачи') date_start = models.DateTimeField(default=timezone.now) date_end = models.DateTimeField(default=timezone.now) worker = models.CharField(max_length = 200, help_text = 'Укажите сотрудника, которому назначена задача') status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default = 'N') class Meta(): ordering = ('date_start',) def __str__(self): return self.task_name def get_absolute_url(self): return reverse('task-detail', args=[str(self.id)]) URLS.PY in App path: … -
Page doesnt renders remains the same on all links but URL is changed though or called(hit)
i im facing a problem that in URL it's been redirected but the page doesn't load it's showing the same page on all options in navbar page doesn't redirect even though URL is called while clicking it I have defined both the apps in the main project URL and even it shows no error as well but only the URL is changed on chrome but the page remains the same on all options I meanwhile clicking it doesn't load the page? -
Django, write custom message for auth user
I am using default Django username field as an email field. but when it displays error it says for username. how can i write custom error message for username already exists -
Docker-compose with Django, Redis, Gunicorn, Uvicorn, Nginx: Is my Nginx working?
I am trying to use docker-compose to setup the following: Container 1: gunicorn to serve django WSGI + uvicorn to serve django ASGI (for websockets) Container 2: redis server for websockets Container 3: nginx server to handle HTTP/websocket requests and direct them to WSGI/ASGI respectively However, after docker-compose up, my nginx server doesn't seem to be working. I can run the app stack with no issues in communications between redis/django but I don't see my ngnix working anywhere. My questions are: 1) How do I know that my nginx server is working? (i.e requests are not sent directly to gunicorn/uvicorn but via nginx) 2) Is this the correct setup? Heres my docker-compose.yml: version: '3.1' services: web_app_server: restart: always build: . container_name: web_app_server ports: - "8007:8765" - "8000:8000" redis_server: restart: always image: redis ports: - "6379:6379" nginx: image: nginx:1.13 ports: - 1337:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d depends_on: # <-- wait for djangoapp to be "ready" before starting this service - web_app_server At the end of the Dockerfile for building the web_app_server in docker-compose, I have CMD ./dockerfile_start.sh where dockerfile_start.sh contains: killall gunicorn killall uvicorn ./gunicorn_wsgi.sh & P1=$! ./uvicorn_asgi.sh & P2=$! wait $P1 $P2 with gunicorn_wsgi.sh: gunicorn locallibrary.wsgi:application --bind 0.0.0.0:8765 and uvicorn_asgi.sh uvicorn … -
Found elements with non-unique id
I have 3 posts on homepage and each have a comment form, I am using one form for all posts. I am using jQuery to disabled submit button if there are no text in input and also enable submit button if there is text in input. The problem is that each post submit button have same ID, how do i make button a unique id for each post ID? <span class="md-form"> <form enctype="multipart/form-data" class="feeds-form form-inline md-form form-sm" method="POST" action="{% url 'site:home' %}"> {% csrf_token %} <input type="hidden" value={{post.id}} name="post_comment"> <textarea name="comment_post" class="textinput textInput" placeholder="Add a comment..." required="" id="id_comment_post{{ post.id }}" onkeyup="if(this.textLength != 0) {submit.disabled = false} else {submit.disabled = true}"></textarea> <button type="submit" id="submit" disabled><i class="fas fa-paper-plane" aria-hidden="true"></i></button> </form> -
How to increase speed of React-Django app?
My application is really slow. The whole working day I'm not available to see my table content. I'm fetching data from my database using REST API and Axios. I'm not sure what is wrong inside my code. I would appreciate it if someone can troubleshoot my issue. This is a complete request I'm taking. This table is trying to show up the whole day. import React, { useState, useEffect } from 'react'; import Table from 'react-bootstrap/Table' import axios from 'axios'; import BootstrapTable from 'react-bootstrap-table-next'; import paginationFactory from 'react-bootstrap-table2-paginator'; import * as ReactBootStrap from 'react-bootstrap'; const IzlazniRacuni = () => { const [racuniIzlazniFinancijski, setRacuniIzlazniFinancijski] = useState([]); const [operateri, setOperateri] = useState([]); const [robnoArtikli, setRobnoArtikli] = useState([]); const [poslovneJedinice, setPoslovneJedinice] = useState([]); const [poslovniPartneri, setPoslovniPartneri] = useState([]); const fetchData = () => { const racuniIzlazniFinancijskiAPI = 'http://127.0.0.1:8000/api/Racuniizlaznifinancijski'; const operateriAPI = 'http://127.0.0.1:8000/api/Operateri'; const robnoArtikliAPI = 'http://127.0.0.1:8000/api/Robnoartikli'; const poslovneJediniceAPI = 'http://127.0.0.1:8000/api/Poslovnejedinice'; const poslovniPartneriAPI = 'http://127.0.0.1:8000/api/Poslovnipartneri'; const getRacuniIzlazniFinancijski = axios.get(racuniIzlazniFinancijskiAPI) const getOperateri = axios.get(operateriAPI) const getRobnoArtikli = axios.get(robnoArtikliAPI) const getPoslovneJedinice = axios.get(poslovneJediniceAPI) const getPoslovniPartneri = axios.get(poslovniPartneriAPI) axios.all([getRacuniIzlazniFinancijski, getOperateri, getRobnoArtikli, getPoslovneJedinice, getPoslovniPartneri]).then( axios.spread((...allData) => { const allRacuniIzlazniFinancijski = allData[0].data const allOperateri = allData[1].data const allRobnoArtikli = allData[2].data const allPoslovneJedinice = allData[3].data const allPoslovniPartneri = allData[4].data setRacuniIzlazniFinancijski(allRacuniIzlazniFinancijski) … -
Django: how to wrap DB function on top of the field while querying records from that model?
I have a text field in the model. Which holds the encrypted string in that field. Also, I have 2 functions in the DB to Encrypt and Decrypt. So, I want to wrap these DB functions on top of that field and save the encrypted string in the DB and while retrieving decrypt function should be wrapped on that field, and the object should have the decrypted string in that attribute. I am thinking of using the Custom Field in Django. Please suggest to me how to do that?