Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ASGI deployment - question about Procfile and Daphne
I've made a simple chat room application in Django, using Daphne as a web server, Channel Layers with Redis, and SQLite as a database. Now I'm trying to deploy it to Heroku. The whole project's directory looks like this: ├───Chat Room Application └───chat_project | ├───chat | ├───chat_project | ├───room |---Dockerfile |---Procfile |---requirements.txt Sorry for the design, the tree command didn't print it the way I wanted. The Chat Room Application directory is where the git repo has been initialized and where the Procfile is supposed to be in. The outer chat_project directory was generated automatically, by Django. And the inner chat_project directory is where the settings.py and asgi.py files are. chat and room are the different Django apps. Since it is an ASGI application, I use the following command to run the web server: daphne chat_project.asgi:application So the Procfile looks like this: web: daphne chat_project.asgi:application My problem is that in my current configuration, the Procfile doesn't see the inner chat_project directory. So when I deploy it, using git push heroku main , I get: === web (Free): daphne chat_project.asgi:application (1) web.1: crashed 2022/11/15 22:12:24 +0200 (~ 6s ago) And when I look at the log, I see: ModuleNotFoundError: No module … -
How to allow requests with API KEY for client application in DJANGO without user login?
I am trying to have a global API KEY where it would be mandatory for the client application to send the API key in headers to get a successful response. I intend to keep my APIs secure and not expose so much information to all public URLs by using IsAuthenticatedOrReadOnly. Even after passing the API keys from the headers if someone tries to go and get it from the network it would be harmful so can anyone help me with the better approach on how we cab secure our API's Find Below more information about what I am trying to achieve. GET /products/ HEADERS - EMPTY RESPONSE - PLEASE PASS THE API KEY TO ACCESS THE APIS GET /products/ HEADERS - [API_KEY - SAMPLE] RESPONSE - [PRO1, PRO2, PRO3, PRO4] POST /products/ HEADERS - [API_KEY - SAMPLE] RESPONSE - PLEASE PROVIDE AUTHENTICATION CREDENTIALS -
Django 4.0.1 - Deleting Instance results in `TypeError: Model instances without primary key value are unhashable`
When deleting a model instance from the admin portal, it raises TypeError: Model instances without primary key value are unhashable. Models.py from django.db import models from djongo import models as MDB_models from django.core.validators import RegexValidator from simple_history.models import HistoricalRecords import datetime,json,uuid from django.contrib.auth.models import User from ..API import Model_Notifications from ..PublicPages import colours from django.apps import apps import sys,requests def leading_zero(value:int): return "{:02d}".format(value) def GetImage(ID): IMG_APP = apps.get_model("VehicleImages","Image") QS = IMG_APP.objects.filter(id=ID) if len(QS) == 0: return None else: return QS.first() class Status(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=150,default="",unique=True) icon = models.ImageField(blank=True,upload_to="StatusIcons") alternateText = models.TextField(max_length=500,default="") history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO NOT EDIT") def __str__(self): return self.name class VehicleChassis(models.Model): _id = MDB_models.ObjectIdField(auto_created=True, unique=True, primary_key=True) name = models.CharField(max_length=100,default="",unique=True) manufacturer = models.CharField(max_length=100,default="",blank=True) vehicle_class = models.CharField( max_length=30, default="", blank=True, choices=[ ("MINI BUS","Mini Bus"), ("MIDI BUS","Midi Bus"), ("SINGLE DECKER BUS","Single Decker Bus"), ("ARTICULATED SINGLE DECKER BUS","Articulated Single Decker Bus"), ("DOUBLE DECKER BUS","Double Decker Bus"), ("COACH","Coach"), ("INTERDECKER COACH","Interdecker Coach"), ]) history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["_id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO NOT EDIT") def __str__(self): return self.name class VehicleModel(models.Model): _id = MDB_models.ObjectIdField(auto_created=True, unique=True, primary_key=True) name = models.CharField(max_length=100,default="",unique=True) manufacturer = models.CharField(max_length=100,default="") history = HistoricalRecords( history_id_field=models.UUIDField(default=uuid.uuid4), excluded_fields=["_id"] ) last_modified_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL,help_text="Set Automatically! DO … -
Создание django-проекта
Не создается Django проект. Установил виртуальное окружение, Django (4.1.3), но при создании проекта выдает ошибку. Работаю на Macbook M1enter image description here Создавал несколько разных виртуальных окружений на разные версии Python, устанавливал разные версии Django -
Why Is Sub the Only Thing Returned in My Payload (Django pyjwt)?
So I recently just started django. I added some authentication for my backend. The issue is: when I decode my token, only the sub is returned. I'd like to know why. Here is my authentication.py file: from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import PermissionDenied from django.contrib.auth import get_user_model from django.conf import settings import jwt User = get_user_model() class JWTAuthentication(BasicAuthentication): def authenticate(self, request): header = request.headers.get('Authorization') if not header: return None if not header.startswith('Bearer'): raise PermissionDenied({'message': 'Invalid authorization header!'}) token = header.replace('Bearer', '') try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) user = User.objects.get(pk=payload.get('sub')) except jwt.exceptions.InvalidTokenError: raise PermissionDenied({'message':'Invalid token'}) except User.DoesNotExist: raise PermissionDenied({'message':'User not found'}) return (user, token) Here is my model: class CustomUser(AbstractUser): username = models.CharField(max_length=200, null=True, blank=True) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) email = models.EmailField(_('email address'), unique=True) bio = models.TextField(null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] -
Why my url appears as a post request when its get django
I have some templates in a django project. I'm trying to save them in the the url with a post request even though I specify it in the html document. Here's my views.py ` from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import WcaForm, IdForm from . import wcaScraper # Create your views here. def id(response): form = IdForm(response.GET) return render(response, "main/id.html", {"form": form}) def idresults(response): print(response.method) if response.method == "GET": print(wcaScraper.getDataByName(response.GET.get('name'))) return render(response, "main/nameresults.html", {"ids": wcaScraper.getDataByName(response.GET.get('name'))}) def search(response): form = WcaForm(response.GET) return render(response, "main/search.html", {"form": form}) def results(response): wcaData = wcaScraper.getDataById(response.GET.get('id')) variablePassed = { "id": response.GET.get('id'), "single3": wcaData[0].single, "avg3": wcaData[0].avg, "single2": wcaData[1].single, "avg2": wcaData[1].avg, "single4": wcaData[2].single, "avg4": wcaData[2].avg, "single5": wcaData[3].single, "avg5": wcaData[3].avg, "single6": wcaData[4].single, "avg6": wcaData[4].avg, "single7": wcaData[5].single, "avg7": wcaData[5].avg, "blind3single": wcaData[6].single, "blind3avg": wcaData[6].avg, "fmsingle": wcaData[7].single, "fmavg": wcaData[7].avg, "ohsingle": wcaData[8].single, "ohavg": wcaData[8].avg, "clocksingle": wcaData[9].single, "clockavg": wcaData[9].avg, "megasingle": wcaData[10].single, "megaavg": wcaData[10].avg, "pyrasingle": wcaData[11].single, "pyraavg": wcaData[11].avg, "skewbsingle": wcaData[12].single, "skewbavg": wcaData[12].avg, "squaresingle": wcaData[13].single, "squareavg": wcaData[13].avg, "blind4single": wcaData[14].single, "blind4avg": wcaData[14].avg, "blind5single": wcaData[15].single, "blind5avg": wcaData[15].avg, "multisingle": wcaData[16].single, "multiavg": wcaData[16].avg, } return render(response, "main/results.html", variablePassed) ` And my html template <html> <h1>Search by name</h1> <form method="get" action="/idresults"> {% csrf_token %} {{form}} <button type="submit">Search</button> </form> <p>or</p> <a href="id/"> Search by WCA Id</a> </html> … -
improperly configured at /18/delete, Django views issue
I have searched through the other questions similar to my own problem and have come to no solution so im hoping someone can help me figure out where i went wrong. I'm trying to implement a delete post option in my blog program but it is throwing the following error once you click the 'delete' button: ImproperlyConfigured at /18/delete/ Deletepost is missing a QuerySet. Define Deletepost.model, Deletepost.queryset, or override Deletepost.get_queryset(). I am nearly sure its a problem with my URLS.py though what exactly i cannot figure out. the following is the code in question: Views.py # delete post class Deletepost(LoginRequiredMixin, DeleteView): form_class = Post success_url = reverse_lazy('blog:home') template_name = 'templates/post.html' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py urlpatterns = [ # home path('', views.postslist.as_view(), name='home'), # add post path('blog_post/', views.PostCreateView.as_view(), name='blog_post'), # posts/comments path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'), # edit post path('<slug:slug>/edit/', views.Editpost.as_view(), name='edit_post'), # delete post path('<int:pk>/delete/', views.Deletepost.as_view(), name='delete_post'), # likes path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), ] post.html <a class="btn btn-outline-danger" href="{% url 'delete_post' post.id %}">Delete</a> Thanks for your time and i'm sorry for the trivial question but you guys are much smarter than me! -
When using django-allauth how do I get the Sites section in the admin page to show?
I'm new to Django and I'm trying to learn it from Django for Professionals by William Vincent. After installing django-allauth and following the steps in the book, I managed to get the logging in and out the sign up functionality to work. However, when I go to 127.0.0.1:8000/admin, I don't see a Sites section. This section is later used in the book to change the site being referred to (example.com) in the registration confirmation email. I've searched for django-allauth Site admin in here and in the docs but I couldn't find anything about making the Sites section show. -
How can I use Transaction rollback with Multiple forms in Django
I have four forms and I need them to be saved one by one however when any one form yields validation error then I need the data saved in the database to be removed. I understand the transaction rollback with Django query but not able to figure out that how would I will do the same with forms. with transaction.atomic(): # to store errors from the forms if any errors = [] # FormSubmitter are the function to submit the forms or provide the errors. cartoon_image_form_submitter = CartoonImageFormSubmitter( data=cartoon, request=request, form_model_keys=CartoonImage_form_model_keys, ) if ('errors' in cartoon_image_form_submitter and cartoon_image_form_submitter['errors'] is not None): errors.append(cartoon_image_form_submitter["errors"]) swimming_level_master_form_submitter = SwimmingLevelMasterFormSubmitter( data=swimming_level_master, form_model_keys=SwimmingLevelMaster_form_model_keys, ) if ('errors' in swimming_level_master_form_submitter and swimming_level_master_form_submitter['errors'] is not None): errors.append(swimming_level_master_form_submitter["errors"]) stages_summary_form_submitter = StagesSummaryFormSubmitter( data=stages_summary, form_model_keys=StagesSummary_form_model_keys, ) if ('errors' in stages_summary_form_submitter and stages_summary_form_submitter['errors'] is not None): errors.append(stages_summary_form_submitter["errors"]) lesson_level_detail_form_submitter = LessonLevelDetailFormSubmitter( data=lesson_level_details, form_model_keys=LessonLevelDetail_form_model_keys, ) if ('errors' in lesson_level_detail_form_submitter and lesson_level_detail_form_submitter['errors'] is not None): errors.append(lesson_level_detail_form_submitter["errors"]) if errors: errors = '<br>'.join([str(elem) for elem in errors]) from django.utils.safestring import mark_safe errors = mark_safe(errors) messages.error(request, errors) return HttpResponseRedirect('../levels/new') return HttpResponseRedirect('../levels/new') I tried with transaction.atomic(): and thought it will work because forms also saves data in db -
Implemented google login using server side flow how can i do for LinkedIn for Django REST Framework and React?
Hi i have Successfully implemented server side google login But i can't find proper implementation for server side login for LikendIn I am using Django Rest framework for bckend and React as front-end i have followed this blog: https://www.hacksoft.io/blog/google-oauth2-with-django-react-part-2 any specific blog or implementation ? -
How can an included file know it is included
In django you can include html files in other html files. So my question is there a variable so that the second file knows that it has been included? If not by default can I create one? Here is an example: a.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>From a.html</h1> {% include "b.html" %} </body> </html> b.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% if included_in_file %} <h1>From b.html</h1> {% else %} <h1>Hello</h1> {% endif %} </body> </html> The point is that when a file is included it shows something else than if it is normally used. Or do I just have to make a second file for the same use? -
multi db routing problem when migrate models in Django
I want to create separate database for hold project logs which define its models on LogCenter app. All other tables of models hold on default database. This is my settings.py: DATABASE_ROUTERS = ['Core.models.ALLDBRouter', 'Core.models.LogCenterRouter', ] DATABASES = { 'default': { 'ENGINE': os.environ.get("DEFAULT_DATABASE_ENGINE"), 'NAME': os.environ.get("DEFAULT_DATABASE_NAME"), 'USER': os.environ.get("DEFAULT_DATABASE_USER"), 'PASSWORD': os.environ.get("DEFAULT_DATABASE_PASSWORD"), 'HOST': DEFAULT_DATABASE_HOST, 'PORT': os.environ.get("DEFAULT_DATABASE_PORT"), # 'OPTIONS': { # 'options': '-c statement_timeout=30000', # }, }, 'log_config': { 'ENGINE': os.environ.get("LOG_DATABASE_ENGINE"), 'NAME': os.environ.get("LOG_DATABASE_NAME"), 'USER': os.environ.get("LOG_DATABASE_USER"), 'PASSWORD': os.environ.get("LOG_DATABASE_PASSWORD"), 'HOST': LOG_DATABASE_HOST, 'PORT': os.environ.get("LOG_DATABASE_PORT"), } } And this is my database routers: class LogCenterRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'LogCenter', } def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'log_config' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'log_config' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth … -
Django API without DRF: What are the consequences
I'm not sure what might go wrong when I have to integrate a django API (built using JsonResponse and without extra frameworks) with a frontend, in this case, Next.js. I built a django API using JsonResponse (void of DRF). I want to build a frontend client with Next.js that would make API calls to my django API. My questions are: Will I have to run both django and next.js servers at the same time to execute the full project? I think I would face some challenge with csrf token, what other challenges may I face having built my API without an API framework as Django Rest Framework? -
Encountered two children with the same key...ecommerce website
why is it that there are two children with the same key Im using React and Im trying to make ecommerce website I dont understand the error of double keys import React, {useEffect} from 'react' import { Link, useParams, useNavigate, useLocation, useSearchParams } from 'react-router-dom' import { useDispatch, useSelector } from 'react-redux' import { Row, Col, ListGroup, Image, Form, Button, Card} from 'react-bootstrap' import Message from '../components/Message' import { addToCart } from '../actions/cartActions' export default function CartScreen() { const { id} = useParams() const { search } = useLocation(); const [searchParams] = useSearchParams(); const dispatch = useDispatch(); const productID = id; const qty = search ? Number(search.split("=")[1]) : 1; const cart = useSelector(state => state.cart) const { cartItems} = cart console.log('cartItems:', cartItems) useEffect(() => { if(productID) { dispatch(addToCart(productID, qty)) } }, [dispatch, productID, qty]) return ( <Row> <Col md={8}> <h1>Shopping Cart</h1> {cartItems.length === 0 ? ( <Message variant='info'> Your cart is empty <Link to='/'>Go Back</Link> </Message> ) : ( <ListGroup varient='flush'> {cartItems.map(item => ( <ListGroup.Item key= { item.product }> <Row> <Col md={2}> <Image src={item.image} alt={item.name} fluid rounded/> </Col> <Col md={3}> <Link to={`/product/${item.product}`}>{item.name}</Link> </Col> <Col md={2}> ${item.price} </Col> </Row> </ListGroup.Item> ))} </ListGroup> )} </Col> <Col md={4}> </Col> </Row> ) } Im … -
no errors are coming also i print the values when i login its not none its the same details when i entered login time
i am creating a website so i finshed register page in login page every details are corret but thats showing please verify ur details i mean the else part also i put a print statment after username and password same details are printing when i typed but not access login views.py def sign_in(request): if request.method == "POST": username=request.POST['username'] password=request.POST['password'] print(username,password) user = authenticate(username=username,password=password) if user is not None: login(request,user) messages.success(request,"you are logged successfully ") return redirect("front_page") else: messages.error(request,"please verify your details") return redirect("sign_in") return render(request,"login.html") def front_page(request): return render(request,"frontpage.html") urls.py path('log_in',views.sign_in,name="sign_in"), path('front_page',views.front_page,name="front_page"), html <div class="signup-form"> <form action="{% url 'sign_in' %}" method="POST"> {% csrf_token %} <h2 class="text-center">Login</h2> <p class="text-center">Please fill in this form to login your account!</p> <hr> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <span class="fa fa-user"></span> </span> </div> <input type="text" class="form-control" name="username" placeholder="Username" required="required"> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-lock"></i> </span> </div> <input type="password" class="form-control" name="password" placeholder="Password" required="required"> </div> </div> <div class="form-group d-flex justify-content-center"> <button type="submit" class="btn btn-primary btn-lg">Login</button> </div> <div class="text-center text-primary">Dont have a account? <a href="{% url 'register' %}">Create here </a></div> </form> </div> i just want to login with username and password,but it shows please verify your details .but … -
How to execute a python function based on a selection of a Drop down list in HTML?
HTML: <div class="iq-custom-select d-inline-block sea-epi s-margin"> <select name="cars" class="form-control season-select"> <option value="season1">Season 1</option> <option value="season2">Season 2</option> <option value="season3">Season 3</option> <option value="season4">Season 4</option> <option value="season5">Season 5</option> </select> </div> And this is my Pyghon method I really do not know how it should be written. DJANGO: def single_show(request, pk): show = get_object_or_404 (Show, pk=pk) episode_s1 = Episode.objects.filter(series=pk,season=1).order_by("episode_number") episode_s2 = Episode.objects.filter(series=pk,season=2).order_by("episode_number") episode_s3 = Episode.objects.filter(series=pk,season=3).order_by("episode_number") episode_s4 = Episode.objects.filter(series=pk,season=4).order_by("episode_number") episode_s5 = Episode.objects.filter(series=pk,season=5).order_by("episode_number") return render(request, "listings/single_show.html",{ 'show' : show, 'episode_s1' : episode_s1, 'episode_s2' : episode_s2, 'episode_s3' : episode_s3, 'episode_s4' : episode_s4, 'episode_s5' : episode_s5, }) I have a dropdown made in html and when I select a value I want to show my episodes -
Create custom user model and Profile
Well I'm trying to create user addition form from frontend that creates user and additional info based on custom user model.But I'm getting duplicate key value violates unique constraint "users_driver_email_key" DETAIL: Key (email)=() already exists. here is my code: Models.py class CustomUser(AbstractUser): is_driver = models.BooleanField(default=False) is_accountant = models.BooleanField(default=False) is_dispatcher = models.BooleanField(default=False) class Driver(models.Model): driver_user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, primary_key = True) full_name = models.CharField(max_length=50, default=None) phone_number = models.CharField(max_length=50, default=None) email = models.EmailField(unique=True,max_length=255, default=None) address = models.CharField(max_length=70, default=None) country = models.CharField(max_length=50, default=None) state = models.CharField(choices=US_STATES,max_length=50, default=None) city = models.CharField(max_length=50, default=None) zipp = models.CharField(max_length=50, default=None) birth_date = models.DateField(default=None) license_no = models.IntegerField(default=None) license_exp_date = models.DateField(default=None) last_medical = models.DateField(default='', blank=True, null=True) next_medical = models.DateField(default='', blank=True, null=True) last_drug_test = models.DateField(default='', blank=True, null=True) next_drug_test = models.DateField(default='', blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=STATUS, default=1) class DriversFiles(models.Model): file = models.FileField(upload_to="media/", blank=True, null=True) driver_files = models.ForeignKey('Driver', on_delete=models.CASCADE, default=None, null=True) @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): # if Created is true (Means Data Inserted) if created: # Check the user_type and insert the data in respective tables if instance.is_driver: Driver.objects.create( driver_user=instance, full_name = "123", phone_number = "123", email = "", address = "123", country = "123", state = "123", city = "123", zipp … -
ERROR: Invalid Token. Expected stringEnd but found tag start "{%" instead
I've been getting this error message for a while now, but actually the code works fine and runs as expected, the line causing the error is this: templates/users/dashboard.html-> <link rel="stylesheet" href="{% static 'css/dashboard.css' %}"> when i remove the quotations i get a deferent error: <link rel="stylesheet" href={% static 'css/dashboard.css' %}> ERROR: Invalid Token. Expected stringStart but found tag start "{%" instead. when i completely remove the line i get the same erro on the first tag with href: <a href="{% url 'login' %}">Logout</a> ERROR: Invalid Token. Expected stringEnd but found tag start "{%" instead. i suspect that its a vscode issue, because the code runs flawlessly, and it only catches the error when i clean the code(format), so as long as i open vscode and never hit (ctrl+shidt+f) i dont get the error message, is there a solution for this? -
Django/Python Libraries for Reporting
Python is a popular tool for all kind of great candidate for reporting tasks. I found 2 Django/Python Libraries for Reporting are : reportlab and pyreportjasper. Could you tell me the advantages and disadvantages of each, so that I could be able to pick the right library ? -
Update data in html without reloading the page
I have a dictionary with questions and answers. What I would like to do is send one question at a time. On the web page I have a div grouping the question and the answers. I would like only this part to update without reloading the page. There is also a submit button When the user presses the button data is sent to the views.py then the view sends the following question. I tried to do this but there is no update in html with the following question urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('quizz', views.initQuiz, name="quizz"), re_path(r'^nextQuestion$', views.nextQuestion, name='nextQ') ] views.py def initQuiz(request): #with open("testjson.json") as f: data = json.load(f) data = [{"question": "q1", "responses": ["rep1", "rep2", "rep3"]}, {"question": "q2", "responses": ["rep1", "rep2", "rep3", "rep4"]}] request.session['data'] = data request.session['numQuestion'] = 0 return nextQuestion(request) def nextQuestion(request): if request.method == "POST": request.session['numQuestion'] = request.session.get('numQuestion') + 1 data = request.session.get('data') numQuestion = request.session.get('numQuestion') numResponse = list(range(1, len(data[numQuestion]["responses"])+1)) return render(request, 'quizz.html', context={"question" : data[numQuestion]["question"], "responses": zip(data[numQuestion]["responses"], numResponse)} quiz.html <div class="container-quiz"> <p class="question"> {{question}} </p> <div class="listReponse"> <div class="reponses"> {% for rep in responses%} <input name={{rep.1}} type="checkbox" class="reponse"> <label for={{rep.1}}>{{rep.0}}</label> {% endfor %} </div> </div> </div> <form … -
Django Single Field Validation cleaned_data
I am new in django and I am learning validation topics. Now I have a question about Single Field Validation and cleaned_data dictionary.I run django 3.2. In my model.py there is this table: class Personen(models.Model): DEUTSCHLAND = 'DE' SCHWEIZ = "CH" ÖSTERREICH = "AT" ENGLAND = "UK" NATION_CHOICES = [ (DEUTSCHLAND, "Deutschland"), (SCHWEIZ, "Schweiz"), (ÖSTERREICH, "Österreich"), (ENGLAND, "England"), ] vorname = models.CharField(max_length=200) nachname = models.CharField(max_length=200) username = models.CharField(max_length=200) stadt = models.CharField(max_length=15, validators=[ validate_nation_regexval], null=True) nationalität = models.CharField( max_length=2, choices=NATION_CHOICES, default=DEUTSCHLAND) biere = models.ManyToManyField("Bier", through="PersonenBier") def __str__(self): return self.username I import this in forms.py and I want to validate the field 'username'. So I created a single field validation in forms.py class PersonenForm(ModelForm): class Meta: model = Personen fields = '__all__' def clean_username(self): print(self.cleaned_data) username_passed = self.cleaned_data["username"] username_req = "user_" if not username_req in username_passed: raise ValidationError("Ungültig") return username_passed So far everything works, but I am confused, as I expected, that the cleaned_data dict only includes the 'username' field. Why are there are also the 'vorname' and 'nachname' keys in the dict? console output cleaned_data dict Thank you for info. -
How to resolve a field path (as passed to the QuerySet.filter method) to the target field in django?
How to resolve a field path like (document__owner__name__contains), as it would be passed to .filter(), to its target field (which here is document.owner.name here) ? -
Is there A Way To Format Serialized Response for Groups and their Permissions in Django Rest Framework?
I created an API endpoint in which I am sending a JSON data. to create a group and then assigned permission to the models (e.g add_user, change_user etc) programmatically. It works fine. The issue now is that I will like to format data retrieved in the same format I sent it in This is for the Django's inbuilt Group, Permissions, ContentType View.py class RolePermissionListCreateAPIView(generics.ListCreateAPIView): queryset = Group.objects.all() serializer_class = RolePermissionSerializer permission_classes = (IsAuthenticated,) def list(self, request): if not request.user.has_perm("auth.view_group"): return Response({"error":"Permission denied."}, status=status.HTTP_401_UNAUTHORIZED) queryset = self.get_queryset() serializer = RolePermissionSerializer(queryset, many=True) return Response(serializer.data) Serializer.py class PermissionSerializer(serializers.ModelSerializer): codename = serializers.CharField(allow_blank=False) class Meta: model = Permission fields ="__all__" class RolePermissionSerializer(serializers.ModelSerializer): name = CharField(max_length=100) permissions = PermissionSerializer(many=True) class Meta: model = Group fields = ["id", "name", "permissions"] Data [ { "id": 1, "name": "Administrator", "permissions": [ { "codename": "add_user" }, { "codename": "change_user" }, { "codename": "deactivate_user" }, { "codename": "delete_user" }, { "codename": "export_user" }, { "codename": "import_user" }, { "codename": "print_user" }, { "codename": "view_user" } ] } ] This actually the way I want the data to be formatted: { "role_name": "Administrator", "modules": [ { "module_name": "User", "can_view": "True", "can_add": "True", "can_edit": "True", "can_delete": "True", "can_print": "True", "can_deactivate": "True", "can_import": "True", … -
Django: How passing parameters from (forms.py) to (views.py)
Please, how i can pass parameters from: forms.py " class InscriptionForm(forms.ModelForm): " to views.py " def inscription(request): " thank you very much in the views.py i put just from .forms import * -
Custom Admin Page with Fields as Objects
I have 3 models: Category, SubCategory, Product. Category and SubCategory have one-to-many relationship. SubCategory and Product have many-to-many relationship(ManyToManyField is in Product). Currently, admin page for Product shows one field for SubCategory as multiple choice field. But I want fields for Product to be as Category objects. SubCategories should be divided by their Categories and user should be able to choose a SubCategory from each of this field. Can't work it out. Thanks in advance! models.py: class Category(models.Model): name = models.CharField(max_length=150, unique=True) created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=150, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='subcategories') created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=150, blank=True) description = models.TextField(blank=True) price = models.IntegerField(default=-1) quantity = models.IntegerField(default=-1) image = models.ImageField(blank=True) created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) discount = models.ForeignKey(Discount, on_delete=models.PROTECT, blank=True) subcategory = models.ManyToManyField(SubCategory) class Meta: ordering = ('-created_at',) def __str__(self): return self.name