Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django jwt channels cannot verify
I have two Django Projects sharing the same database. One is django-restframework One is django-channels django-restframework login will get JWT I cannot verify successfully in django-channels I wrote the test function restframework verify ok class Test(APIView): def get(self, request): try: token = UntypedToken( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0') print(token, 'token') except (InvalidToken, TokenError): print('InvalidToken, TokenError') return Response(status=status.HTTP_200_OK) channels verify error @database_sync_to_async def test_get_user(): try: token = UntypedToken( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0') print(token, 'token') except (InvalidToken, TokenError) as e: print('InvalidToken, TokenError', e) Can't verify JWT like this? -
ImportError: Couldn't import Django. with "poetry"
I configure django project with poetry. I created pyproject.toml and installed django. [tool.poetry] name = "graphene" version = "0.1.0" description = "" authors = ["yilmaz <yilmaz@gmail.com>"] license = "MIT" [tool.poetry.dependencies] python = "^3.9" #Django installed Django = "^4.0" psycopg2-binary = "^2.9.2" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" If I try adding django again: # venv is activated (base) ┌──(venv)─(t㉿kali)-[~/Documents/projects/graphql/graphene] └─$ poetry add django 1 ⨯ The following packages are already present in the pyproject.toml and will be skipped: • django If you want to update it to the latest compatible version, you can use `poetry update package`. If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`. Nothing to add. I created apps folder and want to add an app p manage.py startapp users apps/users this is giving me this error: 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? -
CSRF verification failed. Request aborted.No solution works for me on the internet
In my forms with the same token I add the @csrf_exemp, but since in login I am using the Django default I do not have a login view, I have put the token in each template and deactivated the MIDDLEWARE in settings and nothing to solve the problem too I have the host fine, I can register but not logging in nor in the django admin it gives me the same error. enter image description here {% extends "layout.html" %} {% block content %} {% load static %} {% load crispy_forms_tags %} <main style="min-height: 100vh"> <section> <div class="container p-4" style="min-height: 100vh"> <div class="row"> <div class="col-12 col-md-6 offset-md-3"> <div class="card bg-black"> <div class="card-body"> <h2 class="h3">Login</h2> <form method="post"> {% csrf_token %} {{ form | crispy }} <a href="{% url 'main' %}">Home</a> | <a href="{% url 'sign_up' %}">Sign Up</a> <input type="submit" class="btn btn-success" value="login" /> </form> </div> </div> </div> </div> </div> </section> </main> {%endblock%} -
exec: "--env": executable file not found in $PATH: unknown
I try to build a docker image of my Django App. The build is successful but when I run it, I've got this error : docker run -it -p 8888:8888 gads-api-monitor --env PORT 8888 docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "--env": executable file not found in $PATH: unknown. ERRO[0000] error waiting for container: context canceled Here's my pipenv : [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "4.0" gunicorn = "*" psycopg2-binary = "*" [dev-packages] [requires] python_version = "3.9" And my Dockerfile : FROM python:3.9-slim ENV APP_HOME /app WORKDIR ${APP_HOME} COPY . ./ RUN pip install pip pipenv --upgrade RUN pipenv install --skip-lock --system --dev CMD /usr/local/bin/gunicorn google_ads_api_monitor.wsgi:application --bind "0.0.0.0:$PORT" --env "DJANGO_SETTINGS_MODULE=google_ads_api_monitor.settings.production" I'm not sure to understand what "executable" is not found here. Gunicorn ? Or my Django settings file ? Many thanks ! -
How to prefill input box with future date in Django template?
I am trying to prefill an input field with a future date in a django template. <input name="expiration_date" class="form-control" id="expiration_date" type="text" data-toggle="input-mask" data-mask-format="0000-00-00" value="{{ object.table.expiration_date|default:'' }}" How could I set it so object.table.expiration_date|default:'' is prefilled with datetime.now() plus 30 days? -
Importing Model from different App - Getting Relative Import or No module Errors
I've read numerous Stackoverflows on this subject and unfortunately still don't understand what's going on and can't get this to work. I'm trying to import a model contained in a different app of the same project. I've tried just about everything including: from ProjectName.Appname.models import Class from ..AppName.models import Class import ProjectName.Appname.models (then reference via models.ClassName) from Appname.models import Class Nothing seems to work. I either get a no module error, or relative import error. Note, PyCharm doesn't show any errors and displays the location of the file/class when hovering over the import, so naming is correct. The error only occurs when running check. -
SSL/TLS Error when Testing Django API via HTTPS on Localhost
In an effort to test an API via an HTTPS connection locally, I followed the approach described here by Evan Grim where I use stunnel4 as a middleman between my requests and my API server. Here's a minimalist urls.py that will generate a token provided a valid username and password. from django.urls import include, path from django.contrib import admin from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path("admin", admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),] I have also modified the stunnel4 config file as below. pid= cert = stunnel/stunnel.pem sslVersion = all foreground = yes output = stunnel.log options = NO_SSLv2 [https] accept=8443 connect=8001 TIMEOUTclose=1 However, when I try any route via postman or curl (at port 8443), I receive the following errors. I get a tls_setup_handshake:internal error from stunnel4. 2021.12.19 18:51:22 LOG5[16]: Service [https] accepted connection from 127.0.0.1:36502 2021.12.19 18:51:22 LOG3[16]: SSL_accept: ../ssl/statem/statem_lib.c:109: error:141FC044:SSL routines:tls_setup_handshake:internal error 2021.12.19 18:51:22 LOG5[16]: Connection reset: 0 byte(s) sent to TLS, 0 byte(s) sent to socket Postman gives me the following error in its console when I submit requests through it. Error: write EPROTO 48081748826312:error:10000438:SSL routines:OPENSSL_internal:TLSV1_ALERT_INTERNAL_ERROR:../../third_party/boringssl/src/ssl/tls_record.cc:594:SSL alert number 80 And when I try curl, I see the following. curl: (35) OpenSSL SSL_connect: Connection … -
SearchVectorField - joined reference not allowed for taggit field
My model definition is as follows (a simplified model of the one being used in actual product. There are a coupe of other fields: from django.db import models from taggit.managers import TaggableManager from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Product(models.Model): tags = TaggableManager() search_vector = SearchVectorField(null=True) class Meta: indexes = [ GinIndex(fields=['search_vector']) ] I run make migrations and migrate commands. These work correctly. I then run the following set of commands to build the index: search_vector = SearchVector('tags__name') Product.objects.all().update(search_vector=search_vector) I end up getting the following error: django.core.exceptions.FieldError: Joined field references are not permitted in this query This is clearly caused by the tags__name field, but I am not sure how to solve it. Can someone please explain what I would need to do in order to run the above commands correctly? Thanks! -
How to unpack a Python queued job results?
I finally got to setting up RQ to help me with long running function calls in django, but I'm running into a problem with unpacking the values from a queue's result. I checked out the docs as per https://python-rq.org/docs/results/ but to no avail. Here's what my code currently looks like under views.py: def render_data(request): reddit_url = request.POST.get('reddit_url') sort = request.POST.get('sort') res = q.enqueue(run_data, reddit_url, sort) val1, val2 = res.result data = { 'val1': val1, 'val2': val2, } return JsonResponse(data) The expected response would be the returned values, but instead, in console I receive an error 500 along with createError.js:16 Uncaught (in promise) Error: Request failed with status code 500. In Heroku console, the error is File "/app/pc_algo/views.py", line 49, in render_data 'val1': val1, NameError: name 'users_data' is not defined Am I unpacking the jobs results wrong? I've tried looking up the error but I couldn't find a better tutorial on RQ results than the one above. -
Display file uploaded to Aws S3
https://s3.console.aws.amazon.com/s3/object/<Bucket_name>?region=us-east-2&prefix=media/<filename> is the url I want to save to my custom Abstractuser from file upload. How would you upload a file to override the user avatar field from the views.py? from django.shortcuts import render from .forms import UserProfileForm def index(request): return render(request,'home.html') The retrieving part works. <img class="profile-pic" src="{{user.avatar.url}}" > Will currently display the avatar associated with the user. https://s3.console.aws.amazon.com/s3/object/<Bucket_name>?region=us-east-2&prefix=media/default.png Settings.py MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION ) DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.MediaStorage' -
Django cannot find new modules, using pyenv and virtualenv
I’m sure this is pretty straightforward to someone experienced. I’m learning Django through the Wedge of Django ebook. I’m using Python 3.8.7 installed via pyenv like so: pyenv install 3.8.7 Then I’ve set up a virtualenv like so: pyenv virtualenv 3.8.7 everycheese I activate the virtualenv in my repo like so: pyenv local everycheese The environment is shown as active in the prompt, as it starts with (everycheese). The main project is cloned from Django Cookiecutter https://github.com/cookiecutter/cookiecutter-django I’ve then used pip to install requirements from the requirements.txt files. However - I’m running into trouble when I try to add new packages (by adding the package to requirements.txt as a new line and installing again with pip). pip list, or pip freeze both show the new module. But when I add the module to my INSTALLED_APPS and try to import it in my models.py file, Django cannot find it. When I type which python, and which pip, they point to different directories and I think this may be part of the problem but I am stuck. -
Django CKEditor change color
How change black color dialog window widget Django-CKEditor? Due to the black color background, not visible black text in django admin. Or tell me where the text color of Django-CKEditor dialog boxes changes. -
Forbidden (CSRF token missing.) error when trying to make a POST request. Using React (Axios) and Django
I've been trying to solve this issue in various ways for awhile now, but every answer I have seen on here has not worked for me yet. I am running React (and Redux) on my localhost:3000, and Django on localhost:8000. I'm very still new to this, but I have seen posts where people have said to include csrf token in the header where the axios post is taken place, but that hasn't worked for me. I've also tried fiddling with settings.py, but none of that has worked as well. This is what I had before researching just to hopefully get a base. Thank you! Here is my /actions/auth.js import axios from 'axios'; import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL, } from './types'; // login function export const login = (email, password) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json', }, }; const body = JSON.stringify({ email, password }); try { const response = await axios.post( `${process.env.REACT_APP_API_URL}/auth/jwt/create/`, body, config ); dispatch({ type: LOGIN_SUCCESS, payload: response.data, }); dispatch(load_user()); } catch (err) { dispatch({ type: LOGIN_FAIL, }); } }; settings.py """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR … -
How properly add async methods to DRF application ? what is the best approach for it: Asyncio or Celery?
I'm a new to async in django and want to make some experiments with it. Exactly wan to make my CRUD methods in DRF async at least. Asyns I mean approximelty the same dehaviour as JS async\await. What I need to start from: Asyncio or Celery ? May be some articles and sources to read . Thanks ! P.S. using django 4.0 (just updated), drf 3.13.1 -
Flask return a proper list object to test in Postman
im currenty doing some work for school; i have a flask app and some postman tests that i have to pass, one of which requests an array of dicts (something like [{dict1}, {dict1},..]) ive been trying to return this: result = [{ "reservationUid": data["reservationUid"], "status": data["status"], "startDate": data["startDate"], "tillDate": data["tillDate"], "book": book_data, "library": library_data }] ive used jsonify(), dumps() + mimetype='application/json', make_response() but nothing really helped, it seems like if i do so, postman wont count that as a json but as an undefined? for example, for return Response(dumps(result), mimetype='application/json') it returns TypeError: Cannot read property 'status' of undefined here is the part of the test where it dies: const response = pm.response.json(); pm.expect(response).to.be.an("array") const reservation = _.find(response, { "reservationUid": reservationUid }) pm.expect(reservation.status).to.be.eq("RENTED") pm.expect(reservation.startDate).to.be.not.undefined pm.expect(reservation.tillDate).to.be.not.undefined tho my response data returns looks like [ { "reservationUid": "f464ca3a-fcf7-4e3f-86f0-76c7bba96f72", "status": "RENTED", "startDate": "2021-10-09", "tillDate": "2021-10-11", ... <some more data here> } ] basically status is actually "RENTED" like required. for django apps that return serializers data with many=True field such tests work just fine, but since u cant just return an array in flask this gets so complicated :( my best solution is to redirect my requests to the django app but isnt … -
Django - create multiple tables from Excel sheets
Forgive me for the relative naivete of this question...I inherited a Django project with zero Django experience myself so I'm trying to keep this thing running while teaching myself the framework at the same time. I have an Excel workbook with multiple sheets and I want to be able to create a table for each sheet. The workbook comes from an API, so I'm using requests to download the workbook. I'm familiar with downloading an Excel workbook and creating a dataframe for each tab, but I'm not sure how to pass multiple dataframes on to multiple models within Django without making the get request one time for each of the sheets. Here is an example of my update command for a flat file get request: import os import pandas as pd import sys import json from datetime import date, datetime from utils.update_dataset_command import UpdateDatasetCommand class Command(UpdateDatasetCommand): app_label = 'my_app' model_name = 'table1' def pull_data(self, fields): # Pull the dataset from get_request = requests.get('URL.csv') dataframe = pd.read_csv(get_request.content) return dataframe What I'm trying to achieve is to be able to do something like: Class Command(UpdateDatasetCommand): app_label = myapp model_names = ['table1', 'table2', 'table3'] def pull_data(self, fields): get_request = requests.get('URL.xlsx') Excel = pd.ExcelFile(get_request.content) … -
Prefetch query with relational conditions - Django
I'm trying to make a request that prefetch all the data to reduce the amount of requests to my database. I'm using the prefetch_related() method and the Prefetch object class to tell what to load in the same request, here is my code: pairs_queryset = Pair.objects.filter(quote_id="2781", last_price__isnull=False) \ | Pair.objects.filter(quote_id="825", last_price__isnull=False) \ | Pair.objects.filter(quote_id="3408", last_price__isnull=False) queryset = Portfolio.objects.prefetch_related( Prefetch('connections__wallets__currency__metadata__images'), Prefetch('connections__wallets__currency__base_pairs', queryset=pairs_queryset), ).get(id=portfolio_id) data = Serializer(queryset).data My problem here is that I have multiple base_pairs in my database that depends on the Connection model. So I would like to add a filter that depends on a value contained in on of the previous models (i.e. connection) of the prefetch. As connections is a set (multiple values), I want that the following: connections__wallets__currency__base_pair retrieve the base_pair related to the connection currently fetched. Here is a diagram: connections__wallets__currency__base_pairs ^ |_______________________________| depends on I read the documentation and couldn't find any solution. Is it possible? -
Stuck creating a django posts filter
I need to filter the posts by the options selected between: "most commented" "category" "date". This is actually my code: models: class BlogPost(models.Model): class BlogPostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='publicado') options = ( ('borrador', 'Borrador'), ('publicado', 'Publicado') ) categoria = models.ForeignKey(BlogCategoria, on_delete=models.PROTECT,default=1) titulo = models.CharField(max_length=250) excerpt = models.TextField(null=True) contenido = models.TextField() slug = models.SlugField(max_length=250, unique_for_date='publicado',null=False, unique=True) publicado = models.DateTimeField(default=timezone.now) autor = models.ForeignKey(Usuario,on_delete=models.CASCADE,related_name="autor") status = models.CharField(max_length=10,choices=options,default='borrador') imagen = models.ImageField(default= "empty.jpg" ,null=True, blank = True) objects = models.Manager() postobjects = BlogPostObjects() class Meta: ordering = ('-publicado',) db_table= "blog_post" view: class BlogInicio(ListView): template_name = "Blog/blog_inicio.html" model = BlogPost context_object_name = "posts" paginate_by = 9 def get_queryset(self): return BlogPost.postobjects.all() -
how to update a form inside a class based detail view?
I created a survey form for each user which the staff user can fill it for them. I created a detail view and added formMixin just like this: class ScientificInfoView(FormMixin, DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' form_class = ScientificInfoForm def get_success_url(self): return reverse('scientific-info', kwargs={'pk': self.object.pk}) def get_context_date(self, **kwargs): context = super(ScientificInfoView, self).get_context_data(**kwargs) context['form'] = ScientificInfoForm() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): f = form.save(commit=False) f.user = self.object.user f.save() return super(ScientificInfoView, self).form_valid(form) it works just fine but I want the staff to be able to edit and update these forms as well. If I click on the object and refill the form it wouldn't update the previous one but makes a new object for that user. I don't want that. I need to somehow change this view to update the view if the user has this object already. I created a dashboard that divides those who have filled forms and those who haven't. I want the filled ones to get redirected to the update view, not the detail view I wrote. is there a way to update this one or should I create … -
Debug Celery tasks without CELERY_ALWAYS_EAGER
I'm facing an issue with Debugging Celery tasks running in a chain. If I set the CELERY_ALWAYS_EAGER configuration the tasks will run on the same process one by one and I'm able to Debug. but, when I set this configuration another problem is raised, I have an issue creating a socket. socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP) I get an error: _sock = _realsocket(family, type, proto) error: [Errno 1] Operation not permitted I can guess it's a result of the CELERY_ALWAYS_EAGER configuration. How can I handle this issue? -
I can't create a form with password1 password2 in Django
error:Unknown field(s) (password1, password2) specified for User I have no idea why it doesn't work as documentation says Documentation: class UserCreationForm¶ A ModelForm for creating a new user. It has three fields: username (from the user model), password1, and password2. It verifies that password1 and password2 match, validates the password using validate_password(), and sets the user’s password using set_password(). My forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] my views.py class CreateUserView(CreateView): model = User form = CreateUserForm template_name = 'registration/register.html' fields = ['username', 'email', 'password1', 'password2 ] class UserLoginView(LoginView): next_page = "home.html" '] urls.py urlpatterns = [ path('register/', CreateUserView.as_view(), name='register'), ] -
CRIPSY FORMS InvalidCursorName at html file
i'm new to Django but so far i developed a lot of beginner projects. Since i want to share the stuff and learn the last step of django(deployment) i started to dig into Docker containers and AWS deploying methods. My project works perfectly on the local server without docker but when i put it into container and run i have the error in my form page which shown below; InvalidCursorName at /request/form_request / cursor "_django_curs_140621549230904_sync_2" does not exist Request Method: GET Request URL: http://127.0.0.1:8000/request/form_request%20/ Django Version: 3.2.10 Exception Type: InvalidCursorName Exception Value: cursor "_django_curs_140621549230904_sync_2" does not exist Exception Location: /py/lib/python3.9/site-packages/django/db/models/sql/compiler.py, line 1178, in execute_sql Python Executable: /py/bin/python Python Version: 3.9.9 Python Path: ['/app', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/py/lib/python3.9/site-packages'] Server time: Sun, 19 Dec 2021 15:37:57 +0000 Error during template rendering In template /py/lib/python3.9/site-packages/crispy_forms/templates/bootstrap/field.html, error at line 30 cursor "_django_curs_140621549230904_sync_2" does not exist {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} 22 <div class="controls"> 23 {% if field|is_checkbox and form_show_labels %} 24 <label for="{{ field.id_for_label }}" class="checkbox {% if field.field.required %}requiredField{% endif %}"> 25 {% crispy_field field %} 26 {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %} 27 </label> 28 {% include 'bootstrap/layout/help_text_and_errors.html' %} 29 {% else %} 30 {% crispy_field … -
guidance with Dj-rest-auth and implementing google login in flutter app
I have a flutter application with a DRF back end. currently using Dj-rest-auth for regular authentication (token). I'm at a point where I'd like to implement social authentication (specifically Google). I searched a few resources but still don't quite get the workflow. https://github.com/iMerica/dj-rest-auth/pull/336/commits/8f5cc65049c4bcb0c650bde707f5023013497b20 my guess is: you set up your application on google cloud console. You make a request to get an "access token" to the google auth on the Frontend (in my case flutter) send that access token to your Back end - django to confirm. which then sends back a regular token for authentication? Any guidance would be appreciate. -
Django intermittent multithread shared queue
I am trying to solve this simple problem in django the Correct Way Worker1(thread): django connected to serial device streaming data ~ 1kb/s Consumer1(thread): reads FIFO (queue) and processes the data as it enters the fifo **the consumer will run intermittently How do I pass the queue object to the newly created consumer if the worker is already running with its own queue? I use memcached. I could pass the queue object that way? The example below works because i use globals. In Django views this will not be the case. My consumer will start in a fresh def that is triggered by a url... stop_thread=False q=queue.Queue(maxsize=100) connectSerial() t2= threading.Thread(target=consumer,args=(q),daemon=True).start() time.sleep(5) stop_thread=True def connectSerial(): ser = serial.Serial() ser.baudrate = 1000000 ser.timeout=1 ser.port = '/dev/ttyACM2' ser.open() t1 = threading.Thread(target = readSerial, args = (ser), daemon = True).start() def readserial(ser): global stop_thread,q msg = bytearray() buf = bytearray() #trimmed at open must add back while True: if(stop_thread): break try: while True: timelast=time.time() i = max(1, min(2048, ser.in_waiting)) msg = ser.read(i) buf.extend(msg) a= msg[0:1][0] q.put(a) break except Exception as e: stop_thread=True ser.close() break stop_thread=True ser.close() def consumer(): global stop_thread,q while not stop_thread: if not q.empty(): a=q.get() b=a*100 print(b) -
django template variable - uncaught referenceerror i is not defined
I have this code in html template: {%for i in result %} <tr> <td id="tdId_{{ i.id }}1">{{i.1}}</td> <td id="tdId_{{ i.id }}2">{{i.2}}</td> <td id="tdId_{{ i.id }}7">{{i.7}}</td> <td id="tdId_{{ i.id }}8">{{i.8}}</td> <td id="tdId_{{ i.id }}9">{{i.9}}</td> <td id="tdId_{{ i.id }}10">{{i.10}}</td> <td id="tdId_{{ i.id }}4">{{i.4|date:'Y-m-d H:i'}}</td> <td><input type="datetime-local" id="tdId_{{i.id}}5"/></td> <td><button value="{{i.id}}" type="button" onclick="setEndActivity({{i.id}})">End</button><td/> <!-- <td><button value="{{i.id}}" type="button" onclick="setEndActivity(this.value)">End</button><td/> --> </tr> {% endfor %} It writes error message: Uncaught ReferenceError: i is not defined at setEndActivity ((index):198) at HTMLButtonElement.onclick ((index):68) setEndActivity @ (index):198 onclick @ (index):68 The commented line didn't help.