Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How can one unbind port 3306?
I am new to google cloud but was just able to deploy the test Django app that google provided in their documentation. This process included downloading the cloud_sql_proxy and running the following in the terminal (MacOS): ./cloud_sql_proxy -instances="my-instance-274702:us-central1:fms"=tcp:3306 This command starts running the proxy in order to connect locally to the DB in the cloud. Everything was working fine until I terminated the proxy with ctrl + C. When I ran the following command to start the proxy again I got the following error: ludovico@Ludovicos-MacBook-Pro django % ./cloud_sql_proxy -instances="my-instance-274702:us-central1:fms"=tcp:3306 2020/04/18 23:38:10 Rlimits for file descriptors set to {&{8500 9223372036854775807}} 2020/04/18 23:38:12 listen tcp 127.0.0.1:3306: bind: address already in use I got this error the first time I did this but I fixed it by shutting down the MySQL server that was running on port 3306. Now however, port 3306 is already bound to the cloud_sql_proxy and so it is throwing an error and is unable to start the proxy. If I run the same command with port 3307 it works just fine: ./cloud_sql_proxy -instances="my-instance-274702:us-central1:fms"=tcp:3307 But Django does not look for port 3307 it looks for port 3306. Is it possible to unbind port 3306? Better yet, is there a command … -
How can I loop thru a string in model Python?
I want to show Women League in template and here is my views.py code: leagues = League.objects.all() for league in leagues: print(league.name) It will show me all the name of the leagues which is: International Conference of Amateur Ice Hockey International Collegiate Baseball Conference Atlantic Federation of Amateur Baseball Players Atlantic Federation of Basketball Athletics Atlantic Soccer Conference International Association of Womens' Basketball Players American Conference of Amateur Football Atlantic Amateur Field Hockey League Transamerican Womens' Football Athletics Conference Pacific Ice Hockey Conference And how can I loop thru these name and pick out Leagues that have Womens' in it? -
Django Ajax form
I want to use Ajax in Django 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: raise Http404 My orders.views.py: @login_required() def checkout(request): try: … -
Dates are not sorted in correct order on website?
I am using this https://datatables.net/examples/api/multi_filter.html for HTML tables as it provides multiple features. My Django website passes on dates as strings to the frontend Collection Date in descending order and also datetime object to display on frontend HTML template. But it is not sorted correctly. This website has inbuilt sort facility which is not working fine. https://datatables.net/examples/api/multi_filter.html How to sort date string with format "%m-%d-%Y"? Please help me to resolve this. Thank you -
How to get other object field for ForeignKey Django
Firstly, I extend user like this: class MyProfile(models.Model): user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE) full_name = models.CharField(max_length=255, unique=True) id_number = models.CharField('ID Number', max_length=14) def __str__(self): return str(self.full_name) And then I want to get reference for full_name's field & id_number's field to other model like this: class MyModel(models.Model): full_name = models.ForeignKey(MyProfile, related_name='full_name_mymodel', to_field='full_name', on_delete=models.CASCADE) id_number = models.ForeignKey(MyProfile, related_name='ic_number_mymodel', on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.full_name) And this the form: class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal checkbox-inline' self.helper.label_class = 'col-lg-4' class Meta: model = MyModel fields = '__all__' full_name = forms.CharField(required=True, label="", widget=forms.TextInput(attrs={'class': "form-control"})) id_number = forms.CharField(required=True, label="", widget=forms.TextInput(attrs={'class': "form-control"})) description = forms.CharField(required=False, label="", widget=forms.TextInput(attrs={'class': "form-control"})) But it print both full_name instead of id_number for id_number's field like following picture: How to get full_name's object for full_name's field & id_number's object for id_number's field? -
Django + Uvicorn
I'm trying to use Django 3.0 with Uvicorn and getting this on start: INFO: Started server process [96219] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. I could turn lifespan off with the --lifespan off flag, but is there a way to have it work with Django? A quick search for Django + lifespan seems to not return anything.