Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django redirect url Not Found 404 during working with dynamic forms HTMX
In the view function, I redirect when making a post-request to refer-urk, to which I pass the id of the saved class instance, however, this id is lost and I get 404 Not Found. models.py: class Position(models.Model): position_name = models.CharField(max_length=255, blank=True, verbose_name='Position') created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user by', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) class Meta: ordering = ['date_create'] def __str__(self): return self.position_name class Contacts(models.Model): pos = models.ForeignKey('Position', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Position') contact_label = models.CharField(max_length=100, blank=True, verbose_name='Contact label') contact_value = models.CharField(max_length=255, blank=True, verbose_name='Contact value') def __str__(self): return self.contact_label forms.py: class CreateCVContactForm(forms.ModelForm): class Meta: model = resume.models.Contacts fields = ( 'contact_label', 'contact_value' ) In views.py usnig def createcvcontacts i do redirect for POST-request and pas id of saved object instance to url and then with HTMX i get this id in def ditailcontact which renders detail info abot object instance and pass context to contact_detail.html template: views.py: @login_required(login_url='/users/login/') def create_cv_contacts(request, pk): ''' functions for working with models.Contacts ''' position = Position.objects.get(id=pk) contacts = Contacts.objects.filter(pos=position) form = CreateCVContactForm(request.POST or None) if request.method == "POST": if form.is_valid(): contact = form.save(commit=False) contact.pos = position contact.save() return redirect("resume:detail-contact", pk=contact.id) # here this redirect else: return render(request, "resume/partials/contact_form.html", context={ "form": form }) context = … -
Django and MongoDB Error - REALLY WANT TO KNOW
This is a problem with Django connecting to MongoDB I'm building a Django project. And I want to connect my project to MongoDB. But I have some problem. It is really stressful. I set my code in settings.py like below. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'portfolio', 'CLIENT': { 'host': 'mongodb+srv://mmastrangelo1120:Bluecomet20040117@bluecomet.wxi3uwk.mongodb.net', 'username': 'mmastrangelo1120', 'password': 'Bluecomet20040117', 'authMechanism': 'SCRAM-SHA-1', 'authSource': 'admin' } } } Of course I installed djongo successfully. Every packages were installed, but it shows only error like this when I run any command like py manage.py migrate or py manage.py runserver: django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How to get specific details from a tag web scraping
I'm trying to scrape a specific details as a list from a page Using Beautifulsoup in python. <p class="collapse text in" id="list_2"> <big>•</big> &nbsp;car <br> <big>•</big> &nbsp;bike&nbsp; <br> <span id="list_hidden_2" class="inline_hidden collapse in" aria-expanded="true"> <big>•</big> &nbsp;bus <br> <big>•</big> &nbsp;train <br><br> </span> <span>...</span> <a data-id="list" href="#list_hidden_2" class="link_sm link_toggle" data-toggle="collapse" aria-expanded="true"></a> </p> I need a list with every text contained in the p tag like this, list = ['car', 'bike', 'bus', 'train'] from bs4 import BeautifulSoup import requests response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') p_tag = soup.find("p", {"id":"list_2"}) list = p_tag.text.strip() print(list) output: • car• bike • bus• train how to convert this as a list like, list = ['car', 'bike', 'bus', 'train'] -
How to fetch data at the moment the database updates, without refreshing the page, in Django?
In a web application that I'm building using Django, there is a filed in the main page that fetches a price float from the database and shows it, and I need it to be updated every time that the source price (in the database) gets updated, or within some seconds. And I need that to be without refreshing the page, kind of live you can say. Is there any possible way to reach this without using Django channels, e.g. by using JavaScript or anything else? -
after user logged in... its not redirecting to comments page .when i added ID..to comments in urls.py..then sudden its not redirecting
reverse for 'comments' with no arguments not found. 2 pattern(s) tried: ['comments/(?p[0-9]+)\z', '\ comments/(?p[0-9]+)/\z'] enter image description here [enter image description here] (https://i.stack.imgur.com/av1iG.png) enter image description here -
How to join 2 Models in Django using 2 common columns?
I have 2 tables in Django, one for stock data and another for stock metadata. The date and ticker together are unique in each model, class BulkData(models.Model): date = models.DateField() ticker = models.CharField(max_length=10) name = models.CharField(max_length=400) type = models.CharField(max_length= 20) exchange_short_name = models.CharField(max_length=5) MarketCapitalization = models.DecimalField(max_digits=40, decimal_places=2) request_exchange = models.CharField(max_length=20) class ohlcdata(models.Model): date = models.DateField() ticker = models.CharField(max_length=10, null=False) open = models.DecimalField(max_digits=15, decimal_places=5, null = True) high = models.DecimalField(max_digits=15, decimal_places=5, null = True) low = models.DecimalField(max_digits=15, decimal_places=5, null = True) close = models.DecimalField(max_digits=15, decimal_places=5, null = True) volume = models.DecimalField(max_digits=40, decimal_places=0, null = True) I need todo a join operation on date and ticker and right now I'm using a raw SQL query. query3 = "SELECT * FROM stocklist_bulkdata LEFT JOIN stocklist_ohlcdata ON `stocklist_bulkdata`.`date` = `stocklist_ohlcdata`.`date` AND `stocklist_bulkdata`.`ticker` = `stocklist_ohlcdata`.`ticker` WHERE `stocklist_bulkdata`.`date` = '2023-03-30'" qs3 = BulkData.objects.raw(query3) How can I do this using Django QuerySet instead of raw SQL query? Tried using raw SQL query, looking to do this using Django QuerySet -
Django error: Exception Value: Cannot resolve keyword 'tags' into field. Choices are: date, id, rp_tags, rp_title, slug, tagged_items, url
Currently, I am learning Django and with it, I am building a non profit organization's website. It is almost like a blog website except for like, comment features. Anyways, there's a page where all the reports are listed and these have tags. I used Django-taggit. I followed through a tutorial to show the tags and making it clickable and filter by tags - but I am running into the following error: error1 error2 Here are my relevent model, view, app/url and template files: from django.utils import timezone from django.utils.translation import gettext_lazy as _ from taggit.managers import TaggableManager class Report(models.Model): rp_title = models.CharField(max_length=500) slug = models.SlugField(max_length=300, unique_for_date='date') url = models.URLField(max_length=500) date = models.DateTimeField(default=timezone.now) rp_tags = TaggableManager() # rp_body = models.TextField() def __str__(self): return self.rp_title class Meta: ordering = ('rp_title',) def get_absolute_url(self): return reverse('report:report_detail', args=[self.slug]) class ReportListView(ListView): model = Report queryset = Report.objects.all() context_object_name = 'reports' template_name = 'blog/report_list.html' class ReportTagView(ListView): model = Report context_object_name = 'reports' template_name = 'blog/report_list.html' def get_queryset(self): return Report.objects.filter(tags__slug=self.kwargs.get('tag_slug')) <div class="sidebar__single sidebar__tags"> <h3 class="sidebar__title">Tags</h3> <div class="sidebar__tags-list"> {% for tag in report.rp_tags.all %} <a href="{% url 'blog:report_tag' tag.slug %}" class="link-light text-decoration-none badge bg-secondary"> {{ tag.name }} </a> {% endfor %} </div> </div> app_name = 'blog' urlpatterns = [ … -
Why changes made in Wagtail's Editor only appear with a delay in the backend (although can be seen in front tend)?
For several months now, when I edit a Page in the Editor of Wagtail and the click "Save", these changes sometimes (often at certain times) disappear fron the Editor. I can see it because when I edit content, I immediately go check the result in frontend and go back to the Editor to edit mistakes for example. In thoses situations, I can see the right content in front end, but not in the back end. I eventually discovered that I need to wait, and after a few minutes at most, the changes appear back in the Editor. Sometimes, if I make successive editions, some of them will appear first, and then the other. Simple example : I add a picture in a blog post, click Save or Publish. I can see the picture in front end, but when I come back to edit this page in back end, the picture is not there anymore. If I wait a little (either come back or just wait and refreh the page in the Editor), the picture will (re)appear in the Editor. Note that the CMS seems to really save the changes because I can see them in front end and in the … -
Django 4.2: Formset "This field is required"
Basic idea: Have a custom database table with only 2 text fields. It will never be updated by the user! Allow the user to select records via checkboxes. The selected records only influence the file that is being served later by the server. This is my models.py: class Person(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) I've created a custom non-model-form, derived from forms.Form only, because I will never use the user input to update the database table. All I need is some boolean information from the user. Here's forms.py: class PersonForm(forms.Form): first_name = forms.CharField() last_name = forms.CharField() selected = forms.BooleanField() PersonFormset = forms.formset_factory(PersonForm, extra=0) When the user calls the GET-view, he will see all people in the table and can select some via the checkboxes (notice: form has an additional boolean field). This is the GET-part of my views.py: obj = Person.objects.all().values() forms = PersonFormset(initial=obj) return render(request, 'myapp/mytemplate.html', {'formset': forms}) Everything works fine and displays correctly inside my HTML table. But then the POST fails. Here's the POST-part of my views.py: forms = PersonFormset(request.POST) The forms.is_valid() function returns false and all the error messages state 'This field is required' for all fields of all forms. For example forms[0]['first_name'].value() is None … -
django orm - annotate / aggregation (avg) in subquery
I have this model: class UserMovieRel(models.Model): user = models.ForeignKey("register.User", on_delete=models.CASCADE) movie = models.ForeignKey("Movie", on_delete=models.CASCADE, related_name="users") rating = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(10)], null=True, blank=True ) advice = models.CharField(max_length=500, null=True, blank=True) objects = UserMovieRelManager() def __str__(self) -> str: return f"{self.user} - {self.movie} (rating: {self.rating or 'n/a'})" class Meta: constraints = [ models.UniqueConstraint(fields=["user", "movie"], name="user_movie_unique"), ] I'm trying to get the avg rating for each movie in this way: avg_ratings = UserMovieRel.objects.filter(movie_id=OuterRef("movie_id")).exclude(rating__isnull=True).annotate(avg_rating=Avg("rating")) UserMovieRel.objects.annotate(avg_rating=Subquery(avg_ratings[0])) but it fails: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I've tried also with aggregation: UserMovieRel.objects.annotate( avg_rating=Subquery( UserMovieRel.objects.filter( movie_id=OuterRef("movie_id") ).aggregate( avg_rating=Avg("rating") )["avg_rating"] ) ) but I've got the same error. any help on this? Thanks -
next-auth and django rest framework - how should I fetch user data after JWT authentication?
I'm building an app that uses django rest framework and simplejwt to authorize the users. I'm having trouble understanding what should be the optimal way of fetching user data after the user logs in and JWT is provided. Let's say I'd want to display the user name and email on the navigation bar. Should I: a) add the user name and email to the JWT response (not encoded)? b) after getting the JWT, use it to fetch the user data? As of now, my JWT (/api/auth/) endpoint response looks something like this: { "refresh": "refresh_token", "access": "access_token" } And here's an example of the decoded access token: decoded access token I thought that perhaps next-auth decodes the JWT response and pulls the user data from there. -
I am facing this error: cannot convert dictionary update sequence element #0 to a sequence (Django)
I am trying to edit some preregistered user details, I can see the user id is printed when I do it via the template and am Trying to det a default value for the username in this form (because I want it to be the logged in user) The code is as follows: views.py from django.shortcuts import render,redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.forms import modelformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login,logout from .models import * from .forms import * def udetail(request): userid = request.user.id user = account.objects.get(pk=userid) form=updateuser(initial={'username'== user}) if request.method == 'POST': form = updateuser(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'main/udetail.html', context) Forms.py from django.forms import ModelForm from django.forms import BaseInlineFormSet from django.forms import BaseModelFormSet from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import * class updateuser(ModelForm): class Meta: model = account fields = ['username','dob','height','weight','extype','gender'] models.py from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, BaseUserManager GENDER_CHOICES = [ ("Male", "Male "), ("Female", "Female "), ] EX_CHOICES = [ ("70", "0-30 minutes "), ("250", "30-90 minutes "), ("600", "More than 90 minutes "), ] class … -
Django : redirect to previous url
its possible to create a thing which redirect me to previous url hi im learning django and thats one freaking me out i want create a button in my project which redirect user to url came form e.g. user from profile goes to followings and want get back to profile To be more precise a button like this little thing up here enter image description here which i can use it in entire project i tried everything came to my mind or i found in my searches with no results:) -
How do I stop Django from logging PermissionDenied exceptions?
My custom middleware raises a PermissionDenied exception in certain cases to return a 403 response to the client. I believe this is the "correct" way to do this. Unfortunately it also logs the exception with a traceback every time this happens, even with DEBUG set to False. 2023-05-08 10:27:25,293 WARNING django.request Forbidden (Permission denied): / Traceback (most recent call last): File "/opt/project/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/project/myapp/middleware.py", line 112, in call raise PermissionDenied django.core.exceptions.PermissionDenied I don't care about these exceptions. Is there a simple way to prevent them from being logged? -
I can't connect to another server using SSH tunnel in Django when containerizing it with Docker
I set up a SSH Tunnel for a MySQL instance in another server in my Django settings. Something like this: ssh_tunnel = SSHTunnelForwarder( os.environ['MYSQL_SERVER_IP'], ssh_username=os.environ['MYSQL_SERVER_USERNAME'], ssh_password=os.environ['MYSQL_SERVER_PASSWORD'], remote_bind_address=('localhost', 3306), ) ssh_tunnel.start() The package used is https://github.com/pahaz/sshtunnel When I start the app in local it works perfect, but when it's inside a container via docker-compose it throws Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 64590689ab386fb7f27ad7ca, topology_type: Unknown, servers: [<ServerDescription ('127.0.0.1', 27017) The docker-compose of this part of the service is this one: web: restart: always build: context: . dockerfile: ./Dockerfile ports: - "8000:8000" expose: - "8000" - "27017" links: - postgres:postgres volumes: - static_volume:/usr/src/app/static - media_volume:/web/media/ env_file: .env environment: DEBUG: 'true' command: python manage.py runserver 0.0.0.0:8000 networks: - web And this is the Dockerfile related to it FROM python:3.9-slim-buster RUN apt-get update && apt-get install -y gcc python3-dev RUN apt-get install libeccodes-dev -y RUN python -m pip install --upgrade pip COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY . . What am I doing wrong? Thanks! I tried exposing the port mentioned in the error (27017) and installing the ssh package in the docker instance. -
Removing url prefixes in django
Here is my localhost url localhost: 127.0.0.1:/8000/searches/?q=css I want to get rid of these: '?q=' I tried removing the name attributes from my html. <input type="text"> -
Unable to redirect non-www to www in django Nginx project on Digital Ocean
Hello I would be grateful if someone could please help with the following Nginx configuration: /etc/nginx/sites-available/example server { server_name example.com *.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/admin/pyapps/example/example/static/; } location /static/admin/ { alias /home/admin/pyapps/example/example/static/admin/; } location /media/ { root /home/admin/pyapps/example; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = admin.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = backoffice.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name example.com *.example.com; return 404; # managed by Certbot } I would like to create a redirection for example.com to https://www.example.com. Note that I am using django-hosts. My configuration for django-hosts below: settings.py ROOT_URLCONF = 'example.urls' ROOT_HOSTCONF = 'example.hosts' DEFAULT_HOST = 'www' # DEFAULT_REDIRECT_URL = "http://www.example.com:8000" DEFAULT_REDIRECT_URL = "http://www.example.com" PARENT_HOST = 'example.com' # HOST_PORT = '8000' MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', .... 'django_hosts.middleware.HostsResponseMiddleware', ] hosts.py from django.conf import settings from … -
Converting django app to windows exe using pyinstaller
I converted a django application into a windows application using pyinstaller. I created a seperate file runserver.py where I'm running the server in a thread and then opening webbrowser using web browser module. I'm getting error as No python at 'path' . It is taking my path on other computers too. It's not taking the path of env i created within django How can I activate the env of django so when people click on exe it should use the dependencies of env created within django app. -
Django doubling values in queryDict ... help please
I create some cascade models, double forms, and set of HTML-s with double views.py in django. When i want to save data i get doubling of data that has hidden input attribute. this is from my forms.py `class TaskContentForm(forms.ModelForm): task = forms.ModelChoiceField(queryset=Task.objects.all(), label="Task", widget=forms.HiddenInput(), required=True ) position_label = forms.CharField(label="Position Label", widget=forms.TextInput(attrs={'class': 'form-control task_content'}), required=True ) position_name = forms.CharField(label="Position Name", widget=forms.TextInput(attrs={'class': 'form-control task'}), required=True ) . . .` my models.py `class Task(models.Model): . . . class TaskContent(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) position_label = models.CharField(max_length=100) position_name = models.CharField(max_length=100) . . . ` and my edit_content.html `<div class="row item-row"> <div class="col-12"> <div class="card card-body bg-white border-light shadow-sm mb-4"> <h2 class="h5 mb-4">Transaction information</h2> <form action="{% url 'task_contents' task=task.id pk=task_content.id %}" method="post"> {% csrf_token %} {% if task.id %} <input type="hidden" name="task" value="{{ task.id }}"> {% endif %} <div class="row"> {% for field in form %} <div class="col-md-6 mb-3"> <div>{{ field.label_tag }}{{ field }}</div> </div> {% endfor %} </div> <div class="mt-3"> <a class="btn btn-danger delete_item" data-href="{% url 'task_contents' task=task.id pk=task_content.id action='single' %}">Delete</a> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> </div>` When i press submit, i get terminal output: `{'_state': <django.db.models.base.ModelState object at 0x00000203DFEC5A20>, 'id': 8, 'task_id': 4, 'position_label': '1032', 'position_name': 'Kvaka', 'material': 'Silumin', 'material_supplier': … -
How to call an a callbacks when I take an a type of autorization?
I have got a project, which have an autorization by vk and google. I need to call funcitions like vk_callback or google_callback when i make autorization by this types. Hoe can i do it? views.py: def home(request): return HttpResponse('Home Page') def vk_callback(request): user_info_getter = UserInfoGetter(request.user, 'vk-oauth2') take_info = user_info_getter.get_user_info_vk() if take_info: name, last_name, photo = take_info print(name, last_name, photo, sep='\n') return redirect(home) def google_callback(request): user_info_getter = UserInfoGetter(request.user, 'google-oauth2') take_info = user_info_getter.get_user_info_google() if take_info: name, last_name, photo = take_info print(name, last_name, photo, sep='\n') return redirect(home) I try to make it by url-address, but it doesn't work: urls.py: urlpatterns = [ path('vk/callback/', views.vk_callback, name='vk_callback'), path('google/callback/', views.google_callback, name='google_callback') ] After successful authorization takes info from server: "GET /complete/google-oauth2/?state=Qw2iyDHL9w6ueu4aKU8cfx7lC4VKjEgN&code=4%2F0AbUR2VMMND7R2atmHBSbfGxtlbRBzTwiMnsiSpcYAmLI2cQeKuK7D1b_iUJ6uc2Pgp863w&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.ema il+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&prompt=none HTTP/1.1" 302 0 -
Django-Huey 'NoneType' object is not callable
I keep getting an error each time I run Django-Huey queue. I have set up DJANGO_HUEY using greenlet worker. ##django sttings.py DJANGO_HUEY = { 'default': 'files', #this name must match with any of the queues defined below. 'queues': { 'files': {#this name will be used in decorators below 'huey_class': 'huey.RedisHuey', 'name': 'files_tasks', 'immediate': False, 'consumer': { 'workers': 50, 'worker_type': 'greenlet', }, }, } ##tesk @db_task(queue='files') def process_file(): #... file processing #error venv\Lib\site-packages\huey\consumer.py", line 210, in get_stop_flag return GreenEvent() TypeError: 'NoneType' object is not callable. How can I fix this error. -
Django - insert model reference in static location
I am working on a new Django-application and wanted to insert a reference to staticfiles from the model I've created. Model: url=testname I want to insert this name into an image url through static: {% static 'folder/testname.png' %} Is there any way I can insert this, like inserting model.url? -
Not being able to Migrate new app because 'Migration admin.0001_initial is applied before its dependency userSocial.0001_initial on database 'default'
I created a Django root, where I created one app to access my database and created all the necessary models, serializers, views and urls to access it as an API on my web app. After finishing that Django App with a PostgreSQL DB and a Web App. I wanted to create 2 new Apps in the same root to access the same database but for a different use scenario and a different Web App. The first one has the ability to do everything View, Delete and Update my database, this next two apps are for creating Users and creating a small Social Media with posts and comments. However after getting the UserModel ready and set up the models for the Social Media App, I am getting this error: PS C:\codeacademy\O_lar\o_lar_db> python manage.py migrate Traceback (most recent call last): File "C:\codeacademy\O_lar\o_lar_db\manage.py", line 22, in <module> main() File "C:\codeacademy\O_lar\o_lar_db\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\migrate.py", line 120, … -
Django template variables rendered after 403
I have an HTML template which will render button depending on context variable. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} <button type="submit">{{ number }}</button> </form> </body> </html> After passing "if" check for numbers greater than 400, the function should return response 403 and stop. But in my case it only ignores a template and still renders a context variable. def run_script(request, number): if number > 400: return HttpResponseForbidden() context = {'number': number} return render(request, "mainapp/number.html", context) The only solution I found is so set the rendered value to null in the "if" statement if number > 400: number = None return HttpResponseForbidden() This way I get proper response 403, but I dont like this method since it requires changing every variable, when multiple provided and doesn't look like a proper implementation. Any suggestion how to properly stop execution on response 403? -
Django ModelForm is_valid method always false
i'am getting an error using Django ModelForm. The method form.is_valid is always false and i don't understand why. After have put all the values in the form it doesn't enter inside the method and then nothing happens when i press the submit button. This is my code. ** models.py ** class Product(models.Model): image= models.ImageField(blank=True, null=True) name= models.CharField(max_length=200) type=models.CharField(max_length=30) product_code=models.CharField(max_length=20, unique=True) productor= models.CharField(max_length=50) color= models.CharField(max_length=40) size=models.CharField(max_length=100) weight=models.FloatField(default=0) full_price= models.FloatField(default=0) discount=models.PositiveIntegerField(default=0) final_price=models.FloatField(default=0) quantity= models.PositiveIntegerField(default=0) supplier= models.ForeignKey(User,on_delete=models.CASCADE) #Utente staff che ha inserito il prodotto recensioni = models.ManyToManyField(Recensione) def __str__(self): return self.nameclass Computer(Product): display_size= models.FloatField(default=0) display_resolution= models.CharField(max_length=20) cpu= models.CharField(max_length=50) ram= models.PositiveIntegerField(default=0) disk_size= models.FloatField(default=0) disk_type= models.CharField(max_length=20) operating_system= models.CharField(max_length=100) graphic_card= models.CharField(max_length=50) battery_autonomy= models.FloatField(default=0) additional_function= models.CharField(max_length=1000) ** forms.py ** class ComputerForm(forms.ModelForm): class Meta: model=Computer fields=['image','name','product_code','productor','color','size','weight','full_price','discount','quantity', 'display_size', 'display_resolution', 'cpu', 'ram', 'disk_size', 'operating_system', 'graphic_card', 'battery_autonomy', 'additional_function'] ** views.py ** #Aggiunta nuovo Prodotto @login_required def add_product(request,category): templ="products/product_form.html" form=ComputerForm() if request.method == "POST": form=ComputerForm(request.POST, request.FILES ) #Controllo campi form siano validi if form.is_valid(): print("Valid") form.save() return redirect("products:all_products") return render(request,template_name=templ,context={"form":form}) ** product_form.html ** <div class="col-4" style= "width:30%;right:+20px;"> <h3> <b> Dati prodotto: </b> </h3> <form method='POST'> {% csrf_token %} {% crispy form %} <br> <input type="submit" class="btn btn primary" style="background-color:blue;color:white;" value="Aggiungi Prodotto"> </form> </div>