Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why i am getting a error like no module found
[enter image description hereenter image description here](https://i.stack.imgur.com/fST8f.png) when i am trying to migrate this file i am getting the module error how must i needd to remove that error from the vs code and run properly,This error is even occuring after i have done pip install. -
Migrations not working on azure and django
i'm facing some problems with Django on my azure resource group. The main page of my landing is working fine, but when i try to log in, it does not work, and i get the error that it has ben caused by the "Accounts application" Error: relation "accounts_user" does not exist LINE 1: ...s_user"."admin", "accounts_user"."timestamp" FROM "accounts_... I've performed the migrations on the SSH, but i think that they are not being properly migrated, since even when i "Create a superuser" the user that i've just created does not work to log in and throw the same error. Although it the variables for the database seem to be sent correctly, as i can see on the local variables on the error: ignored_wrapper_args (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7a01ddf85cc0>, 'cursor': <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7a01d58667a0>}) params ('USER EMAIL',) self <django.db.backends.postgresql.base.CursorDebugWrapper object at 0x7a01d58667a0> sql ('SELECT "accounts_user"."id", "accounts_user"."password", ' '"accounts_user"."last_login", "accounts_user"."email", ' '"accounts_user"."full_name", "accounts_user"."active", ' '"accounts_user"."staff", "accounts_user"."admin", ' '"accounts_user"."timestamp" FROM "accounts_user" WHERE ' '"accounts_user"."email" = %s LIMIT 21') And: DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'MY HOST NAME.postgres.database.azure.com', 'NAME': 'MY DATABASE NAME', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': … -
JWT Refresh token is not generating on Login
I am doing a django project, using dj-rest-auth, and jwt token. When registering a user, the program generates a refresh token along with access token, but when logging in, it only generates access token and refresh token is an empty string "". I cannot find a similar problem, nor any solution to this. Here is my settings.py: """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-$!z5s1dryft$&tjajmulo+kb7^vi$mfujnzor$_zi(7qv9jxwj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #3rd Party 'rest_framework', 'rest_framework_simplejwt', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'corsheaders', #local 'accounts.apps.AccountsConfig', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = … -
torch cuda memory not realeasing
i want to clean up gpu memory using deallocate_memory function. It works atexit function but when I call deallocate_memory function, the memory is not released. def ready(self): # self.deallocate_gpu_memory() # Register resource cleanup for application exit atexit.register(self.cleanup_resources) #works self.deallocate_memory() #does not work def cleanup_resources(self): self.deallocate_gpu_memory() def deallocate_gpu_memory(self): if torch.cuda.is_available(): device = torch.device('cuda:0') # Allocate a small amount of GPU memory dummy_tensor = torch.tensor([0.0], device=device) # Delete the dummy tensor del dummy_tensor # Empty the cache to release memory torch.cuda.empty_cache() print('GPU memory released') -
Django Redirect Urls.py errors
I would like to create a registration form, which then sends more data to another form. My user chooses his username and password on the first form that redirect to the second form where he fills in information such as his city, favorite sport...etc. These two steps work perfectly on their own. Only then I would like to send on a third form on which the user fills in the data of his dogs, which is in another app. For this I use the urls.py of the project, and I include the urls.py of the apps. From there it no longer works. If I only use the users form, and its urls, it works, but if I import the urls.py then I cannot access the second form without a "NoReverseMatch at /signup/ Reverse for 'additional_details_main_user' not found. 'additional_details_main_user' is not a valid view function or pattern name.NoReverseMatch at /signup/." This error happens after the first form, which is only username and password. I cannot even access to the other one of the user. This is my code structure: robert (main app) urls.py userProfile folders : templates, static...etc urls.py dogProfile folders : templates, static...etc urls.py urls.py from robert: from django.contrib import … -
Forbidden (403) CSRF check failed. Order cancelled. Djnago - python
Proibido (403) Verificação CSRF falhou. Pedido cancelado. Help Reason given for failure: Origin checking failed - https://dashboardequiuniemp.fly.dev does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. … -
class not seing it's properties
my class from django.db import models from django.contrib.auth.models import User class Task(models.Model): id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default="") deadline: models.IntegerField(default=None) creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.id) + str(self.content) my error: File "/Users/ironside/Documents/Python/PythonDjango-Project/api/models.py", line 13, in str return str(self.id) + str(self.content) AttributeError: 'Task' object has no attribute 'content' I tested, and all other properties give the same error ('content' changes to property name). It's as if it only sees id as valid property. I'd like to be able to print the id + content or any other property -
django.core.exceptions.ImproperlyConfigured Django 4.2.6
So, I started refactoring my project, but I also deleted my migrations folder (which I just learned is a no-no.) Now I can't run the server or tests. I only get the error below. File "C:\Users\Documents\projects\venv\Lib\site-packages\django\urls\resolvers.py", line 237, in _compile raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: "^users\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 2; was group 1 at position 37 I tried starting the project again in a separate folder with a new db, copying and pasting the necessary code, then running makemigrations and migrate, but the same error keeps appearing. I don't want to have to start from scratch again, so if there's a way to fix it, please let me know. I still have the migrations table and info in my first db, if that helps. -
How to add element class in ckeditor on django?
I'm trying add default element class in ckeditor on Django website like. <ul class="sm-circle"></ul> -
Set default widget for custom model field in django 4
I would like to have a custom field which uses a specific widget. In my example it's a model.CharField derived field. It should always use forms.Textarea instead of the default forms.TextInput. I want to have this definition in MyCustomField class, to not always have to override the admin form to use the specific widget. This is my code: class MyCustomField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 # Set the fixed max length here super().__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'widget': forms.Textarea} defaults.update(kwargs) return super().formfield(**defaults) It just shows forms.TextInput widget instead of forms.Textarea - any idea what is wrong? -
How do I inherit from different templates in Djanog based on whether the user is logged in or not
Exactly what the question says. I have three templates base.html, logged_in_base.html, and page.html. I want page.html to extend base.html when the user isn't logged in and to extend logged_in_base.html when the user is logged in. How do I do this? (This is basically because I have a different navbar for logged in users and not logged in users.) -
Textarea adding whitespaces everytime I submit
I have a form with textarea and everytime I click the submit button and use it again, it adds whitespaces. {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>Edit Page</h1> <form method="POST" action="{% url 'edit' title=title %}"> {% csrf_token %} <div id="title"> <label>Title:</label> <textarea name="title" class="form-control" style="width: 600px; height: 50px;">{{ title }}</textarea> </div> <div id="body"> <label>Body:</label> <textarea name="content" class="form-control" rows="5" style="width: 600px; height: 400px;">{{ content }}</textarea> </div> <input type="submit" class="btn btn-primary" value="Edit" style="margin-left: 546px; margin-top: 10px;"> </form> {% endblock %} I need to know how do I prevent it adding whitespaces -
Run a specific function on a specific field in a queryset
I am trying to run a function on a specific field in a queryset before i send it to the template for rendering. I have the following models. class Customer(models.Model): name = models.CharField(max_length=255) class Device(models.Model): cid = models.ForeignKey(Customer, on_delete=models.CASCADE) name = models.CharField(max_length=255) oid = models.TextField(null=True) I have the following view, that i am trying to run the checkStatus function on queryset field of objectid, but everytime it runs i get the following error, the "info" is the value that the checkStatus function is returning back. error TypeError: QuerySet.annotate() received non-expression(s): info. views.py def device_detail(request, cid): customers = models.Customer.objects.all() customer_details = get_object_or_404(models.Customer, id=cid) device_details = customer_details.device_set.all() device_details.annotate(checkStatus("objectid")) return render(request, 'devices/detail.html', { 'device_details': device_details }) -
deployed django webpage using apache and mode_wsgi doesnt show other pages aside from index.html
I am totally new to the world of Django, I recently tried to deploy my website on production server and I have been successful to some extent. I deployed the website on a windows base VPS, using apache and mode_wsgi. the webpage is up and running, I can view it on localhost, the problem is when I try to show other pages of the website like "localhost/about", it gives me " Not Found The requested resource was not found on this server. " does anybody had the same issue? any help in how to solve it would be much appreciated -
Django not sending debug errors in production
I have a django app running on production but server errors are not sent to the established e-mail. This is my settings.py: ADMINS = [('Foo the man', "******@gmail.com")] SERVER_EMAIL = os.getenv('SERVER_EMAIL') EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_HOST_IMAP = os.getenv('EMAIL_HOST_IMAP') EMAIL_PORT = '587' EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') Regular e-mails from within the app are being sent correctly, but debug errors are not sent and I can't figure out why. -
Accessing model attributes results in Self not defined error
Can anyone help me understand why I am receiving the error self is not defined while accessing a class attribute? Thanks for your help class Receipt(models.Model): "" receipt_id = models.AutoField( primary_key=True, db_comment="" ) store_name = models.TextField( max_length=255, default="Unidentified", db_comment="" ) total_amt = models.DecimalField( max_digits=6, decimal_places=2, default=0.00, db_comment="" ) def create_from_document(document): "" if (document is None): return False self.store_name = document.store_name self.total_amt = document.total_amt self.save() return self -
Why does my Django view return 'Reverse for 'initiate_transcription' with arguments '('',)' not found'?
A user uploads a file on page 1 and the site redirects them to page 2 where they can click a button which triggers the service. I'm trying to create a unique URL for each user upload and I know the error has to do with the {% url 'initiate_transcription' session_id %} in HTML page 2 form but i'm not sure what to change. Here is the code: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.transcribeSubmit, name = "transcribeSubmit"), path("init-transcription/<str:session_id>/", views.initiate_transcription, name = "initiate_transcription"), ] views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) session_id = str(uuid.uuid4()) request.session['session_id'] = session_id # Render the 'transcribe-complete.html' template to a string return JsonResponse({'redirect': reverse('initiate_transcription', args=[session_id])}) else: else: form = UploadFileForm() @csrf_protect def initiate_transcription(request, session_id): if request.method == 'POST': try: # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcript = transcribe_file(path_string,audio_language, output_file_type ) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, … -
Django inline with PolymorphicParentModelAdmin
i have a problem with my CreationInline, i have this code in models.py: class Creation(PolymorphicModel): """Model representing a creation.""" original_title = models.CharField('Título original', max_length=10000, null=True, blank=True,) subtitles = models.TextField('Subtítulos, capítulos y entregas', null=True, blank=True,) authorship = models.TextField('Autoría', null=True, blank=True,) publication_year = models.IntegerField("Año de publicación",default=2023, choices=((i,i) for i in range(1930, 2024))) synopsis = models.TextField('Sinopsis', null=True, blank=True,) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True,) keywords = models.ManyToManyField(KeyWord, blank=True) product = models.OneToOneField("Product", on_delete=models.CASCADE, related_name="product_creation") def __str__(self): return self.product.title class MediaCreation(Creation): original_language = models.ForeignKey(Language, on_delete=models.SET_NULL,blank=True, null=True) IMDb = models.CharField(max_length=10000,blank=True, null=True) commertial_editions = models.CharField('Ediciones comerciales', max_length=10000,blank=True, null=True) class Movie(MediaCreation): """Model representing a Movie.""" remastering = models.TextField('Reedición', null=True, blank=True) direction = models.TextField('Dirección', null=True, blank=True) producer = models.TextField('Producción', null=True, blank=True) genre = models.ManyToManyField(Genre, limit_choices_to={"type": "Movie"}) there are other models that inherit from Creation, such us Novel, Comin, etc. My code in admin.py is: class CreationInline(NestedStackedInline): model=Creation class CreationParentAdmin(PolymorphicParentModelAdmin): """Parent admin class for Creation model.""" base_model = Creation child_models = (Movie, Musica, TVSerie, Videogame, Theatre) @admin.register(Creation) class CreationAdmin(CreationParentAdmin, DisableAddButtonModelAdmin): """Admin class for Creation model.""" base_model = Creation readonly_fields = ('product',) child_models = (Movie, Musica, TVSerie, Videogame, Theatre, Novel, Comic, BoardGame) list_filter = (PolymorphicChildModelFilter, ) list_display = ('get_product_title', 'original_title', 'authorship', 'publication_year') def get_product_title(self, obj): return obj.product.title # Obtiene el título … -
Printing to thermal printer in python
I have been trying to print on a POS printer and a label printer, depending on the running function. Here is where I am at: import win32print, win32ui, win32con # X from the left margin, Y from top margin # both in pixels X=50; Y=50 # Separate lines from Your string # for example:input_string and create # new string for example: multi_line_string # @@@@@@@ lable = Lable.objects.all().last() # @@@@@@@ multi_line_string = label_text.splitlines() the_name_will_appear_on_printer_spool = str(f"print_job{lable.id}") hDC = win32ui.CreateDC () # Set default printer from Windows: # hDC.CreatePrinterDC (win32print.GetDefaultPrinter ()) hDC.CreatePrinterDC(win32print.OpenPrinter(printers.label)) hDC.StartDoc (the_name_will_appear_on_printer_spool) hDC.StartPage () for line in multi_line_string: hDC.TextOut(X,Y,line) Y += 50 print(hDC.TextOut.text()) hDC.EndPage () hDC.EndDoc () message.success(request, 'Test printer job send') I have been using p = win32print.OpenPrinter("EPSON LX-350") to grab a specific printer but in this case i need to use something like this: hDC.CreatePrinterDC (win32print.OpenPrinter("EPSON LX-350")). The problem is I'm getting this error: Objects of type 'PyHANDLE' can not be converted to Unicode. Since i grabbed this from a 2013 answer there may be a better way to do this, I'm open to suggestions. Thank you in advance -
DJango Left join issues
LEFT JOIN ISSUE Model1 KPI_ID KPI_Name 1 KPI1 2 KPI2 3 KPI3 4 KPI4 Model2 Emp_Name KPI_ID Amount Mr. A 1 100 Mr. A 3 200 Mr. B 2 300 Mr. B 4 400 Output For Employe : Mr. A KPI_ID KPI_Name Amount 1 KPI1 100 2 KPI2 NULL 3 KPI3 200 4 KPI4 NULL For Employe : Mr. B KPI_ID KPI_Name Amount 1 KPI1 NULL 2 KPI2 300 3 KPI3 NULL 4 KPI4 400 Django left join issue -
best practice for dynamic filtering
I want to filter with keywords the user can enter. for example: models.py: class Product(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() now I want to let the user enter "category": "teapot" or "name": "IKEA Glas 0.5L" and the code should in the get_queryset method execute: def get_queryset(self): VALUE = self.request.GET.keys(SOMEPARAM) return Product.objects.filter(SOMEPARAM__contains=VALUE) how can this be done (I know I can do a lot of if clauses, but my model is quite large in terms of fields that can all be handled equally. so for example for the IKEA example that would be: Product.objects.filter(name__contains="IKEA Glas ...") -
Getting CORS error after adding Dockerfile to my Django project
So to keep it brief, I have a fullstack application which is deployed on Railway. Everything worked perfectly. Then I decided to integrate celery so I can run some tasks in background. Now in order to use celery in production I wanted to containerize my Django app where it can also run celery. So I followed some tutorials and added Dockerfile to my Django app. Dockerfile: FROM python:3.9.7 WORKDIR /app COPY . /app RUN pip install -r requirements.txt ENV DJANGO_SETTINGS_MODULE=backend.settings ENV CELERY_BROKER_URL=redis://default:***********************-43.railway.app:**** ARG RAILWAY_ENVIRONMENT ENV PORT = 8080 EXPOSE 8080 CMD ["python", "-m", "celery", "-A", "backend", "worker", "--loglevel=info","--pool=solo"] Everysince I added this, my application is facing this CORS issue..I dont know why and I searched thru google and I couldnt find any answers, I am new to Docker so I hope to get some insight on this. Here is my CORS config in Django: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'https://checkout.stripe.com', 'https://sendit-frontend-production.up.railway.app' ] CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
How to get a prefilled authorization key in swagger with drf-specatular
I use django, drf and drf-spectacular. I create swagger documentation. Some endpoints require authentication. I can authenticate in swagger by pressing authorize and filling in the token. I would like that this filled in automatically for me. How do I do that? I tried to add preauthorizeApiKey to my settings, like this: SPECTACULAR_SETTINGS = { 'SWAGGER_UI_SETTINGS': { 'preauthorizeApiKey': 'Token my-secret-token' } } It doesnt work. -
after implementing serial number the sorting of serial number is not working.answer will be appreciated
after implementing serial number the sorting of serial number is not working.answer will be appreciated. i did serial number of jquery datatable.i used django and jquery datatable and after implementing serial number the sorting of serial number is not working.answer will be appreciated. -
Why do get requests to amazon.nl work but not to amazon.com / amazon.de?
Currently I am trying to build an amazon web scraper which scrapes some information of an item from the product page. For this I am using LXML and parsing the data using xpath. The main problem I am facing is that when I make a get request to amazon.nl only about 1/10 of them are successfull, but when I try to make one to amazon.de, or amazon.com, it takes a very long time for it to return an answer(if it ever does). HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/117.0.0.0 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) while True: response = requests.get(URL, HEADERS) if response.status_code != 503: break currently this is all the code I am using to make the get requests. Can someone help on how this could be improved (better success ratio) or explain why I cant seem to make get requests to amazon.de / amazon.com also as I side not I am living in the netherlands which could play a part on why I can access amazon.nl