Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango forms : Invalid choice error when saving form input to database
I do have an invalid choice error when trying to save value from my django form to my database. Here is the details : I do have a model with multiples choices for the value class ActivityType(models.Model): CHOICES = ( ('Randonnée', 'Randonnée'), ('Raquettes', 'Raquettes'), ('VTT', 'VTT'), ('Via ferrata', 'Via ferrata'), } Then , another model contain the previous one as foreign key : class TopoUnit (models.Model): activity_type = models.ForeignKey(ActivityType, on_delete=models.CASCADE, null=True) I defined a form to fufill this model : class TopoUnitForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['activity_type'].choices = ActivityType.CHOICES class Meta: model = TopoUnit fields = '__all__' On the HTML template, I'm displaying the form <div class="form-group"> <label>Activité</label> {{ form.activity_type }} </div> Finnaly,here is my view : def returnPage(request): #Called when the form is clicked form = TopoUnitForm() #Instanciate the form if (request.method == 'POST') : print(request.POST) #Print in CLI form = TopoUnitForm(request.POST) #Some var wihch can be used in the html {{form}} if form.is_valid(): print("saving") form.save() #save in the database else : print('\n' + str(form.errors)) context = {'form' : form } return render(request, 'guidebook.html', context) Unfortunatley, when pressing the button with an option selected in the form options list, the form_is_valid() return false. I Obtain the following … -
How to give a client a JWT while a redirection?
I'm working on a web app in django, and I'm facing a problem in implementing a JWT authentication. I have a django application which is responsible for user management and therefore authentication. So when I authenticate a user in my view, I have to redirect him to the home page which is in another django application. But here is the problem, when I authenticate a user, I create a JWT and pass it to the response so that the client of the user can store it, but it seems that when redirecting, the client cannot store the JWT. Here is the view that authenticate the users : def loginUser(request: HttpRequest): """ Request : URL : /user/loginUser/ Method : POST Content-type : application/x-www-form-urlencoded Required informations : -username -password Response : Status : 302 Redirect url : /home """ if request.method != "POST": return JsonResponse( data={"error":"Bad request method."}, hearders={"Allow":"POST"}, status=405, ) try: username = request.POST["username"] password = request.POST["password"] except KeyError: return redirect("/user/loginPage/?error=Missing informations") user = authenticate(username=username, password=password) if user != None: exp = datetime.datetime.now() + datetime.timedelta(hours=3) exp = int(exp.timestamp()) payload = { "user_id":user.id, "username":user.username, "exp":exp } token = jwt.encode(payload=payload, key=JWT_KEY) response = HttpResponse(status=302) response["Location"] = "/home" response["Authorization"] = "Bearer "+str(token) return response … -
jQuery is not return output in console
{% extends 'shop/basic.html' %} {% load static %} {% block css %} .col-md-3 { display: inline-block; margin-left: -4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img { width: 227px; max-height: 242px; } body .carousel-indicator li { background-color: blue; } body .carousel-indicators { bottom: 0; } body .carousel-control-prev-icon, body .carousel-control-next-icon { background-color: blue; } .carousel-control-prev, .carousel-control-next { top: 0; bottom: 0; } body .no-padding { padding-left: 0; padding-right: 0; } {% endblock %} {% block body %} <div class="container"> <!-- First Carousel --> {% for product, range, nSlides in allProds %} <h3 class="my-4">Flash Sale On {{ product.0.category }} - Recommended Items</h3> <div id="demo{{ forloop.counter }}" class="carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo{{ forloop.counter }}" data-slide-to="0" class="active"></li> {% for i in range %} <li data-target="#demo{{ forloop.parentloop.counter }}" data-slide-to="{{ i }}"></li> {% endfor %} </ul> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{ product.0.image }}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.0.product_name }}</h5> <p class="card-text">{{ product.0.desc }}</p> <button id="pr{{ product.0.id }}" class="btn btn-primary cart">Add To Cart</button> </div> </div> </div> {% for i in product|slice:"1:"%} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{ i.image }}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ … -
URL patterns are all the same but I get an error on one that makes no sense
I have an Django Rest Framework API and the URLs are setup the following way: There is a folder called api and inside that api folder I have two other folders: urls and views In the urls folder I have a init.py file that looks like this: from .users import urlpatterns_users from .mail import urlpatterns_mail from .notifications import urlpatterns_notifications urlpatterns = ( urlpatterns_users + urlpatterns_mail + urlpatterns_notifications ) and in the views folder a init.py file that looks like this: from .mail import * from .notifications import * from .users import * The mail.py file inside the urls folder looks like this: from django.urls import path, include from api.views import * urlpatterns_mail = [ path("mail/c/", CreateMail.as_view()), path("mail/<int:user>/sent/", GetSent.as_view()), path("mail/<int:user>/received/", GetReceived.as_view()), path("mail/<int:user>/trashed/", GetUserTrashed.as_view()), path("mail/<int:pk>/d/", TrashMail.as_view()), ] and the notifications.py file in the urls file looks like this: from django.urls import path, include from api.views import * urlpatterns_notifications = [ path("notifications/c/", CreateNotification.as_view()), ] The mail.py file in the views folder looks like this: from rest_framework import generics from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from mail.serializers import * from django.db.models import Q, Max from django.contrib.auth import get_user_model from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_201_CREATED, HTTP_404_NOT_FOUND, HTTP_202_ACCEPTED, HTTP_200_OK, … -
Testing with pytest-django: Formset is not valid
I'm using pytest-django for testing my django project. Here is my code. The error is on the 345th line. Since the formset is not valid, it redirect me to "make_order/" and not to "reverse('myapp:order_success')". Do you know what is the problem and how can I resolve it? Thanks! -
Celery + Redis + Django task not running
I have a django website and recently based on this tutorial have installed celery, redis and configured files. HAve deployed the project on digitalocean server. Now issue I am facing is that whenever .delay() is called, task is not getting executed. But when I use below command in project folder, task is discovered and executed. python -m celery -A django_celery worker -l info What should I do so that every time a user calls function, celery automatically discoveres task and execute it? -
Django html issuce unable to click hyperlink
i created a Djange, There are .html file in my templates. i just dont know why when clink this link the website no any respone. But if i open this html without django the link is work <a href="file://\\HKCT-OFFS-01\Data\Information Technology\Documents\Contract">useful link </a> anyone have any idea? T^T <a href="https://www.timeanddate.com/worldclock/hong-kong/hong-kong">website</a> i tried this is work <a href="file://\\HKCT-OFFS-01\Data\Information Technology\Documents\Contract">useful link </a> but fail to open share folder FYI\\HKCT-OFFS-01\Data\Information Technology\Documents\Contract This is a workable path. -
Handling different actions based on click event and search in Django plotly dash
I am working on Django plotly dash app and have some callback functions that are triggered when two input elements sidebar-graph (it is a bar chart) and search-top2vec-input (it is a search box) receive updates. The callback function, update_charts_word_graph_app2, has the following signature: def _register_app2_callbacks(self): @self.app2.callback( [ Output("sidebar-content", "children"), Output("network-graph-chart", "children"), Output("graph-title-text", "children"), Output("word-cloud-title-text", "children"), Output("top-10-urls-title-text", "children"), Output("word-cloud-graph", "children"), Output("top-10-urls-graph", "children"), Output("search-error-message", "children"), Output("ls-loading-output-top2vec", "children"), ], [ Input("sidebar-graph", "clickData"), Input("search-top2vec-input", "value"), ], ) def update_charts_word_graph_app2(click_data, search_value): return self._update_charts_word_graph(click_data, search_value) # Return all outputs The issue I'm facing is that when I click on the bar chart, the click_data is not None anymore and then I try to perform a search, the search functionality doesn't work as expected because the click event data is still present. Here's the relevant part of the code: def _update_charts_word_graph(self, click_data=None, search_value=None): """ update the word graphs and related components based on clicke data or search value. Args: click_data (dict, optional): Click data from the graph. Defaults to None. search_value (str, optional): Search value from the input. Defaults to None. Returns: List: List of components to be updated """ object_graph = Graph() if click_data is not None: print("." * 20) print("click") print(click_data) print(search_value) print("." * 20) … -
How to connect Django to AWS RDS
I was following a Django tutorial but now I can't connect to the database. My settings.py file looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'masteruser', 'PASSWORD': 'passKode', 'HOST': 'w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com', 'PORT': '5432' } } But when I run the command python manage.py migrate I get errors as shown below: Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 269, in get_new_connection connection = self.Database.connect(**conn_params) File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "w3-django-project.czmrkj1y3qxu.eu-west-2.rds.amazonaws.com" (172.31.11.179), port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/home/amen/Documents/PRJKTZ/PYTHON/W3Django/myworld/lib/python3.10/site-packages/django/core/management/base.py", line … -
Django Local Host works but hosting servers don't
I'm really new to programming. I had to make a web application with Django, so I made a weather app. It works fine if I run it locally with runserver but I tried various hosting websites and none work. This is my GitHub Repository. I hope anyone can help me. Various hosting websites. Want my application to work online but it doesn't. -
how to use EAV in django?
I want to use django_EAV 2 in my store project made by Django template to have different attribute for each product but i don't know how to use it and there were no tutorial in the web.can some body help me plz? -
*293 connect() failed (111:connection refused) while connecting to upstream, client 221.148.103.36, server;
when i try to test via postman, i get 502 bad gate error. so i explored docker at aws ec2 server(and conducted 'sudo docker logs {containerId}), and found this error sentence. [error] 20#20: *293 connect() failed (111: Connection refused) while connecting to upstream, client 221.148.103.36, server. is there anyone how to fix this error? maybe, i think its because of nginx.conf file problem. upstream django_rest_framework_17th { server web:8000; } server { listen 80; location / { proxy_pass http://django_rest_framework_17th; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/static/; } location /media/ { alias /home/app/web/media/; } } this is my nginx.conf file. plus, i'm doing project with django, pycharm. -
Place items in the same row in Bootstrap
I have a problem with the following code. There are two forms after each other: searchform and booksform. I want to put the searchform and the first button of the booksform in the same row with Bootstrap. {% include 'header.html' %} {% load static %} <section class="bg-light px-5 py-4"> <div class="row mb-4"> <div class="col-6"><h2 class="h2">Könyvek</h2></div> </div> <form id="searchform" onSubmit="return false;"> <div class="row"> <div class="col-3"><input type="text" class="form-control" id="searchbar"></div> <div class="col-2"><input type="button" value="Keresés" class="btn btn-outline-secondary" id="search"></div> </div> </form> <form action="{% url 'books' %}" method="post" id="booksform" name="booksform"> {% csrf_token %} <div class="col-7 text-end"><input type="button" class="btn btn-primary me-3" value="Mentés" id="save" name="save"></div> <table class="table table-light table-hover"> <thead> <th>Angol cím</th> <th>Magyar cím</th> <th class="text-center">Olvastam</th> </thead> <tbody id="tbody"> {% for i in books %} <tr> <td>{{i.eng_title}}</td> <td>{{i.title}}</td> <td class="text-center"><input type="checkbox" name="check-{{i.id}}" id="check-{{i.id}}" class="form-check-input"></td> </tr> {% endfor %} </tbody> </table> <input type="hidden" name="checked" id="checked"> </form> </section> <script src="{% static 'js/books.js' %}" defer data-tocheck="{{books_read}}" data-books="{{booksjson}}"></script> {% include "footer.html" %} I tried to put <div class="row> before the searchform and </div> after the save button in booksform. It didn't work because I opened the div before the booksform and I closed it inside of that. Thank you for your answers. -
foreign key brings all fields, I only want foreignkey.name Django
from django.db import models from vendors.models import Vendor # Create your models here. class Product(models.Model): name = models.CharField(max_length=50, verbose_name= ('Product Name')) description = models.CharField(max_length=50, verbose_name= ('Description')) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) cost_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= ('Cost Price')) selling_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= ('Selling Price')) quantity = models.IntegerField(default=0) def __str__(self): return f"Name: {self.name}, Description: {self.description}, Vendor: {self.vendor}, Cost Price: {self.cost_price}, Selling Price: {self.selling_price}, Quantity: {self.quantity}" above is my models.py below is my forms.py class ProductForm(forms.ModelForm): vendor = forms.ModelChoiceField(queryset=Vendor.objects.only('name')) class Meta: model = Product fields = ['name', 'description', 'vendor', 'cost_price', 'selling_price', 'quantity'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['vendor'].queryset = Vendor.objects.only('name') self.fields['vendor'].empty_label = 'Select a vendor' for field_name in self.fields: if field_name != 'vendor': self.fields[field_name].widget.attrs.update({'value': ''}) def label_from_instance(self, obj): return obj.name when loading the purchaseform, I need the vendor field to populate only the name of vendor, now it's populating all fields of vendors_vendor table. Please guide me. -
Managing Inactive SQS Queues in Django with Celery on AWS ECS
I have Django app where I am using SQS and celery. Everything is hosted on ECS where I have 3 services: django-api, celery-beat and celery-worker. I have enabled autoscaling policy on celery-worker service that is creating containers/task based on number of MessagesVisible on SQS, by default there are 0 containers in this service. The problem is that after 6 hours my alarms and SQS are becomming inactive and I need to wait 10-15 minutes to run first celery during a day. It seems that this is some kind of optimization done automatically by AWS. You can read more about that here: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-monitoring-using-cloudwatch.html I was thinking to send empty message to SQS every hour to avoid going to inactive but I don't want to create periodic task because that will trigger my alarm and it will create new container on celery-worker service to perform this task and that will cost me money. The question is what is the most efficient way to handle this issue without using celery worker? Is there any way to directly send empty message to SQS from Django every hour? Any help would be appreciated. -
Creating user and user profile with one request which has nested JSON body in Django rest framework
I want to make api to create user and disease instance. accounts/serializers.py: class MyUserSerializer(serializers.ModelSerializer): user_disease = DiseaseSerializer(many=False, read_only=False) class Meta: model = MyUser fields = '__all__' def create(self, validated_data): print("validated_data : ", validated_data) user = MyUser.objects.create(**validated_data) # disease_data = validated_data['disease'] # disease = Disease.objects.create(user, **disease_data) return user accounts/views.py: class SignUpAPIView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = MyUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() # After validation about user, generate token pair token = TokenObtainPairSerializer.get_token(user) refresh_token = str(token) access_token = str(token.access_token) res = Response( { "user": serializer.data, "message": "sign_up success", "token": { "access": access_token, "refresh": refresh_token } }, status=status.HTTP_201_CREATED ) # Store JWT token in cookie res.set_cookie("access", access_token, httponly=True) res.set_cookie("refresh", refresh_token, httponly=True) return res else: print("is_valid() is false!") return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def perform_create(self, serializer): serializer.save(user=self.request.user) when I'm trying to send with POST method, This is a JSON Content: { "identifier": "test1", "password": "test1", "username": "username1", "email": "test1@naver.com", "birth": "19960314", "gender": true, "isForeigner": false, "height": 169, "weight": 60, "pw_queiston_idx": 0, "pw_answer": "test_answer", "disease": { "arrhythmia": true } } And its response : Status: 400 Bad Request Size: 44 Bytes Time: 15 ms { "user_disease": [ "This field is required." ] } What I want to do Making api to create User … -
How to create a store with Django and Python that can handle millions of products?
Suppose I want to create a store with Django and Python. In each store, there are some products with a title, an amount of inventory, and some common features. However, there are some unique features for each product. For example, the features of a refrigerator are different from those of a dishwasher. It is not correct to define a separate model for each type of product when we may have millions of products like Amazon. What solution do you suggest for this problem? -
How can I ensure that user registration data is stored in both the 'Register' and 'Login' tables in my database?
Why is the user registration data only being stored in the 'Register' table and not in the 'Login' table in my Django application with MySQL? How can I modify my code to ensure that the registration data is stored in both tables when a user registers? I have separate tables for registration and login, where the 'Register' table contains columns such as 'Ent_ID', 'Username', 'Email_ID', and 'Password', and the 'Login' table contains columns such as 'Login_ID', 'Ent_ID' (foreign key referencing 'Register' table), 'Email_ID', and 'Password'. Any insights or suggestions on how to resolve this issue would be greatly appreciated. Thank you! I have created two tables in my Django application, 'Register' and 'Login', for user registration and login functionality respectively. The 'Register' table has columns like 'Ent_ID', 'Username', 'Email_ID', and 'Password', while the 'Login' table has columns like 'Login_ID', 'Ent_ID' (foreign key referencing 'Register' table), 'Email_ID', and 'Password'. When a user registers, I expected their registration data to be stored in both the 'Register' and 'Login' tables. However, only the data is being stored in the 'Register' table and not in the 'Login' table. As a result, I am unable to perform login functionality using the registered credentials. I have … -
I am getting an error in django saying it might be an issue with circular import but I am not sure how to fix. I think my code is correct
I am very new to coding so I will explain what I did step by step. I created a virtual environment in command prompt and then I installed django in that. Then, I opened the project in vs code and activated the new environment in the terminal. I then create calc by running the command: python manage.py startapp calc This my urls.py file in calc: ** from django.urls import path from . import views #from all import views urlpatterns = [ #setting up the mapping path('',views.home,name='home') #homepage can be represented by '' or '/' ]** and this is my views.py file: ** from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("Hello world")** and my project url.py file: **from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ]** but when i run the command - python manage.py runserver I am getting this error: File "C:\Users\maya\env1\Lib\site-packages\django\urls\resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'calc.urls' from 'C:\Users\maya\myprojects\firstproject\calc\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. … -
jQuery is not giving output in console
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script> <script> localStorage.setItem('cart', JSON.stringify({})) if (localStorage.getItem('cart') == null) { let cart = {} console.log('Running properly....') } else { cart = JSON.parse(localStorage.getItem('cart')) } buttons = document.querySelectorAll('.cart') for (let button of buttons) { button.addEventListener('click', () => { if (cart[button.id] != undefined) { cart[button.id] += 1 } else { cart[button.id] = 1 } localStorage.setItem('cart', JSON.stringify(cart)) console.log(cart) }) } </script> I was building a ecom platform in Django so I wanted to make a function that whenever I click on my add to cart button the console will return the product number. That is why I wrote this jQuery at the very end of my index.html file but it's not working. Should I download jQuery for this? Because CDN is not working on my computer. -
Are there any functions to get only the language used to display browser UI in Django?
I set 3 languages on Google Chrome, then I set the 2nd language English for displaying the Google Chrome UI as shown below: Then, with request.META['HTTP_ACCEPT_LANGUAGE'], I tried to get only the 2nd language English used to display the Google Chrome UI because for users, I want to show my website in their languages used to display their browser UI by translation when they visit my website but I got all the languages set in Google Chrome as shown below: # "views.py" from django.http import HttpResponse def test(request): print(request.META['HTTP_ACCEPT_LANGUAGE']) # fr,en;q=0.9,ja;q=0.8 return HttpResponse("Test") So, are there any functions to get only the 2nd language English used to display the Google Chrome UI? -
How to change the default cookie name `django_language` set by `set_language()` in Django?
I could set and use set_language() as shown below: # "core/urls.py" ... urlpatterns += [ path("i18n/", include("django.conf.urls.i18n")) # Here ] Now, I want to change the default cookie name django_language below considering the security because users can easily know that Django is used for the website: So, how can I change the default cookie name django_language? -
Django: psycopg2: Could not translate host name to address: Name or service not known
I am attempting to connect to a PostgreSQL DB using psycopg2 and a django app. The pods running the application report the following error: 127.0.0.1 - - [13/Jul/2023:17:35:05 -0500] "GET /read HTTP/1.1" 301 0 "-" "PostmanRuntime/7.32.3" An error occurred while processing the GET request: could not translate host name "resume-postgresql-primary-hl " to address: Name or service not known Internal Server Error: /read/ When I run it on localhost, it works (connects to the DB and returns the data) Nslookup from the pods is also working: root@resume-backend-677cd68846-m22h8:/srv/app# nslookup resume-postgresql-primary-hl Server: 10.96.0.10 Address: 10.96.0.10#53 Name: resume-postgresql-primary-hl.resume.svc.cluster.local Address: 10.244.0.114 I can't figure out what is going on. Any ideas? -
How to include all fields from foreign key in django model form
I am trying to access the fields related to a foreign key from a model form. I have read the docs and it seems I should be able to access these fields with dot notation. Does what I am attempting make sense? Is there a better way to do this same thing. html form {% csrf_token %} {{ form.room.room_available }} {{ form.renter }} <input type="submit" value="Submit"> </form> Models.py class Room(models.Model): roomNum = models.CharField(max_length=20) room_is_premium = models.BooleanField(default=False) room_available = models.BooleanField(default=False) class BookedRoom(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True) renter = models.CharField(max_length=200) start = models.BooleanField(default=True) end = models.BooleanField(default=True) Views.py def bookRoomNow(request, pk): room = get_object_or_404(Room, pk=pk) if request.method == "POST": form = BookingForm(request.POST or None) if form.is_valid(): form = form.save(commit=False) #this room.instance form.room = room form.save() return redirect('room_details', pk=room.pk) else: form = BookingForm() context= {"form":form} return render(request, 'booker/booking_form.html', context) -
How do resolve error 400 in this case with method POST of Django Rest Framework when I create join method
I am redoing a course on DRFI want to post user, group with join method but I got error 400 when I post this to becoming member. The views, the models and the serializers are below. #Views.py ``` class MemberViewSet(ModelViewSet): queryset = Member.objects.all() serializer_class = MemberSerializer @action(detail=False, methods=['post']) def join(self, request): if 'group' in request.data and 'user' in request.data: try: group = Group.objects.get(id=request.data['group']) user = User.objects.get(id=request.data['user']) member = Member.objects.create(user=user, group=group, admin=False) serializer = MemberSerializer(member, many=False) reponse = {'message': 'Joined group', 'results': serializer.data} return Response(response, status=status.HTTP_200_OK) except: response = {'message': 'Cannot join'} return Response(response, status=status.HTTP_400_BAD_REQUEST) else: response = {'message': 'Wrong params'} return Response(response, status=status.HTTP_400_BAD_REQUEST)``` #models.py ``` from django.db import models, transaction from django.contrib.auth.models import User # Create your models here. class Group(models.Model): name = models.CharField(max_length=50, null=False, unique=False) location = models.CharField(max_length=50, null=False) description = models.CharField(max_length=250, null=False, unique=False) active = models.BooleanField(default=True) class Meta: unique_together=(('name', 'location')) def __str__(self): return self.name @transaction.atomic def disable(self): if self.active is False: return self.active = False self.save() self.events.update(active=False) class Event(models.Model): name = models.CharField(max_length=25, default='Match') team1 = models.CharField(max_length=32, blank=False) team2 = models.CharField(max_length=32, blank=False) time = models.DateTimeField(null=False, blank=False) score1 = models.IntegerField(null=True, blank=True) score2 = models.IntegerField(null=True, blank=True) group = models.ForeignKey(Group, related_name='events', on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.name class Member(models.Model): group …