Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my django-crispy AdminForm not able to resolve AdminSite url?
Setup I defined an new admin url: from django.contrib.admin import AdminSite from django.http import HttpResponse from django.urls import path class MyAdminSite(AdminSite): def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path( "generate", admin_site.admin_view(self.my_view), name="generate", ) ] return urls def my_view(self, request): print(request.data) return HttpResponse("Hello!") admin_site = MyAdminSite() The url is successfully registered: print(admin_site.get_urls()) [ ..., ..., <URLPattern 'generate' [name='generate']>] # <-- here! Now in my django-crispy-form, I need to add a form action for multiple submit buttons. The library does not allow multiple form actions to be set, so I had to disable the form tag and add a new one manually: class PromptForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() # django-crispy-forms self.helper.form_method = 'post' self.helper.form_tag = False # <-- disable form_tag # Form layout self.helper.layout = Layout( # Add new form_tag HTML("""<form action="{% url 'admin:generate' %}"><input type="submit" class="btn btn-success" value="generate"></form>"""), ) Issue Neither {% url 'generate' %} nor {% url 'admin:generate' %} are able to reverse match the new url: `django.urls.exceptions.NoReverseMatch: Reverse for 'generate' not found. 'generate' is not a valid view function or pattern name. -
Django can't acces media files, 404 Page not found
I recently started to learn Django but I'm still struggeling with accessing media files. My settings.py file includes the following: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ My urls.py in the project directory contains the following. urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] if st.DEBUG: urlpatterns += django_Static(st.MEDIA_URL, document_root=st.MEDIA_ROOT) When I then try to load an image via a GET request I get the following message: " Page not found (404) ... Using the URLconf defined in ecommerce_project.urls, Django tried these URL patterns, in this order: admin/ [name='store_homepage'] ^media/(?P<path>.*)$ The current path, media/product_pictures/256132756_922283745365869_1303861998719790800_n.jpg, matched the last one. I really don't know what to do since I tried everything. Has someone also stumbled accross this problem? -
limit number of foreign key using Django CheckConstraint
I am using Django 4.1 and Postgresql and as stated in their documentation CheckConstraint accept Q object and Expression. Based on https://code.djangoproject.com/ticket/31646, I thought my solution would work, but when calling makemigrations nothing happens (Count inherit from Func). Goal: I would like to limit the number of Messages per Discussion. I did see a solution using a validators on the ForeignKey field but it is not robust (see Limit number of foreign keys). I would prefer not to have to create a SQL function and calling it (would like a Django solution only). from django.core.exceptions import ValidationError from django.db import models from django.db.models.lookups import IntegerLessThan class Discussion(models.Model): MAX_MESSAGES = 10 class Message(models.Model): discussion = models.ForeignKey( "discussion.Discussion", models.CASCADE, related_name="messages", ) constraints = [ models.CheckConstraint( name="limit_discussion_messages", check=IntegerLessThan( models.Count("discussion", filter=models.Q(discussion=models.F("discussion"))), models.Value(Discussion.MAX_MESSAGES), ), ), ] -
Getting null value in column "userId_id" of relation "pnrDB_run when sending a POST to django backend
Still very new to Django. I'm trying to send a post request to my backend from insomnia right now and I'm getting the error Getting null value when I'm passing in the ID value. Here is my seralizer: class RunSerialzer(serializers.HyperlinkedModelSerializer): gameId = GameSerialzer( read_only = True ) userId = UserSerialzer( read_only = True ) class Meta: model = Run fields=('id','name','isComplete','deaths','badges','userId','gameId') My view: class RunList(generics.ListCreateAPIView): queryset = Run.objects.all() serializer_class = RunSerialzer And my request I'm making: { "gameId":1, "userId": 1, "name":"testrun2", "deaths":0, "badges": 0, "isComplete": false } and the second one I tried { "gameId": { "id": 1, "name": "Vintage White", "photo": "https://archives.bulbagarden.net/media/upload/thumb/0/08/White_EN_boxart.png/250px-White_EN_boxart.png" }, "userId": { "id": 1, "name": "TestUser" }, "name":"testrun2", "isComplete": false, "deaths": 0, "badges": 0 } I feel like I need to create either a new Serailizer to get the instance I want in my Game model with the pk im passing in the request -
Django wrong imagefield.path
i have a model with an image field like this app_icon = models.ImageField(upload_to='icons/') the project has 'uploads' as media folder, which has subfolders, including 'icons'. The image is correctly uploaded to the 'icons' subfolder but when i try to access it using self.app_icon.path it returns .../uploads/imagename.jpg instead of .../uploads/icons/imagename.jpg so i get file not found error. Even the url doesn't include the 'icons' subfolder my settings: MEDIA_URL = '/uploads/' MEDIA_ROOT = BASE_DIR / 'uploads/' i can't find any answer to this problem, which seems so random to me. -
how to make models for user auth(use abstract user) for login and signup using django?
how to make models for user auth(use abstract user) for login and signup using Django? I want to make login OTP based for ecommerse website. from django.db import models class User(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) mobile = models.CharField(max_length=10) address = models.CharField(max_length=200) emailId = models.CharField(max_length=50) password = models.CharField(max_length=200) I tr above code. What should I have to add above? -
Count elements in Django
I am learning Django. I have a question about counting elements from tables. class Opinion(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) users = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) books = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) rate = models.IntegerField() description = models.TextField() def __str__(self): return self.user_id.username + ' ' + self.book_id.title My table Opinion is in relationship with built-in table User. I am wondering how can I count how many opinions each user has added? I would like to show information about users and the amount of opinions they have added on my website. Thanks for the help. -
I am trying check if user is authenticated navigate to dashboard . There is no error in console and network. How can I fix this?
I am developing a authentication system using Django, DRF and Djoser in backend and React, reduxtool kit in front end. Every thing works perfectly fine exept mapStatToProps which provide isAuthenticated const mapStateToProps = (state) => ({ isAuthenticated: state.auth?.isAuthenticated, } doesn't work when I use it as if (isAuthenticated) { return <Navigate to="/dashboard" />; } to redirect page to dashboard in login.jsx. I don't why. Please help me to fix this bug. redux state in redux devtool shows { rootReducer: { auth: { access: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYyMjAwMTM4LCJqdGkiOiJjMjY1OGE5YjM2MTg0NjMxYTRhOTNlYzNiNjZmNDc1MSIsInVzZXJfaWQiOjR9.rpBooY2zuHQE7ttl8DFjR3XSam3B6f55ZYMF_jQeyJc', refresh: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY2MjI4MjkzOCwianRpIjoiODM2ZTA1OGVmMTU4NDUxN2I5ZDViNWExMGU1YThkZmMiLCJ1c2VyX2lkIjo0fQ.MzEIvO6vmEhJZ2v3_TZCC4k3gBaKEVeES4OzAaq9DBI', isAuthenticated: true, user: { email: 'ripyschool@gmail.com', id: 4, username: 'ripyschool' } } } } #my loginpage import React, { useState } from "react"; import { Link, Navigate } from "react-router-dom"; import { connect } from "react-redux"; import { login } from "../actions/auth"; import axios from "axios"; import style from "../assets/styles/Login.module.css"; import { FaGoogle } from "react-icons/fa"; import { FaGithub } from "react-icons/fa"; import FormLayout from "../hocs/FormLayout"; const Login = ({ login, isAuthenticated }) => { const [formData, setFormData] = useState({ username: "", password: "", }); const { username, password } = formData; const onChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = (e) => { e.preventDefault(); login(username, password); }; const continueWithGoogle … -
Django Pycharm Process finished with exit code -1
Recently when i run Django project server on 0.0.0.0 port 8000 (I should run on 0.0.0.0 instead of 127.0.0.1) randomly in some requests return this error and kill the process(completely random). Process finished with exit code -1 And after reload, on first request give save error I use window 10 and Pycharm v 2021.2.2 it seems it's bug of Pycharm. Because there is no problem when deploy on the server -
AttributeError: 'WSGIRequest' object has no attribute 'get' I got this error earlier and I didn't find my answer here
I am going through a django course and I got this error earlier but the tutor doesn't !!! what should I do ??? this is my code below views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Project from .forms import ProjectForm def projects(request): objs = Project.objects.all() context = {"projects": objs} return render(request, 'projects/project.html', context) def dynamic(request, text): obj = Project.objects.get(id=text) return render(request, 'projects/single-project.html', {'obj': obj}) def createproject(request): form = ProjectForm() context = {'form': form} return render(request, 'projectform.html', context) models.py from django.db import models import uuid class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(null=True, blank=True, max_length=2000) source_link = models.CharField(null=True, blank=True, max_length=2000) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) tag = models.ManyToManyField('Tag', blank=True) total_vote = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) def __str__(self): return self.title class Review(models.Model): VOTE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.value class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name forms.py from django.forms import ModelForm … -
GiltLab CI/CD Django tests failing
I want to run some tests on Gitlab with CI/CD with a Django project. The tests on my local pc work fine, my job test pipeline is always failing with those tests. I get a SyntaxError. Here the script failure I get in the pipeline when the tests failed : Running with gitlab-runner 15.3.0~beta.42.gdb7789ca (db7789ca) on blue-3.shared.runners-manager.gitlab.com/default zxwgkjAP Preparing the "docker+machine" executor 00:06 Using Docker executor with image ruby:2.5 ... Pulling docker image ruby:2.5 ... Using docker image sha256:27d049ce98db4e55ddfaec6cd98c7c9cfd195bc7e994493776959db33522383b for ruby:2.5 with digest ruby@sha256:ecc3e4f5da13d881a415c9692bb52d2b85b090f38f4ad99ae94f932b3598444b ... Preparing environment 00:01 Running on runner-zxwgkjap-project-39068925-concurrent-0 via runner-zxwgkjap-shared-1662191947-427cb239... Getting source from Git repository 00:02 $ eval "$CI_PRE_CLONE_SCRIPT" Fetching changes with git depth set to 20... Initialized empty Git repository in /builds/XXX/Deploy_django_application_to_server/.git/ Created fresh repository. Checking out 51c8456f as master... Skipping Git submodules setup Executing "step_script" stage of the job script 00:01 Using docker image sha256:27d049ce98db4e55ddfaec6cd98c7c9cfd195bc7e994493776959db33522383b for ruby:2.5 with digest ruby@sha256:ecc3e4f5da13d881a415c9692bb52d2b85b090f38f4ad99ae94f932b3598444b ... $ echo "Running unit tests..." Running unit tests... $ python manage.py test app_users.tests.CustomUserTests File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax Cleaning up project directory and file based variables 00:00 ERROR: Job failed: exit code 1 *the script of my .gitlab-ci.yml is : stages: # List of stages for jobs, and … -
How to integrate scikit-ExSTraCS with my Django application
I'd like to use https://github.com/UrbsLab/scikit-ExSTraCS's features in my application, but I've discovered that it lacks REST interfaces. This is okay because I can easily create Django REST APIs for scikit-ExSTraCS' classes, but I'm hoping someone here has some experience with this or knows of a package that already handles it. -
Enviroments variables and migrations not working in django
I have following problem. I, starting app with structure like this: In env_vasr.sh I want to keep all the credentials etc. I source this file and variables are in env. However, when I run django-admin migrate, I get the following problem: Can anyone tell me what is the problem please. ├── eMenue │ ├── eMenue │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-310.pyc │ │ │ └── settings.cpython-310.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── eMenueApp │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ └── manage.py ├── env_vars.sh ├── global_settings.json ├── requirements.txt This the output from the django-admin migrate command: With hardcoded values it worked fine. However, I created ne project after to add env variables from file. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/michal/devel/eMenue/venv/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michal/devel/eMenue/venv/lib/python3.10/site-packages/django/core/management/base.py", line 415, in … -
saving value in session but not able to retreive in future api calls
I am not much ware about how django sessions works and how does it communicate with frontend technologies like vue.js I have a project setup in django from backend and vue.js for frontend request.session['session_user_id'] = serializer.entity.owner.id using this code I am saving the user_id in session and trying to retrieve the this session user_id in future API calls but I am getting None request.session['session_user_id'] giving None Can anyone help me or explain in doing this in a correct way or finding a better approach ? -
Django keeps logging me out from dev server when changing my codebase
In my Django app I have a lot of if request.user.is_authenticated logic and once I change some code other than in templates (like forms, models, views, etc.) I get logged out from the development server which makes it quite annoying to always have to re-login in the frontend to test my prior code changes again. Is there any way to stay logged in when in Debug = True (or other) mode? # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "False") == "True" # Add s.th. here to keep me logged in? -
django-taggit similar_objects(): how to specify a model in the queryset
I use django-taggit on my site across several applications. The package uses a generic foreign key (by default), which allows it to work with many models, which is very convenient when working with tags and displaying different objects filtered by certain tags. But this default behaviour doesn't satisfy me when I try to find similar objects for example: # news/views.py class NewsDetailView(TagMixin, FormMixin, DetailView): model = News ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) related_items = self.object.tags.similar_objects()[:4] context['related_items'] = related_items return context In this case, I want to select similar news, but instead I get similar objects of all types, including articles or shop goods. Please tell me how can I specify my model in this command: related_items = self.object.tags.similar_objects()[:4] I want it to be News only. -
How to display an image from an external API as part of a response in Django
I have an external API that returns images and it requires a private key in order to access it. The content type it returns is 'image/jpeg'. I am creating an API with the Django Rest Framework that uses this API. I also have a model with some basic char entries, and I want to return both those model entries as well as the image in a response, with the goal of making AJAX calls to it in JS and displaying both the data and the image in HTML. I'm not exactly sure if I need to use Django forms? or if I can just make a call to the API in a plain js file hosted in my project? the latter would be ideal if I am able to send the image as part of the response... but ofcourse I don't want to expose the API key, which is part of the URL I am making a request to to get the image. I just want to essentially download the image and send it as a response. This is the current code I have been testing out: @api_view(['GET']) def random_image(request): response = requests.get('api url with secret key') if request.method == … -
Django migration error when using queryset in a Modelform
I use a queryset in a modelform instance to populate choices. However, when I now want to run the initial project db migration it returns django.db.utils.ProgrammingError: relation "core_category" does not exist LINE 1: ..._category"."name", "core_category"."fa_icon" FROM "core_cate... I tried to use a try - except block to work-around this but it didn't change the situation. So how to overcome this? As of course the categories table will be empty when migrating initially. class PollerForm(ModelForm): """ A form to create new Pollers """ # Get categories as choices, use try except # for initial migrations if no categories are available yet try: CHOICES = Category.objects.all() except (OperationalError, ProgrammingError) as e: CHOICES = [] # User instance will be passed in the view class Meta: model = Poller exclude = ('created_by',) category = forms.Select(choices=CHOICES) -
Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found
When I am using the get_url function in the SubCategroy model it gives an error like this. NoReverseMatch at /products/category/fiction/ Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found. 1 pattern(s) tried: ['products/\^category/\(\?P(?P<category_slug>[-a-zA-Z0-9_]+)\[\-\\W\]\+\)/\(\?P(?P<sub_category_slug>[-a-zA-Z0-9_]+)\[\-\\w\]\+\)/\$\Z'] there are no errors when I am not using {{sub_category.get_url }} in my HTML. but I want to use the URLs of each sub-category in the HTML. what did I do wrong? the way I used sub-categories maybe not be a good idea. if there are any good suggestions please add to your answer. also, I want to use language as also another categorizing criterion. is there a better or alternate way to implement this? My html {% if category_links %} {% for category in category_links %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="" data-bs-toggle="dropdown">{{ category.category_name }}</a> <ul class="dropdown-menu list-unstyled category-list "> {% if sub_category_links %} {% for sub_category in sub_category_links %} {% if sub_category.category_id == category.pk %} <li><a class="dropdown-item" href="{{ sub_category.get_url }}"> {{ sub_category.subcategory_name }} </a></li> {% endif %} {% endfor %} {% endif %} <li><a class="dropdown-item" href="{{ category.get_url }}"> View All </a></li> </ul> </li> {% endfor %} {% endif %} urls.py urlpatterns = [ path('', views.products, name="products"), path('category/<slug:category_slug>/', views.products, name='products-by-category'), path('category/<slug:category_slug>/<slug:sub_category_slug>/', views.products, name='products-by-sub-category'), path('language/<slug:language_slug>/', views.products_by_language, … -
Django form success messages on an HTML page with multiple forms
I am trying to display 2 forms in my contact.html page in a Django project. Each form needs to display a success message when being successfully submitted by users. The problem is that both forms in the page show the same success message when either of them being submitted. How can I tie the success message to the submitted form on my HTML page? forms.py from dataclasses import field, fields from logging import PlaceHolder from socket import fromshare from django import forms from .models import ServiceRequest, Contact, Newsletter class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','phone','message'] class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ['name','email'] views.py from http.client import HTTPResponse from multiprocessing import context from django.shortcuts import render from django.views.generic import TemplateView from .forms import ContactForm, NewsletterForm, ServiceRequest, ServiceRequestForm from django.http import HttpResponseRedirect from django.contrib import messages from django.urls import reverse def Contact(request): contact_form = ContactForm(request.POST or None) newsletter_form = NewsletterForm(request.POST or None) if request.method == 'POST' and contact_form.is_valid(): contact_form.save() messages.success(request, "Thanks for contacting us!") return HttpResponseRedirect(request.path_info) elif request.method == 'POST' and newsletter_form.is_valid(): newsletter_form.save() messages.success(request, "Thanks for joining our newsletter!") return HttpResponseRedirect(request.path_info) context = { "contact_form":contact_form, "newsletter_form":newsletter_form, } return render(request, "main/contact.html", context) contact.html {% extends "blog/base.html" %} … -
Django allauth Microsoft SSO
I'm having trouble configuring my SSO options for my Django project that I'm working on. I'm hoping to make it so that only those users in my organization are able to sign into the application but I keep getting the following error: AADSTS50194: Application 'Azure: Application (client) ID'(DjangoAppSSO) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant. I have gone in and populated the admin console with my Client ID being the same as above from the Azure account. I also created a Client Secret with my Value and Secret ID and put those in the admin console as well. I populated the Value as the "Key" in admin and Secret ID as the "Secret Key". All the required imports are done for settings.py and I believe the issue is in what I am giving the SOCIALACCOUNT_PROVIDERS possibly. settings.py: SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'APP': { 'tenant': 'organization', 'client_id': 'Azure: Application (client) ID', } } } Just for clarification sake, anywhere it says "Azure: Application (client) ID" is the actual value from there, I just don't want … -
I can't open my dashboard page in login Buttton? Why?
enter image description here I can't open my dashboard page in login button, I don't understand where is my fault. Please someone help me -
Why do we use underscore "_" in this python function using django?
_, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) So here is a function that returns a list of names. I am trying to understand how this function works but I don't understand what that underscore at the beginning is doing there. Thank you! -
Django signals weak=False
If I use Debug=false, the django signals stop working and I have to use week=false. I can't figure out why the default is week=true. I just figured out that it has something to do with the garbage collector. From the fact that I use week=false, does the garbage collector not run? Will the memory fill up with garbage over time and start a memory leak? Example use: @receiver(post_save, sender=sender, weak=False) def define_status(sender, instance, created, **kwargs): ..... -
django terminate adding any input to the database from the form
In an auction web. I'm trying to terminate adding any input (bids, comments and add to watchlist) by any user to the database if the owner of the product press on 'close ' button so I tried to implement this pseudo code: in views.py function listing: t = 1 if == 1: if owner clicks on the close button: ... t = 2 if the user adds a comment: ... if the user adds a bid: ... if user clicks on add to watchlist button: ... else: return message ('Auction has ended') I have implemented this code and the listing page accepted entries and inputs after the owner of the listing clicked on the 'close' button. I also tried to change the value of t to a boolean value ( t = True, if t == True, if user clicked: return t = False) but it didn't work. so what is the problem. def entry(request, name): enter = listing.objects.get(title = name) f= bids.objects.filter(product_id = enter) x = 0 z = "" last = None ended = None like = "k" l = 0 if request.method == 'POST' and request.POST.get("bid"): biddd = int(request.POST['bid']) user = request.user if biddd > x: bids.objects.create(bid= …