Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I can't install pillow with pip
I created a ImageField in model.py file and when I tried to run Python gave me an error. It says I have to install pillow . So I typed pip install pillow command. Then it started installing and after some time (though I thought it was successfully installed) it gave another error and said that it was not successfully installed. It gave me bunch of red colored text that I didn't understand. -
How can I update sqlite3 after any time login in Django 2.2?
I use from django.contrib.auth.models import User in Django for Authentication. I want update 1 column of auth_user table when any user login. @login_required def showmap(request): return render(request,'index.html') -
Django pass a filtered query set between class based views
I have a Django class based ListView, which is filtered within its get_queryset function, using url parameters from a filter form, that returns an object_list. Now I want to export the filtered content of the ListView by using a button that calls a second class based view for exporting the list to a .csv file. Both views are not the problem, but how do I get the data from the ListView, after its filtered, to the export view. Tried something with sessions, but did not get that to work. Perhaps it is possible to hand over the filter parameters but I always ran into problems with the request.session cache, which seems not to be available, even if everything necessary is enabled in the settings. Any ideas for a good approach on this? Everything I read so far about sessions did not help especially with class based views. -
Django. Submitting form with valid data returns http 405 after submission with invalid data
trying to implement crud with ajax and got stuck with this error. When I fill the form with correct data it works perfectly fine, but if I try to submit the form with an invalid data to verify error handling and then re-submit it I get 405 error returned. The only thing what comes into my mind is problem with repeatable csrf_token verification, but I guess I'm incorrect... Here is my view for processing request: def create_employee(request): data = dict() if request.method == "POST": form = AddEmployee(request.POST) if form.is_valid(): form.save(commit=False) form.instance.works_for = request.user.works_for form.instance.property_id = request.user.property_id form.save() data.update({'form_is_valid': True}) employees = User.objects.filter(property_id=request.user.property_id) data.update({'html_single_employee': render_to_string('single_employee.html', {'object_list': employees})}) else: data.update({'form_is_valid': False}) else: form = AddEmployee() context = {'form': form} data.update({'html_partial_employee_create': render_to_string('partial_employee_create.html', context, request=request )}) return JsonResponse(data) Here is HTML with js: {% extends "base.html" %} {% block content %} <!-- Button that triggers modal with form to add an employee --> <div class="row mt-1 ml-3"> <button id="OpenCreateEmployeeModal" type="button" class="btn btn-dark btn-sm open-modal"> Add employee </button> </div> <!-- Modal itself --> <div class="modal fade" id="CreateEmployeeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> {% include "partial_employee_create.html" %} </div> </div> </div> <!-- Personell display section --> <div class="container"> <div class="row justify-content-center"> <table … -
Is it possible to change the management/commands directory in Django?
In Django it's possible to write custom management commands. These are stored by default in the proj/app/management/commands directory of your application. Is there a way to change this location to a custom directory? E.g. /proj/cmd/? For example, to change the migrations directory you can use the MIGRATIONS_MODULES setting. Is there an equivalent for management commands? It doesn't appear to be documented. -
Retrieve a python list from external python file(Django)
I'm trying to retrieve a python list that generates from an external python file(algorithm.py). In algorithm.py has a set of functions that used to generate a python list. There is no issue with algorithm.py file and it generates the python list as I expect. I followed the below steps to get the python list which generates in algorithm.py into views.py. 1.) Pass a variable(lec_name) from a function in views.py to algorithm.py and retrieve the output by using stdout as the below statement. lec_name = request.POST['selected_name'] result = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) 2.) And then when I print(result.stdout), I receive the output(the python list which I expect) as an array of byte as below. b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]\r\n" 3.) Then I used print((result.stdout).strip()) to remove \r\n and It gives output as below. b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]" This gives the python list which I expect as an array of byte So what I need, retrieve the output(the python list which I expect) as a python list. How can I solve this? I tried lot of things, but none succeeded. I'm using Python 3.7.4, Django 3.0.1 -
Django + React. Set-Cookie does not set cookie (CORS enabled)
I have a React app, working with Django back-end. I have an authorization URL, I send axios.post() to the URL, and Django responses me back with a Set-Cookie header, but the cookie will not be set for some reason, even if I have CORS-policy configured like this: settings.py INSTALLED_APPS = [ 'MyApp.apps.MyAppConfig', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", # 3000 - React port "http://localhost:8000", # 8000 - API port "http://127.0.0.1:3000", "http://127.0.0.1:8000" ] Form sending code: const url_to_send = `${this.state.api_base_url}:${this.state.api_base_port}${this.state.api_user_url}/login/`; axios.post(url_to_send, `username=${this.state.username}&password=${this.state.password}`, {}, { withCredentials: true, }) Request headers: POST /api/v1.1/user/login/ HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Content-Length: 42 Accept: application/json, text/plain, */* Sec-Fetch-Dest: empty User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36 DNT: 1 Content-Type: application/x-www-form-urlencoded Origin: http://localhost:3000 Sec-Fetch-Site: cross-site Sec-Fetch-Mode: cors Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US;q=0.9,en;q=0.8,bg;q=0.7,kk;q=0.6 Response headers: HTTP/1.1 200 OK Date: Sun, 19 Apr 2020 09:56:27 GMT Server: WSGIServer/0.2 CPython/3.6.9 Content-Type: application/json X-Frame-Options: DENY Vary: Cookie, Origin X-Content-Type-Options: nosniff Content-Length: 31 Access-Control-Allow-Origin: http://localhost:3000 Set-Cookie: csrftoken=dajeDwkCNv84lbhZ9xEqLCU5zr9BedlIgvgzrjFQJfcWTI9JYuf3jWtDpZwH9dn3; expires=Sun, 18 Apr 2021 09:56:25 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=9f50dovwlfia1ismtnlcr449dw55ljht; expires=Sun, 03 May 2020 09:56:25 GMT; HttpOnly; Max-Age=1209600; … -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 30: 'else'. Did you forget to register or load this tag?
Error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 30: 'else'. Did you forget to register or load this tag? This is the display i do get -
Using the URLconf defined in products.urls, Django tried these URL patterns, in this order:
*from django.urls import path, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('products/',include('products.urls')), path('accounts/',include('accounts.urls')), ]* The above code of pyshop/url.py I could not login to admin page. -
Authorize client with a model other than User
In DRF, You can create custom authentication classes and schemes. But in the end, all of them should return a tuple of (user, auth). I have a special case where my endpoints are going to get called by multiple servers and each one of them has their unique secret, stored in the Server model and table in my app. How I can implement authentication of these servers while the entity being authorized is not a User, but some other model? This is my current code (not tested): from rest_framework import authentication from rest_framework import exceptions from .models import Server class ServerAuthentication(authentication.BaseAuthentication): def authenticate(self, request): server_name = request.META.get('X_Server') server_secret = request.META.get('Authorization') if not server_name or not server_secret: return None try: server = Server.objects.get(name=server_name, secret=server_secret) except Server.DoesNotExist: raise exceptions.AuthenticationFailed('No such server') return server, None -
JS function not working in Django template
{% extends 'home.html' %} {% load static %} {% block title %}Customer{% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form }} Date of Birth:(dd/mm/yyyy) <label> <select id="day"> <option value="1" onclick="day()">1</option> </select> </label> <label> <select id="month"> <option value="1" onclick="month()">1</option> </select> </label> <label> <select id="year"> <option value="1" onclick="year(">1</option> </select> </label> <button type="submit">Submit</button> </form> {% endblock %} JS file function day() { let dd = 1; for (dd = 1; dd <= 31; dd++) { document.getElementById("day") document.write("<option value=" + dd + ">" + dd + "</option>") } } function month() { let mm = 1; for (mm = 1; mm <= 12; mm++) { document.getElementById("month") document.write("<option value=" + mm + ">" + mm + "</option>") } } function year() { let yy = 1950; for (yy = 1950; yy <= 2020; yy++) { document.getElementById("year") document.write("<option value=" + mm + ">" + mm + "</option>") }} js function is not working i can't understand what happened i create separate file where i declare functions for date of birth form but it's not response any thing except the html -
Obtain DRF JWT token for users with no password set
I am building a Django Rest Framework backend and Angular frontend. I am using dj-rest-auth to authenticate the user with Discord. This all works fine. I want to use django-rest-framework-jwt to authenticate my calls from my frontend to my backend. You can use obtain_jwt_token from the package, but this requires a username and password. Since my users are logging in with Discord, I have user.set_unusable_password() in my UserManager. How can I obtain and refresh JWT tokens if the users have no password set? Also, how does one even access a user's password from their UserModel to pass it to the obtain_jwt_token URL? Thank you -
Django - Problems with Ajax Form
Hi I'm trying to develop an e-commerce website using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") else: … -
Django 2.2.4 TypeError at /accounts/login __init__() takes 1 positional argument but 2 were given
TypeError at /accounts/login init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login Django Version: 2.2.4 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: E:\Python\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 blogsite/blogsite/urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth import views from django.contrib.auth.views import LoginView as auth_login from django.contrib.auth.views import LogoutView as auth_logout urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('accounts/login',auth_login,name='login'), path('accounts/logout',auth_logout,name='logout',kwargs={'next_page':'/'}) ] blogsite/blog/urls.py from django.urls import path,re_path from . import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), re_path(r'^post/(?P<id>\d+)$',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.CreatePostView.as_view(),name='post_new'), re_path(r'^post/(?P<id>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'), re_path(r'^post/(?P<id>\d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.DraftListView.as_view(),name='post_draft_list'), re_path(r'^post/(?P<id>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'), re_path(r'^comment/(?P<id>\d+)/approve/$',views.comment_approve,name='comment_approve'), re_path(r'^comment/(?P<id>\d+)/remove/$',views.comment_remove,name='comment_remove'), re_path(r'^post/(?P<id>\d+)/publish/$',views.post_publish,name='post_publish'), ] -
Retrieve a python list from external python file
I have this script: lec_name = request.POST['selected_name'] out = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) strVal = (out.stdout).strip().decode("utf-8") print(strVal) This script works fine and returns a python list from an external python file as a string(str). [['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']] But I want that returned python list as a list, not as a str. I tried many similar solutions but nothing helped. How can I achieve this? Is there any better way to achieve what I need? I'm using Python 3.7.4, Django 3.0.1. -
Can I set multiple Static Roots in django?
My problem: I already have a static folder for .css .js and images. But I have another directory in my server that stores recorded video, which keeps populating on a daily basis. I want django to be able to access files from that directory, where the videos keep populating. What can be the solution to this? Is it possible to make multiple static roots? -
for engine in engines.all: TypeError: 'method' object is not iterable why? in django project
[ hello ,this code can not run with error for engine in engines.all: TypeError: 'method' object is not iterable ]1 -
How do i access wordpress data/dashboard?
So, I have created a custom dashboard using Django. I want to access all the fields(activeplugins, active themes, wordpress version, etc) present in my wordpress dashboard and display it in my dashboard. -
Django Redirect after POST
I have a Django ModelForm which is rendering fine on the frontend and would like the page to redirect to the home page after POST. When I fill out the form and click submit, I can see the POST come through in the terminal with a status of 302 and does not run the redirect. If I remove the redirect in my views and post the data from the frontend, the POST comes through with a status of 200. #views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import OptInForm from django.forms import forms def index(request): return render(request, 'pages/index.html') def arthritis(request): form = OptInForm() if request.method == 'POST': form = OptInForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('index') else: form = OptInForm() return render(request, 'pages/physical_therapy/arthritis_pain.html', {'form': form}) Here is the form which the view is pulling from: #forms.py from django.forms import ModelForm from .models import OptIn class OptInForm(ModelForm): class Meta: model = OptIn fields = ['first_name', 'last_name', 'email', 'phone'] This is the model: #models.py from django.db import models from django.forms import ModelForm from datetime import datetime class OptIn(models.Model): opt_in_option = models.CharField(max_length=50, blank=True, choices = OPT_IN_CHOICES) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=40, blank=False) phone = … -
How to connect the external independent template(contains of javascript and ajax) with django backend to POST the zip file to external template
connect the external independent template(contains of javascript and ajax) with django backend to pass the image from front end and get the image in backend convert into the zip file and post to external javascript template -
datetime field in django response json
I am using the following codes with django. The results are coming. But can we make the startDate and endDate fields I want return as datetime? On the frontend side, it warns that the startDate and endDate information comes as strings. I want to prevent this API url: http://127.0.0.1:8000/api/appointments/list?user=2&groupCode=1453&startDate=2020-04-17+10:00:00&endDate=2020-12-12+08:00:00 views.py ` class AppointmentsListAPIView(ListAPIView): serializer_class = AppointmentsCreateSerializer permission_classes = [IsOwner] def get_queryset(self): queryset = Appointments.objects.filter(user=(self.request.query_params.get('user')), groupCode=(self.request.query_params.get('groupCode')), startDate__gte=(self.request.query_params.get('startDate')), endDate__lte=(self.request.query_params.get('endDate'))) return queryset ` model.py ` class Appointments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=0, blank=False) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=False) note = models.CharField(max_length=100, blank=True) startDate = models.DateTimeField(blank=True) endDate = models.DateTimeField(blank=True) title = models.CharField(max_length=90, blank=True, default=0) allDay = models.BooleanField(default=False) modifiedDate = models.DateField(auto_now=True) groupCode = models.CharField(max_length=50, blank=False) appointmentsKey = models.UUIDField(editable=False, default=uuid.uuid4, blank=False) created_userKey = models.UUIDField(editable=False, default=uuid.uuid4) createdDate = models.DateField(auto_now=True, editable=False) ` response ` [ { "user": 2, "customer": 41, "appointmentsKey": "e9adbadb-342e-4b03-9505-59d7b5312582", "created_userKey": "47f332f1-cc7c-4067-a43a-98939186ab31", "createdDate": "2020-04-19", "modifiedDate": "2020-04-19", "groupCode": "1453", "note": "", "title": "1", "startDate": "2020-04-22T06:00:00Z", "endDate": "2020-04-22T06:30:00Z", "allDay": false } ] ` on the frontend side the following fields are string, but want it to come as datetime "startDate": "2020-04-22T05:00:00Z", "endDate": "2020-04-22T05:30:00Z", -
DJANGO PASS THE VALUE OF INPUT TO URL VIEW
i want to pass the value of input form to my view.py with {% url %} so i have this form in my .html <form> <input id="demo" type="text" name=""> </form> <button onclick="myFunction({{no}})">Start</button> <button onclick="myFunction(1)">Stop</button> with some script so i dont wanna use django forms <script> var elements = {{dataset|safe}}; function random_item(items) {return items[Math.floor(Math.random()*items.length)];} function myFunction(x) { if (x == 0){inter = setInterval( function myFunction() { document.getElementById("demo").value = random_item(elements)}, 30);} else { clearInterval(inter)} } </script> and this in my url app paternn urlpatterns = [ path('',views.index, name='index'), path('<int:no>/',views.index,name='submit') ] this is my view def index(request,no=0): if no == 0: show data else: input data to another table based on no and update data return render(request, 'undian_wombastis/undian.html', context) i have read that i can use json to pas with request.method but is there a way so i can use it like this thankyou -
How to override the get method of model object
I have 3 models User, Role and UserGroup. Model User is an extended model of AbstractBaseUser. Model Role has just one field role_name and model UserGroup has two foreign_key field role and user. I want to insert a record into model UserGroup but since both fields of UserGroup are foreign_key it will only accept model instances of UserGroup.user and UserGroup.role or else it will raise a value error. So, in my APIView I did this - user_group{} user_group['role'] = Role.objects.get(pk=2) user_group['user'] = User.objects.get(pk=1) print(user_group) After executing the above code the value of user_group is - {'role': <Role: Role object (2)>, 'user': <User: pqw109@inc.com>} When I pass user_group to UserGroupSerializer it raises an error because I have defined user field as an integer in UserGroupSerializer. I am writing exactly same query method i.e get() for the objects of both the models but the output is different. What I want is just like field role I want the value of user field as <User: User object (1)>. {'role': <Role: Role object (2)>, 'user': <User: User object (1)>} this is how I am expecting user_group dictionary. I know this can be achieved by overriding the default get() method of manager but I am … -
Django Graphene Returning list of DjangoObjectTypes as opposed to list of Models causes client to override previous results
I'm crossposting this from the repo's issue: https://github.com/graphql-python/graphene-django/issues/938 I have this graphene node class TripNode(DjangoObjectType): legs = List(LegNode) # Need explicit pk when forming TripNode manually and querying for id pk = String(source="id") class Meta: model = Trip interfaces = (relay.Node,) The resolver fetches some remote data and resolves legs there since legs is derived from that remote data as well. def resolve_trips(root, info, **kwargs): response = requests.get("") return [ TripNode( **{ "id": uuid.uuid4(), "origin": trip["origin"], "legs": [ TripLeg( origin_hub=leg["flyFrom"], id=uuid.uuid4(), ) for leg in trip["route"] ], } ) for trip in response.json()["data"] ] Usually I would instead return a list of Trips but I can't use the Django model here because I am resolving the extra field legs that does not exist in the model. One reason it doesn't is that it must be ordered so a one-to-many field would not suffice without some addition. If I do return a list of Trips without legs, it works fine and the client doesn't overwrite the previous query results with the new ones. But that weird overwrite behavior does occur when I use TripNode instead, and that's the only difference. I think it has to do with some graphQL standard not … -
How can I add / in my string as a paramter in django url?
I have land numbers such as '171/20' , '23','34/112/1' , etc. on passing these as a parameter I should be able to fetch info about them. The problem is I can't do something like we do normally. because it will be like localhost:8000/171/20 which is not what I want exactly.