Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How should I serve my API? (authentication without password)
My question on itself isn't a problem in coding, instead I'm having doubts in the design of the user authentication of my API. Sorry if this isn't a question fit for stack overflow I'm developing an API in Django that serves HTML templates. It's going to be served to pages, each one has a set of users. I was planning in following the design described here: Why and when to use API keys So basically, each page will have its own API key, and in order for the users to use the API, the page will request a temporary token for the user. My question is, how could I generate the temporary tokens? Is there a library that deal with this? I had no luck searching. -
Django doesn't send email
I encountered an issue where Django is not sending emails to the specified email address. I would greatly appreciate your assistance. views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() user.is_active = False user.save() current_site = get_current_site(request) subject = 'Account verification email' message = render_to_string('account/registration/email-verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': user_tokenizer_generate.make_token(user), }) print(message) user.email_user(subject=subject, message=message) return redirect('email-verification-sent') context = {'form':form} return render(request, 'account/registration/register.html', context=context) def email_verification(request, uidb64, token): unique_id = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=unique_id) if user and user_tokenizer_generate.check_token(user, token): user.is_active = True user.save() return redirect('email-verification-success') else: return redirect('email-verification-failed') token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator class UserVerificationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): user_id = str(user.pk) ts = str(timestamp) is_active = str(user.is_active) return f"{user_id}{ts}{is_active}" user_tokenizer_generate = UserVerificationTokenGenerator() settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = 'True' EMAIL_HOST_USER = 'XXX@gmail.com' EMAIL_HOST_PASSWORD = 'XXX' EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are correct I have already tried using SSL instead of TLS, disabling two-factor authentication, and removing the line 'EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
Django rest how to show hierarchical data in api response
I am getting the category id for GET request but I want to show text in hierarchical structure like child1 -> child -> child3 my expected response will be look like this { 'category': 'child1 -> child -> child3' } now getting response like this { 'category': 1 } somethings look like that my model where it show category name on hierarchical order my category_model class Product_category(models.Model): domain = models.CharField(max_length=250) parent_category = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) category_name = models.CharField(max_length=200,null=True,blank=True,) category_icon = models.ImageField(upload_to=dynamic_icon_upload_path,blank=True,null=True) def get_hierarchical_name(self): if self.parent_category: return f"{self.parent_category.get_hierarchical_name()}->{self.category_name}" else: return f"{self.category_name}" def __str__(self): return self.get_hierarchical_name() my product model class Product(models.Model): title = models.CharField(max_length=200,blank=True,null=True) category = models.ForeignKey(Product_category,blank=True,null=True,on_delete=models.CASCADE) my serilizer class ParentProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['category',...others product fields] see the screenshot where right now I am getting id instated for hierarchical text -
Django import problem, cant import myapp but i have installed it in setings
I'm working on a Django project and encountering an ImportError when trying to import a function from my app into the urls.py file. Despite the function being defined and the app added to INSTALLED_APPS, Django cannot seem to locate the function. Project Structure: myproject/ manage.py dictionarapicol/ init.py settings.py urls.py asgi.py wsgi.py statics/ find.js myapp/ migrations/ __init__.py templates/ base.htm index.html __init__.py text_processing.py admin.py apps.py models.py tests.py views.py urls.py myapp/urls.py: from django.urls import path from myapp import views from .text_processing import process_text urlpatterns = [ path('', views.home, name='index'), path('contact/', views.contact, name='contact'), path('stiri_apicole/', views.login, name='stiri_apicole'), path('text_processing/', process_text, name='text_processing'), ] text_processing.py from django.http import JsonResponse import json from nltk.stem.snowball import SnowballStemmer import stanza import spacy_stanza from rowordnet import RoWordNet # Load dictionary data with open('static\dictionary.json', 'r', encoding='utf-8') as file: dictionary_data = json.load(file) # Initialize NLTK, spaCy, Stanza, andin stall RoWordNet stemmer = SnowballStemmer("romanian") nlp = spacy_stanza.load_pipeline('ro') import rowordnet as rwn wn = RoWordNet() def process_text(request): text = request.GET.get('text', '') stemmed_text = stemmer.stem(text) doc = nlp(text) lemmatized_text = ' '.join([token.lemma_ for token in doc]) synset_ids = wn.synsets(literal=text) synsets = [wn.synset(synset_id).definition for synset_id in synset_ids] return JsonResponse({ 'stemmed_text': stemmed_text, 'lemmatized_text': lemmatized_text, 'RoWordNet_synsets': synsets }) views.py from django.shortcuts import render # Create your views here. def home(request): … -
How to add global ranking annotation to subsequent Django queries?
I have a Django model that looks like this: class LeaderboardScore(models.Model): score = models.FloatField() player_account = models.ForeignKey(PlayerAccount, on_delete=models.CASCADE) timestamp = models.DateTimeField() This represents top scores in a game. The scores are ranked by score descending and timestamp ascending, so if two scores are the same, the earliest score is ranked higher. Every time I do a query on the leaderboards, I'd like to include the global ranking of each instance in the query result. I can do that successfully when I'm querying all the scores like so: lq = LeaderboardScore.objects.filter(leaderboard__id=1).annotate( rank=Window( expression=DenseRank(), order_by=[F('score').desc(), F('timestamp').asc()] ) ) This will correctly at a rank field with the ranking. But if I take the above query and filter it by player_account like so: # rank will be 1, but should be the global ranking lq.filter(player_account__id=123)[0].rank then the ranking resets so that the first item in the query has the rank of 1, even though its global rank should be different. How do I preserve the global ranking? -
¿How can I download a file on django clicking on a widget?
I have a django project consist in different forms with different fields. Some of them are filefield where I upload files to media based on this class.I just want to make a widget to download the files, so when I am editing in change form if a file has been submit I can click on a button to download. Everytime I click on the button I made I received this error on console: "Not allowed to load local resource:" followed by my local root something like file:///C:/proyectos/etc My code is too extensive but I will try to show you most of them: Models.py (this class is to upload filefields) class CustomStorage(FileSystemStorage): # Almacenamiento nuevo en media def __init__(self, *args, **kwargs): super().__init__(location=os.path.join(settings.BASE_DIR, 'media','companies'), *args, **kwargs) def submission_directory_path(instance, filename): # Obtener el nombre comercial de la compañía y el ID del cliente company_name = slugify(instance.client.company.comercial_name) client_data = f"{instance.client.id}_{slugify(instance.client.name)}_{instance.type_submission.name}" # Construir la ruta del directorio directory_path = os.path.join(company_name, client_data) # Devolver la ruta completa del archivo return os.path.join(directory_path, filename) Urls.py urlpatterns = [ path('admin/', admin.site.urls), #ENDPOINTS path('client-details/<uuid:client_id>/', views.get_contact_details, name='client-details'), path('panel/submission/<uuid:submission_id>/change/cancel', views.cancel_submission, name='cancel_submission'), path('panel/submission/<uuid:submission_id>/change/no-apply', views.no_apply_submission, name='no_apply_submission'), # Ir a pantalla de activación de cuenta path('<str:name>/<str:uidb64>/<str:token>/', views.account_activation, name='account_activation'), path('panel/submission/<uuid:submission_id>/download/<str:file_path>/', views.download_file, name='download_file'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to remove images from MEDIA_ROOT by using "Clear" in Admin panel for ImageField in Django?
I am trying to find the way to remove images from MEDIA_ROOT when I'am using "Clear" in Admin panel. Image that shows the checkbox I want to use When I choice "Clear" option, it removes link to image from database but the image is still in MEDIA_ROOT. It there a way to change its behavior? I tried to look Django documentation and googling but I didn't find anything. -
How can I run a kafka consumer in a django project so that messages will passed to django project
I am running my kafka consumer (from the confluent_kafka library) in a separate django management command. (I did this because I couldn't find a way of running a kafka consumer within the runserver process in django without blocking up the runserver process. If there is a better way of doing this I would love to hear suggestions) My projects requirements are: djnago rest api project will receive kafka message for designated topic project will create an instance of model1. creation of model1 will propagate further actions/logic such as creating/updating other models + sending further kafka messages. My issue comes when designing logic to meet my requirements. Requirement 3 can be met using django signals and there is already code that implements these further actions/logic. My problem comes requirement 2 and a bit of 1. My consumer lives in a separate process from my server process so I need to a way of communicating the messages consumed to my server process. What would be the best way of doing this? Using a cache will require another process to read this cache for updates and that leaves me in the same situation as before. The fact that django code runs synchronously makes … -
Django can login but can't logout - 405 Method Not Allowed
When I try to login using http://127.0.0.1:8000/accounts/login/ it works fine and redirected and creates a sessionid, but when I try to logout using http://127.0.0.1:8000/accounts/logout/ it shows http error 405 and not deleting the sessionid Request URL: http://127.0.0.1:8000/accounts/logout/ Request Method: GET Status Code: 405 Method Not Allowed settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'app.apps.AppConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'upload' LOGIN_REDIRECT_URL = '/' urls.py urlpatterns = [ path('',include('app.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) login.html <form method="POST" action="{% url 'login' %}" class="form"> {% csrf_token %} <center> <div class="logo f-logo"> <i class="fa-brands fa-blogger"></i> </div> <div class="inputs"> <div> <div class="search-bar s-active input"> {{form.username}} <div class="animated-search"> <i class="uil uil-envelope-alt"></i> </div> </div> <div class="search-bar s-active input"> {{form.password}} <div class="animated-search"> <i class="uil uil-key-skeleton"></i> </div> </div> </div> <button class="btn btn-primary rounded" type="submit">Login<span class="material-icons">arrow_right_alt</span></button> <p>Not have an account?<a href="signup.html">Sign up</a></p> </div> </center> </form> logged_out.html {% extends 'base.html' %} {% block title %} Blog | Logout {% endblock title %} {% block content %} <div class="container"> <center> <div class="typo"> <p>You have been successfully logged out. <a href="{% url 'login' %}">Login again</a> </p> </div> </center> </div> {% … -
How to Export Book Data for a Specific Genre in CSV or JSON Format
views.py class ExportBooksAPIView(APIView): permission_classes = [IsAuthenticated] def get_queryset(self, genre_id): try: genre = Genre.objects.get(id=genre_id) books = genre.books.all() return books except Genre.DoesNotExist: return None def get(self, request): genre_id = request.GET.get('genre_id') if not genre_id: return Response("Genre ID not specified in the request.", status=status.HTTP_400_BAD_REQUEST) books = self.get_queryset(genre_id) if not books: return Response(f"Genre with ID '{genre_id}' not found.", status=status.HTTP_404_NOT_FOUND) serializer = BookSerializer(books, many=True) csv_data = self.serialize_to_csv(serializer.data) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="data_books.csv"' response.write(csv_data) return response def serialize_to_csv(self, data): csv_buffer = io.StringIO() csv_writer = csv.writer(csv_buffer) header_row = ['Book Name', 'Author Name', 'Number of Pages'] csv_writer.writerow(header_row) for book in data: csv_writer.writerow([book.get('name', ''), book.get('author', {}).get('name', ''), book.get('pages', '')]) return csv_buffer.getvalue() core/urls.py py path('export-books/', ExportBooksAPIView.as_view(), name='export_books'), ] project/urls.py path('genre/',include('core.urls')), Postman export all the data for a specific genre in a structured format (e.g., CSV or JSON). But i am getting { "detail": "Not found." } i should get all the details of all the books that comes under specific genre -
Add Social Login to my current Django project
I have an email/password signup/login flow in my Django project. I want to add LinkedIn login flow to my project. I would like to use the current User DB table for LinkedIn login. What I want is when a user logs in using LinkedIn, I want to get the user information and save it to the current User DB table, login and redirect to the home page. Please help me! The important thing is that when a user logs in using LinkedIn, I want to customize the user data in the backend and store it in the current User DB table. -
Django with SPA?
First of all, greetings to everyone, I want to convert my project from MPA to SPA in Django, but I can't get the structure in my head. In the area you see in the photo, I want to redirect the base.html (or any field, for example login.html, register...) field to the app field in index.html during a user's first login to the site. html...) field in index.html during the user's first login, but I want to make it workable with the back and forth buttons in the web browser and manual input of the url. The .html pages are returned as a response as a string on the django side and I get the data with fetch. My problem here is that if the person manually enters the url on the login.html page, I redirect the login.html and the index.html is passed. If I first fetch the index.html with the load event and then fetch the login.html, I instantly display the non-css version and then it is fixed. Since the beforeunload event works without fetching the index.html, the DOM cannot find my app field because I did not redirect the index.html. If you have a constructive solution, I would appreciate … -
WSGI application 'CMS.wsgi.application' could not be loaded; Error importing module
enter image description here Above is my django project structure and i have two django apps. I am using session variable to store username when user is logged. but i am getting error while using session variable. raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'CMS.wsgi.application' could not be loaded; Error importing module. wsgi.py ---> main project file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CMS.settings') application = get_wsgi_application() authentication/views.py def login(request): error_message = None if request.method == 'POST': username_value = request.POST.get('username') password_value = request.POST.get('password') try: user = SignUp.objects.get(username=username_value) # Check if the provided password matches the hashed password in the database if check_password(password_value, user.password): # Successful login response = HttpResponse("Login successful!") request.session['username'] = user.username return redirect('home') else: error_message = "Invalid username or password" except DoesNotExist: error_message = "User does not exist" return render(request, 'authentication/login.html', {'error_message': error_message}) settings.py from pathlib import Path from mongoengine import connect # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure--#u^llr^ji5f70u-vm-99-59(m4010v_$a%bga2-puf2-d%l*3' # 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 base.html with htmx
So question is i got my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- styles --> </head> <body> {% include 'includes/sidebar.html' %} <div id="main"> {% block content %} {% endblock content %} </div> {% block js %} <!-- block where js is located --> {% endblock js%} </body> dashboard.html {% extends "base.html" %} {% load i18n %} {% block content %} <!--my content--> {% endblock content %} and my sidebar.html % load static %} {% load i18n %} {% block content %} <div id="sidebar" class="active"> <div class="sidebar-wrapper active"> <div class="sidebar-header"> <div class="d-flex justify-content-between"> <div class="toggler"> <a href="#" class="sidebar-hide d-xl-none d-block"><i class="bi bi-x bi-middle"></i></a> </div> </div> </div> <div class="sidebar-menu"> <ul class="menu"> <li class="sidebar-item has-sub"> <a href="#" class='sidebar-link'> <i class="bi bi-grid-fill"></i> <span>Dashboard</span> </a> <ul class="submenu"> <li class="submenu-item "> {% url "dashboard:dashboard" as dashboard %} <a href="{{ dashboard }}" hx-get="{{ dashboard}}" hx-target="#main" hx-push-url="true" hx-indicator = "#content-loader" hx-on="htmx:beforeRequest: event.detail.target.innerHTML = ''" class='submenu-link'> <i class="bi bi-grid-fill"></i> <span>{% trans 'Dashboard' %}</span> </a> </li> </ul> <!-- else code --> So question is when user redirect from login page to dashboard, if im not extends from base.html it not shown any sidebar and its logical, but with htmlx when im extends base.html template this render … -
Combining django-jsonform with HTMX and CrispyForms resulting in removed interactivity after submit
I am using django to create a form that uses a JSONForm field from the django-jsonform package. I am using HTMX for asyncronous submission of the form and render_crispy_form for rendering the form back after it has been submitted. However, after submitting the form, the things inside the JSONForm are not shown anymore and the interactivity is removed for the django-jsonform field part. Here is my model: class GroceryStore(models.Model): PRODUCTS_SCHEMA = { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "price": {"type": "number"}, }, "required": ["name", "price"], } } creator = models.OneToOneField(User, on_delete = models.CASCADE) name = models.CharField(max_length = 200) products = JSONField(schema = PRODUCTS_SCHEMA, null = True, blank = True, default = None) The data is saved when valid data is submitted, the problem is just that it does not reflect it on the frontend. I am using this for generating the html to replace the form using HTMX: form_html = render_crispy_form(grocery_form) return HttpResponse(form_html) It says in the documentation that HTMX is supported. What could be the problem? -
Django gunicorn setup - DJANGO_WSGI_MODULE - ModuleNotFoundError: No module named 'config'
I'm trying setup the gunicorn but I am facing an error for DJANGO_WSGI_MODULE. DJANGO_WSGI_MODULE=config.wsgi `ModuleNotFoundError: No module named 'config' File "/webapps/djangoapp/myapp_venv/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^` Configuration wsgi_app: None PS: when I run the command directly in the terminal from project root, I am not getting this error. Below command is running properly. myapp_venv/bin/gunicorn config.wsgi:application --name myapp --workers 3 --timeout 120 --user=myappapi --group=webapps --bind=unix:/webapps/myapp/run/gunicorn.sock --log-level=debug --log-file=- Can anyone help please? Thanks I tried to search for wsgi app name but it doesn't work. I also tried to run the command manually and it worked so it looks like directory path related issue. I also think that wsgi_app is set to None which can be causing the issue. I followed this YT video to set this up and have asked question there as well. https://www.youtube.com/watch?v=RIE0O0Lbk8U -
I'm using cryptography in django and the problem is "it is not decrypting the value when using "from_db_value" function"
settings.py: ENCRYPTION_KEY=b'iHHJ-OlINvt7Ez7-js9JiAAy2I_hFJXWYhi8yIJZPCs=' models.py: from django.db import models from .fields import EncryptedTextField class all_License(models.Model): Lic_Id= models.IntegerField(primary_key=True, auto_created=True) LicenseKey= EncryptedTextField() ProductID= models.ForeignKey(Products, on_delete=models.CASCADE) ClientID= models.ForeignKey(Clients, on_delete=models.CASCADE) ActivationStatus= models.BooleanField() ExpirationDate= models.DateField() IssuedDate= models.DateField() AssociatedDeviceID= models.IntegerField() AdditionalText= models.TextField() fields.py: from cryptography.fernet import Fernet, InvalidToken from django.db import models from django.conf import settings import base64 class EncryptedTextField(models.TextField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cipher_suite = Fernet(settings.ENCRYPTION_KEY) def get_prep_value(self, value): cipher_text = self.cipher_suite.encrypt(value.encode('utf-8')) return base64.urlsafe_b64encode(cipher_text).decode('utf-8') def from_db_value(self, value, expression, connection): decrypted_text = self.cipher_suite.decrypt(base64.urlsafe_b64decode(value)) print("hitesh") It just gives me "Invalid token" error while decrypting.it is just giving error in the from_db_value funtion.I have Tried this without django also and it is working fine even with the same key provided above. I don't know how to deal with this error. please help me! -
is adding a table for video, image, and audio a good job for normalizing the database or not
I have an app that has a lot of videos, audios, and images about persons, events, diaries and so on. is it a good practice to having a distinct table for all types of multimedia to query over them and their information and detail fields or there is another good way to handle this mission. evenly, if this is a good solution for normalizing the database, or not? I explored into the net but did not see any complete description about if there is a way to distinct multimedia from tables and just pointing to them through using queries and joining tables, or this is the common way that professional developers do! -
How to fix "Cannot operate on a closed database." while using dumdata in Django
does anybody knows how to fix this problem? sqlite3.ProgrammingError: Cannot operate on a closed database. I just want to finish the command to create a dump of my models. python manage.py dumpdata > .\fixtures\goods\cats.json I dii a little research, it gave me information that this error is connected with wrong encoding in db. Any ideas? I have tried to recreate a db twice, tried to force db work with utf8 encoding using parameters with dumdata -
Docker: django.db.utils.OperationalError: connection to server at "db" (172.19.0.2), port 5432 failed: fe_sendauth: no password supplied
I tried to test the origin code from CS50 Web/Testing/airline1, but I failed to run Docker Container. When I type in terminal: docker-compose up It shows me error message and I cannot open the port http://0.0.0.0:8000/flights/ I have also tried: docker run -e POSTGRES_PASSWORD=password postgres:9.6 And still doesn´t work.. If anybody could help me please? Here are the Error message I got: C:\Users\zhoua\CS50_web\Testing\src7\airline1>docker-compose up [+] Running 2/0 ✔ Container airline1-db-1 Created 0.0s ✔ Container airline1-web-1 Created 0.0s Attaching to db-1, web-1 db-1 | db-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db-1 | db-1 | 2024-02-02 13:40:04.790 UTC [1] LOG: starting PostgreSQL 16.1 (Debian 16.1-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit db-1 | 2024-02-02 13:40:04.794 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db-1 | 2024-02-02 13:40:04.794 UTC [1] LOG: listening on IPv6 address "::", port 5432 db-1 | 2024-02-02 13:40:04.809 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db-1 | 2024-02-02 13:40:04.822 UTC [29] LOG: database system was shut down at 2024-02-02 13:37:09 UTC db-1 | 2024-02-02 13:40:04.835 UTC [1] LOG: database system is ready to accept connections web-1 | Watching for file changes with StatReloader web-1 | System check … -
How to change default Order from ASC to DESC in django OrderFilter
I am not an expert django dev. I was trying to write a viewset which has the ordering_fields and ordering fields, but this ordering field does not have any effect. My viewset is, class ContentViewSet(viewsets.ModelViewSet): queryset = Content.objects.all() serializer_class = ContentSerializer filter_backends = [OrderingFilter] ordering_fields = ['created_at'] ordering = ['-created_at'] What I am looking for is, it will provide the list in descending order. However, if I add a negative sign infront of created_at in the url, it gives me what I am looking for, but I was looking for a solution where I will get the same result without using that negative sign in the url. Thanks in advance. -
How to use DateField in an ArrayField in django
I'm trying to use ArrayField in my model. I get it working with, e.g., IntegerField, but not DateField. So I'm wondering, is there some limitation I'm not aware of, or is there a bit missing in my code that prevents it from working? In my models.py, I added the field with class Directive(models.Model): id = models.AutoField(primary_key=True) ... individual_dates = ArrayField( models.DateField(auto_now_add=False, blank=True, default=date.today), default=list,) test = ArrayField(models.IntegerField(blank=True), default=list,) ... and in my forms.py, I have class DirectiveForm(forms.ModelForm): individual_dates = SimpleArrayField( forms.DateField(), required=False, help_text='comma separated list of dates', widget=DatePickerInput(options={'format': 'DD.MM.YYYY'})) test = SimpleArrayField( forms.IntegerField(), required=False, help_text='comma separated list of ints') ... The form renders fine: Now, when I enter a comma seperated list of integers in the "test" field, the values are stored in the database as expected. when I try to enter a number of dates in the "individual dates" field using the DatePicker, every pick overwrites the previous one, and the last one is eventually stored in the database. when I enter a comma separated list of dates by hand, only the first entry is stored in database. But, when I use the django shell, import my model and try to enter dates there, it works as expected: >>> … -
TypeError at / Field 'id' expected a number but got ... django
Hello to all the programmers, I am a Django Developer, when I run my site without an account, the server got this error: TypeError at / Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000025D3D8E2F90>>. My views.py is: def homepage(request): if request.user.is_authenticated: print("ok") user = request.user posts = Posts.objects.all() sortedk = sorted(posts, key= lambda f: f.lan(), reverse=True) comments = [] pictures = [] com = [] comments_pictures = [] for i in sortedk: lst = [] id = i.id poste = Comments.objects.filter(post_name_id = id) com.append(poste) num = len(poste) prf = Profile.objects.get(id = i.writer_id) pictures.append(prf.avator) comments.append(num) for comment in poste: idh = comment.author_id kk = Profile.objects.get(id = idh) lst.append(kk.avator) comments_pictures.append(lst) print(comments_pictures) if request.method == "POST": form = CommentForms(request.POST) if form.is_valid(): ns = form.save(commit=False) ns.author = user ns.post_name_id = int(request.POST.get("pk")[0]) ns.save() return redirect('home:homepage') else: form = CommentForms() cont = { "user":user, "posts":sortedk, 'comments':comments, "pictures":pictures, "pos":com, "form":form, "comment_pictures":comments_pictures, } return render(request, 'home/home.html',cont) else: return render(request, "home/home.html") Please help me in it. How can I fix it? Is there anyway? -
Problem with context processor in async django
My django app has following features: A model with an async method. An async view. A context processor that call an async method from the model and modifies the response context from the view. I am using Django 5.0 and python 3.12, daphne as asgi server. What's my problem: It appears that as of now django does not differentiate between sync and async context processors. From django source (django/template/context.py): updates = {} for processor in processors: context = processor(self.request) print(f"Context processor {processor.__qualname__}") try: updates.update(context) except TypeError as e: raise TypeError( f"Context processor {processor.__qualname__} didn't return a " "dictionary." ) from e So if a context processor is async, django internals will just try to update response context with a coroutine and cause a Context processor ... didn't return a dictionary. exception. So I tried to make my context processor synchronous by wrapping a call to the async model method with asgiref.sync.async_to_sync. Regardless of setting the force_new_loop parameter I am getting You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. exception. Am I missing something or is django async support just not at the point where it can provide the … -
Django_rest_framework Page Not Found
When I have been trying 127.0.0.1:8000/api/ it's working but when I've been trying 127.0.0.1:800/api/rota it isn't working. I don't know what is wrong. When linked urls.py files. below the code of the the file:url.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), **path('api/', include('base.api.urls'))**, ] I included the api/urls.py below the code of the file: api/url.py from django.urls import path from . import views urlpatterns = [ path('', views.getMessage), path('rota/', views.getRoutes), ] I linked the url with methods. below the code of the file: api/view.py from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def getRoutes(request): routes=[ 'GET api/' 'GET api/rota' ] return Response(routes) @api_view(['GET']) def getMessage(request): return Response("ok!") Does someone know how to fix it? Here some pictures about the case: [127.0.0.1:8000/api/][1] [127.0.0.1:8000/api/][2] [1]: https://i.stack.imgur.com/c7CoF.png [2]: https://i.stack.imgur.com/b5cok.png I am looking for a solution...