Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set cachecontrol for different types of image differently without overriding get_object_parameters using django-storages
I have multiple apps and each app has different cachecontrol requirement. get_object_parameters provides us. But it will be big change for codebase. Instead is it possible to pass cachecontrol to constructor e.g S3Boto3Storage(**options = { 'bucket_name': 'abc', 'querystring_expire': 172800, 'cachecontro': 'max-age=12000', 'location': 'LINTING', }) Right now its not working need to add this functionality in package. -
Value error at /register/ Fernet key must be 32 url-safe base64-encoded bytes
I am trying to encode the payload data of a form I created using react from frontend using the code below const handleSubmit = (e) => { e.preventDefault(); const encryptedPassword = CryptoJS.AES.encrypt( formData.password, "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" ).toString(); const encryptedPassword2 = CryptoJS.AES.encrypt( formData.password2, "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" ).toString(); const encryptedEmail = CryptoJS.AES.encrypt( formData.email, "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" ).toString(); const encryptedPayload = { ...formData, password: encryptedPassword, password2: encryptedPassword2, email: encryptedEmail, }; // Send the encrypted payload to the backend axios .post("http://127.0.0.1:8003/register/", encryptedPayload) .then((response) => { // Handle successful response console.log(response.data); }) .catch((error) => { // Handle error console.error(error); }); }; So whenever I submit the form, the view function below is what I used to decrypt the payload and save it to the database. class CreateUser(APIView): permission_classes = [AllowAny] def post(self, request): encrypted_password = request.data.get("password") encrypted_password2 = request.data.get("password2") encrypted_email = request.data.get("email") encryption_secret_key = "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" cipher_suite = Fernet(encryption_secret_key) decrypted_password = cipher_suite.decrypt( encrypted_password.encode()).decode() decrypted_password2 = cipher_suite.decrypt( encrypted_password2.encode()).decode() decrypted_email = cipher_suite.decrypt( encrypted_email.encode()).decode() # Update the request data with the decrypted password request.data["password"] = decrypted_password request.data["pasword2"] = decrypted_password2 request.data["email"] = decrypted_email serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.email = user.email.lower() user.username = user.email.lower() if user.email else None user.first_name = user.first_name.lower() if user.first_name else None user.last_name = user.last_name.lower() if user.last_name else None user.avatar … -
Images fetched with axios not found in react/django
Am having problems using axios to fetch data containing images and strings from django backend. It just shows this error in my browser console: gig2_sWgfG4m.png:1 GET http://localhost:5173/media/gig2_sWgfG4m.png 404 (Not Found) I have tried different configurations but still didn't get a positive response. Here is my code: CARD.JSX import axios from "axios" import { useEffect, useState } from "react" const baseURL = 'http://127.0.0.1:8000/BlogHost' export const Card = () => { const [posts, setPosts] = useState([]) useEffect(() => { axios.get(baseURL) .then((response) => { setPosts(response.data); }) .catch(error => { console.error('An error occured while fetching data from backend', error) }) }, []) if (!posts) return null; return ( <div className="bg-gray-400"> <div className="mx-auto min-w-fit px-4 sm:px-6 lg:px-8"> <div className="mx-auto max-w-2xl py-16 sm:py-24 lg:max-w-none lg:py-32"> <div className="mt-6 space-y-12 gap-y-6 gap-x-3 grid grid-cols-1 md:grid md:grid-cols-2 md:space-y-0 lg:grid lg:grid-cols-4 lg:space-y-0"> {posts.map((post) => ( <div key={post.title} className="group relative"> <div className="relative h-80 w-full overflow-hidden rounded-lg bg-white sm:aspect-h-1 sm:aspect-w-2 lg:aspect-h-1 lg:aspect-w-1 group-hover:opacity-75 sm:h-64"> <img src={post.image} alt={post.title} className="h-full w-full object-cover object-center" /> </div> <h3 className="mt-6 text-sm md:text-base lg:text-lg text-gray-800"> <a href='{post.href}'> <span className="absolute inset-0" /> {post.category} </a> </h3> <p className="text-base md:text-xl lg:text-2xl font-semibold text-gray-900">{post.body}</p> </div> ))} </div> </div> </div> </div> ) } BACKEND VIEWS.PY from .models import Blog from .serializer import BlogSerializer … -
How do I integrate xAPI or cmi5 in my Django application?
I have all the user's activity data like course completion data, course topic completion data, time spent on each topic and course, assessment data in MySQL database. But, I couldn't find the documentation/tutorial on integrating cmi5 (with/without xAPI) into Learning Management System platform built using Django web-framework. So, far I have learned a little about the cmi5 from the below links, https://risc-inc.com/cmi5-overview-process-flow/ https://xapi.com/cmi5/cmi5-technical-101/ -
Download CSV using AJAX in Django - saved file contains the view content instead of the csv content
I'm dynamically generating a CSV from some content, and want to provide a message to the user and then download the file. When using Javascript, the file that's downloaded is the HTML of the view, and not the CSV. If I remove the javascript, the CSV is downloaded, but then there is no indication of this to the user. How can I get the CSV when using javascript? One thing I note is that I see a GET after the POST in my Django application log when using the javascript script. I am following https://docs.djangoproject.com/en/4.2/howto/outputting-csv/ to generate the csv content, and got the javascript from the answer in Django cannot download docx file in ajax This view content works when used without the javascript components - a csv file is downloaded. def csv_report(request): if request.method == "POST": report_dates_form = AllMemberseventForm(request.POST) if report_dates_form.is_valid(): start_date = report_dates_form.cleaned_data.get("start_date") end_date = report_dates_form.cleaned_data.get("end_date") events = Events.objects.filter(event_date__range=[start_date, end_date]).order_by("event_date") if events and len(events) > 0: response = HttpResponse( content_type="text/csv", headers={ "Content-Disposition": 'attachment; filename="%s"' % filename, "filename": filename, "event_count": len(events), }, ) writer = csv.writer(response) for event in events: writer.writerow( [event.thing, event.otherthing, event.event_date] ) return response My javascript in the template that the view uses is as follows. … -
Django + Mongo + djongo. Trouble with adding new models with ForeignKey
i use django + mongo with djongo. I have 2 models: Deck and Card; class Deck(models.Model): deckName = models.TextField(max_length=100) deckDetail = models.TextField(max_length=1400) class Card(models.Model): cardName = models.TextField(max_length=100) cardDetail = models.TextField(max_length=1400) deckCard = models.ForeignKey(Deck, on_delete=models.CASCADE) dailyCard = models.BooleanField(default=False, unique=True) when i add new Deck model with http://127.0.0.1:8000/admin/app/deck/add/ (django admin standart) it's ok. But when i add new Card model i have "Exception Type: DatabaseError at /admin/app/card/add/ Exception Value: " ; in py manage.py shell i create 2 new models (card, deck) and it's ok! I think the point is that when saving the Card, the string (id) is passed to the deck field, but do you need int? Or something like that? Do I really have to make my own admin page and override the methods for saving models there? -
Django Model Queryset Calculation
For example class Rice(models.Model): quantity = models.DecimalField(...) Lets say: rices = Rice.objects.all() for i in rices: i.quantity This gives output as : 5 7 9 10 Now what i want to achieve is a total_quantity till that object is reached what my desired output should be : 5 12 21 31 Logic: First object total_quantity till that object is calculated is 0+5 then, next object total_quantity is 0+5+7 then 0+5+7+9 and so on. And this should be done using (queryset) annotate/aggregate or any other db models functions. (If not possible then any other way) If the order changes the the output should also change. -
How does has_module_permission work with inline models in django admin
While there are other ModelAdmin methods that can be used to hide inlines, it's noted here that the InlineModelAdmin also shares the has_module_permission feature with ModelAdmin. It works perfectly on ModelAdmin objects as described in the docs but I don't seem to understand how it works or is supposed to work for InlineModelAdmin objects. class HideModuleAdmin(admin.ModelAdmin): def has_module_permission(self, request): if condition: # This works as expected. Hides it from the menu items return False return super().has_module_permission(request class HideTabularInlineModelAdmin(admin.TabularInline): def has_module_permission(self, request): if condition: # This does not work as expected. The inline is visible places I don't expect to see it return False return super().has_module_permission(request I am simply inheriting the above where I need them e.g class SomeModelAdmin(HideModuleAdmin): pass class SomeTabularInline(HideTabularInlineModelAdmin): pass -
Using Cookiecutter Django Docker backup functions on a Windows machine
I have used Cookiecutter Django to create a dockerized project, which I have deployed to production. I can use the commands for backing up, checking backups, and restoring all fine on my production server, which is a linux machine. I was hoping to move the backup from my production environment to my development environment, which is a windows machine, however using the commands throws an issue "/usr/bin/env: ‘bash\r’: No such file or directory". I've searched around and seen this is a windows files encoding issue but can't find an answer which works for me for resolving that issue. Has anyone faced this issue before and found a workaround? Thanks for any help anyone can offer! -
Multiple Group by boolean fields with date interval
I have a table like this: User Record Date Online Alice 2023/05/01 Online Alice 2023/05/03 Online Alice 2023/05/15 Online Alice 2023/05/31 Offline Alice 2023/06/01 Offline Alice 2023/06/04 Offline Alice 2023/06/20 Online Alice 2023/06/21 Online And I would like to have a result like this: Alice was online from 2023/05/01 to 2023/05/15 Alice was offline from 2023/05/31 to 2023/06/04 Alice was online 2023/06/20 to 2023/06/21 I tried to use this query: _users = (MyUserModel.objects.filter(record_date__year=2023) .values('online', 'record_date') .annotate(min_date=Min('record_date'), max_date=Max('record_date')) .order_by() ) but it doesn't return a correct result -
How to solucionate the error to Upgrade project to Django 4.2.3
I have a Django project in the 3.1.2 version. However, I need upgrade it to a new version, to 4.2.3. I´m having the following message when I upgrade the project. How to solucionate this? "django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'apps.core.apps.CoreConfig.name' is correct. " In the 3.1.2 version, this works well. Follow the structure of the folders of the project: |.quality |.. apps |... core |... changelog |.. quality |... init.py |... asgi.py |... settings.py |... urls.py |... wsgi.py |.. static |.. templates |.. venv Follow the Installed_apps in the settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrapform', 'apps.core', 'apps.changelog', ] Thank you very much! -
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.