Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to serve a media file in Django?
I have a Django project where I'm trying to create a card with an image that was uploaded by the user. I keep getting a certain error but I have already done every solution and its still coming up. any help would be appreciated. the {{image}} variable isn't working html page <div class="p-5 mx-4 bg-white border-2 border-gray-300 grow"> <button><img src="{{image}}" alt=""></button> <h3>{{title}}</h3> <span>{{currentBid}}</span> <span>{{sellor}}</span> </div> settings MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')\ urls urlpatterns = [ path("", views.activeListings, name="activeListings"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("createListing", views.createListing, name="createListing"), path("listingPage/<str:title>", views.listingPage, name="listingPage"), path("wishlist", views.wishlist, name="wishlist"), path("catagory", views.catagory, name="catagory"), path("catagoryListing/<str:catagory>", views.catagoryListingsPage, name='catagoryActiveListingsPage'), path("catagoryListing/listingPage/<str:title>", views.listingPage, name="catagorylistingPage"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also have the media url pattern line in the urls for my whole project error 04 4334 Not Found: /Screen_Shot_2022-10-10_at_5.42.19_PM.png WARNING:django.request:Not Found: /Screen_Shot_2022-09-19_at_2.39.14_PM.png Not Found: /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png Not Found: /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png WARNING:django.request:Not Found: /Screen_Shot_2022-10-10_at_5.42.19_PM.png [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-09-19_at_2.38.33_PM.png HTTP/1.1" 404 4355 WARNING:django.request:Not Found: /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png Not Found: /temperature-anomaly_wlbvLbQ.png WARNING:django.request:Not Found: /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png [26/Oct/2022 12:01:48] "GET /Screen_Shot_2022-09-19_at_2.39.14_PM.png HTTP/1.1" 404 4334 WARNING:django.request:Not Found: /temperature-anomaly_wlbvLbQ.png [26/Oct/2022 12:01:48] "GET /Screen_Shot_2022-10-10_at_5.42.19_PM.png HTTP/1.1" 404 4334 [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png HTTP/1.1" 404 4355 [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png HTTP/1.1" 404 4355 [26/Oct/2022 12:01:48] "GET /temperature-anomaly_wlbvLbQ.png HTTP/1.1" 404 4307 debug is … -
Slug in Djnago URL
I want to create a directory like mysite.com/user after user get logged In. i.e mysite.com/john Here is the corresponding views and urlpatterns. But after authorization I only left with http://127.0.0.1:8000/authorization instead of http://127.0.0.1:8000/user ? models.py user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) project/urls.py urlpatterns = [ path('authorization/', include('authorization.urls')), ] authorization/app/urls.py urlpatterns = [ path('', views.index, name='index'), path('<slug:user>/', views.user_name, name='user_name'), # here path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] corresponding views.py for that user_name @login_required @twitter_login_required def user_name(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/home.html', {'user':user}) -
How to link to URL of related object in DRF
I’m making a music player with a DRF backend. I have two models, one is Song and the other is TrackQueue In the browser, the “nowplaying” instance of TrackQueue shows the meta of the queued song with a link to the file in its meta. What I need now is a url that always produces that instance of the “nowplaying” TrackQueue (id=1) What would that url be and how can I create it? Thank you models.py class Song(models.Model): title = models.CharField(max_length=24) file = models.FileField() def __str__(self): return self.title class TrackQueue(models.Model): title = models.CharField(max_length=64) is_song = models.OneToOneField(Song, on_delete=models.CASCADE) def __str__(self): return self.title Serializers.py from rest_framework import serializers from .models import Song, TrackQueue class SongSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Song fields = ('id' ,'title', 'file') class TrackQueueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TrackQueue fields = ('id' , 'title', 'is_song') views.py from django.shortcuts import render from .serializers import SongSerializer from rest_framework import viewsets from .models import Song, TrackQueue from music.serializers import SongSerializer, TrackQueueSerializer class SongView(viewsets.ModelViewSet): serializer_class = SongSerializer queryset = Song.objects.all() class TrackQueueView(viewsets.ModelViewSet): serializer_class = TrackQueueSerializer queryset = TrackQueue.objects.all() -
Django href link not routing to correct url
The links within my pages/templates/base.html which are used for a header template results in 404 error. The pages load correctly when manually written 'http://127.0.0.1:8000' 'http://127.0.0.1:8000/about/'. I am using class based views and following chapter 3 of Django for beginners (William Vincent). pages/templates/base.html: <header> <a href="{% url 'home' %">Home</a> | <a href="{% url 'about' %">About</a> </header> pages/urls.py: from django.urls import path from .views import HomePageView, AboutPageView urlpatterns = [ path("", HomePageView.as_view(), name="home"), path("about/", AboutPageView.as_view(), name="about"), ] portfolio/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("pages.urls")), ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] pages/views.py: from django.views.generic import TemplateView # Create your views here. from django.http import HttpResponse class HomePageView(TemplateView): template_name = 'home.html' class AboutPageView(TemplateView): template_name = "about.html" The error is as follows: Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin/ [name='home'] about/ [name='about'] The current path, about/{% url 'about' %, didn’t match any of these. Terminal error: Not Found: /{% url 'about' % [26/Oct/2022 11:40:02] "GET /%7B%%20url%20'about'%20% HTTP/1.1" 404 2497 I think the issue lies in pages/urls.py, as if click the 'home' link from 'http://127.0.0.1:8000/about/' the url is 'http://127.0.0.1:8000/about/%7B%%20url%20'home'%20%'. I've tried … -
Nth-child does not change colour for odd and even
This a Django project, in which I loop over folders and files. The background colour of each file should be different. For example, the odd ones should be purple and the even ones should be blue. But they are all shown as purple. Here is the file div from HTML: <div class="each_key">{{file}}</div> Here is the styling in CSS: .each_key:nth-child(odd){ text-align: left; width:197px; height:42px; background-color: purple; padding:10px; } .each_key:nth-child(even){ text-align: left; width:197px; height:42px; background-color: blue; padding:10px; } I've also tried "nth-of-type" and it still gives me purple instead of changing to purple and then blue. -
Django models - Custom jsonfield update method
So my intention is to be more effective when it comes to touching the database jsonfields in my postgres db. I could of course append the jsonfield data like so (both are lists with inner dicts): obj.jsonfield = new_data + old_data obj.update_fields(["jsonfield"]) but I wonder if there is a better way for doing so, because when I got this right, the database first removes old_data and afterward updates the field once again with the old_data. Is there a better way for me to just append to the old_data list in a custom update_fields method? If what do I need to consider there? Thanks a lot -
Need help for Creating Biometric Attendance web application using Django rest api
i'm very new to this it side coming from non-it, recently got placed as python developer through self learning. joined after my company asks me to develop the biometric attendance system for the internal purpose. can anyone guide me how to develop it, what are the model fields required, how should i integrate the device with my rest api application. somebody please help and guide me. i dont know where to start -
Hello everyone, please how do I call the constant messages that comes with a Validation Error into my program?
views.py I want each validation messages to be displayed in the home page according to the type of error message. for example: if the password input is too short, it should only display the password input when it redirects the user back to the home page. Thank you in advance! from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout #from django.contrib.auth.models import User from django.core.mail import send_mail from .models import User from django.contrib.auth.password_validation import validate_password,UserAttributeSimilarityValidator,CommonPasswordValidator,MinimumLengthValidator,NumericPasswordValidator from django.contrib.messages import constants as messages_constants MESSAGE_LEVEL = messages_constants.DEBUG # Create your views here. def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if password: try: new = validate_password(password,user=None,password_validators=None) except: messages.error(request, ) return redirect('home') -
Rpy2 Error in Django - Conversion 'py2rpy' not defined for objects of type '<class 'str'>
I have never used R before, and am trying to call an R function from python using rpy2. It works on a standalone python terminal, but not in Django. But rpy2 does not seem to be able to convert python strings to r objects. I am using a custom library given by a coworker and would like to know if the problem is on his side. Because I have seen other people on SO using the exact same method to run R functions from python. Here's the code from config import celery_app from rpy2.robjects.packages import importr from pathlib import Path import math base = importr("base") my_lib = importr("my_lib") @celery_app.task() def calculate_r_bindings(file_path): """ """ g = my_lib.fit_bindingCurves(input = file_path,tass = 200,tdiss = 530,conc_M = 1.2*math.exp(-7),generate_output = False) return g I am using rpy2 version 3.5.5 Here's the error: File "/Users/user.ali/Projects/ProjectDev/project_env/lib/python3.9/site-packages/rpy2/robjects/conversion.py", line 240, in _py2rpy raise NotImplementedError( NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'str'>' -
psycopg2.OperationalError: SSL connection has been closed unexpectedly
My application is using Django==3.0.6 with psycopg2==2.8.6. I am using Django ORM not SQl-Alchemy. I get this error every 4-5 days randomly. Unable to reproduce this error on local. Any suggestions what can be the reason for this? If I restart my application container, application starts working normally without any errors till I get same error in next 4-5 days. Traceback (most recent call last): ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute ma-datamanagement_1 | return self.cursor.execute(sql, params) ma-datamanagement_1 | psycopg2.OperationalError: SSL connection has been closed unexpectedly ma-datamanagement_1 | ma-datamanagement_1 | ma-datamanagement_1 | The above exception was the direct cause of the following exception: ma-datamanagement_1 | ma-datamanagement_1 | Traceback (most recent call last): ma-datamanagement_1 | File "/insightsmax_datamanagement_app/datastaging/data_upload.py", line 97, in get_s3_bucket_name ma-datamanagement_1 | project_obj = models.Project.objects.get(display_project_id=project_id) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method ma-datamanagement_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get ma-datamanagement_1 | num = len(clone) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 258, in len ma-datamanagement_1 | self._fetch_all() ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all ma-datamanagement_1 | self._result_cache = list(self._iterable_class(self)) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 57, in iter ma-datamanagement_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1151, in execute_sql ma-datamanagement_1 … -
Django - why my widget is cleared out during save?
I'm struggling with a django custom widget used to present HTML data. I've started with a template from standard django's textarea: class Descriptionarea(forms.Widget): template_name = "widgets/descriptionarea.html" def __init__(self, attrs=None): super().__init__(attrs widgets/descriptionarea.html: <textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value }}{% endif %}</textarea> Which works fine as an element of my inline form: class InlineForm(forms.ModelForm): description = forms.CharField(widget=Descriptionarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) which is part of my TabularInline (django-nested-admin in use): class TabularInline(NestedStackedInline): form = InlineForm fields = ("title", "description") readonly_fields = ("title", ) model = MyModel max_num = 0 I'd like to present the description as HTML document, so I've changed the template: <details> <summary>description</summary> <pre name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value | safe }}{% endif %} </pre> </details> Unfortunately, it does not work, as now I cannot use save on admin pages, as Django complains about: This field is required. Indeed during save, the whole widget is cleared out. Second question - when I add the description field to the list of readonly_fields, then it becomes a simple label. Is it possible to provide my own readonly widget? -
Add a .well-known folder to Django urls.py
I want to verify my SSL certificate to verify my server. What makes it more confusing is, it works just fine on my current certificate. But since it's expiring soon, I'm renewing it. But the auth file inside pki-validation folder can't be read. This is what it redirects to when I'm trying to check if the auth file is accessible: I'm using zeroSSL for my SSL. I'm suspecting that the .well-known folder can't be found by the server. So the answer is to specify the folder to the Django urls.py, but I'm having trouble on trying to add a hidden folder (.well-known) to the Django's urls.py file. Tried following this solution https://stackoverflow.com/a/55133603/20029765 but no luck, it redirects to a page saying "Internal Server Error": Is there any other solutions that I can try? -
Django rest framework serializer object from ID
I have this serializer: class OrderLineSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField(source="item.id") name = serializers.ReadOnlyField(source="item.name") price = serializers.ReadOnlyField(source="item.price") quantity = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(MAXNUMBERSIZE)] ) class Meta: model = OrderLine fields = ("id", "name", "price", "quantity", "sub_total") and it's fine when I send data to the user but is there a way to serialize data that I receive from the API without creating another serializer. if I receive some API request with this content {id : 123, quantity : 10} if doesn't get the item from the db. is there a way to do it or I have to create a dedicated serializer? -
Read Image present in Django Model
The code of the model is as follows class Post(models.Model): title = models.CharField(max_length=100) file = models.FileField(null=True,blank=True,upload_to='Files') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) I want to read the file (image or video). Let's say its an image. I want to read this image in an array format. I tried with the following code but i just get the file name and not a image matrix img = Post.objects.all()[0].file print(img) OR print(np.array(img)) Output is : car-1.jpg Expected output : 2d Array -
How to increase speed on select query?
I have a table that has 4 Foreign Keys,and this table contains only 2000 rows. The table was created by using Django ORM. I am using Postgresql as a database. when I send Select query to Database or GET request to that endpoint, data comes in 15 seconds. I have created 2 more indexes, data came in 18 seconds, I have deleted all foreign key indexes and kept only primary key index, data came in roughly 15 seconds again. How can I speed it up? it is simple Select query, SELECT * from table, this is the first time I encounter such thing, I have no idea what to improve. -
ProgrammingError at / column projects_project.prequalif_state does not exist LINE 1: SELECT "projects_project"."id", "projects_project"."prequali
I know the question has already been asked several times, but nothing worked for me I have a project that works properly locally, but when I deployed it on a virtual machine (working with CentOS), many problems related to the database appeared. When I try to print the fields of my 'Project' model from the shell, they are displayed correctly, but I can't display any object from this model : Same error when I try to create a Project object : This happens only with the models of my 'projects' application, I have another application who works correctly I removed all my migrations files and run makemigrations and migrate, nothing changed. If someone can give me any suggestion, I'm interested (nothing important in the database, I can reset it if necessary) Don't hesitate to tell me if you need me to add infomrations to my post -
How to pass request as an arguement to serializer in serializer method field
I have a main serializer, and I also have a serializer for my BOOK model so I made a method to return a serialized queryset using my BOOK SERIALIZER BUT the problem is ** I can't access my main serializer context through BookSerializer** What can I do? Views.py: class BookMainPage(ListModelMixin, RetrieveModelMixin, GenericViewSet): queryset = Book.objects.select_related('owner').all() def get_serializer_context(self): return {'user': self.request.user, 'book_id': self.kwargs.get('pk'), 'request': self.request} def get_serializer_class(self): if self.kwargs.get('pk') is None: return MainPageSerializer return BookComplexSerializer MainPageSerializer: class MainPageSerializer(serializers.Serializer): @staticmethod def get_new_books(self): return BookSimpleSerializer(Book.objects.all().order_by('-created_at')[:10], many=True).data @staticmethod def get_popular_books(self): return BookSimpleSerializer(Book.objects.all().order_by('-bookRate')[:10], many=True).data @staticmethod def get_most_borrowed(self): return BookSimpleSerializer(Book.objects.all().order_by('-wanted_to_read')[:10], many=True).data new_books = serializers.SerializerMethodField(method_name='get_new_books') popular_books = serializers.SerializerMethodField(method_name='get_popular_books') most_borrowed_books = serializers.SerializerMethodField(method_name='get_most_borrowed') BookSimpleSerializer: class BookSimpleSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'picture'] def get_picture(self, obj: Book): request = self.context['request'] photo_url = obj.picture.url return request.build_absolute_uri(photo_url) picture = serializers.SerializerMethodField(method_name='get_picture') class CategorySimpleSerializer(serializers.ModelSeria -
How to set up javascript and django applications to exchange jwt tokens
I have a SAP implemented on the Netlify platform. The processing for the app is implemented in a django api running on a hosted server. Users are authenticated on the Netlify app, but do not need to be authenticated in django. I now want authorised users to be able to post data to the api and the django server objects with the message Forbidden (CSRF cookie not set.): /api/save-archive/{...}/ I am looking at implementing JWT cookies and have considered djangorestframework_simplejwt but that seems to require that the user is authenticated in django My question is, what software elements do I need to be able to generate and consume a token is this scenario? -
Dynamically create a form / dynamically add fields to a form
I've been facing this issue in django and I don't know how to do. Here it is. I have the Product model, and a form allowing a person (not admin) to register a product. I would like to give the possibility to an admin to "build this form or update it", with the fields he wants. The Product template will then be updated with new fields, and the form filled by a person too. Is there a way to do this? Thanks -
Concatenate Properties of Django QuerySet
Can I join Django ORM Model properties/attributes into a string without introducing loops? I have a django model: class Foo(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=1000, db_collation='Latin1_General_CI_AS') I want to select the names into a string from a result of filtering: foos = Foo.objects.filter(id=[1,2,3]) Something equivalent of this piece of C#: using System; using System.Collections.Generic; using System.Linq; public class Program { public class Foo { public string Name { get; set; } } public static void Main() { List<Foo> foos = new List<Foo>(); foos.Add(new Foo { Name = "A1" }); foos.Add(new Foo { Name = "A2" }); Console.WriteLine(string.Join(",", foos.Select(x => x.Name))); } } Which outputs A1,A2. -
Get latest item date where item field_1 & item field_2 have duplicates
I'm using Django 4.0, and Python 3.8. I have a product that has a modification date, department name and designation. I want to retrieve each product but, for products that have the same designation and the same department, I only want to retrieve the last entry. Here is what i have now: ` products = Product.objects.all().order_by('designation') ` I tried sorting on the result and removing duplicate rows it worked for 10 rows but for 100 its dead For the following data: item: designation, date, department item_1, 01/01/1970, department_1 item_2, 01/01/1970, department_2 item_3, 01/01/1970, department_3 item_1, 01/02/1970, department_1 I want: item_1, 01/02/1970, department_1 item_2, 01/01/1970, department_2 item_3, 01/01/1970, department_3 Do you have any advice please ? -
Django/Wagtail Rest API URL Filter with no response
I am using Wagtail and I have an API called 127.0.0.1:8000/api/v2/stories. In the API I am having this JSON response { "count": 81, "results": [ { "id": 122, "title": "Test Blog", "blog_authors": [ { "id": 82, "meta": { "type": "blog.BlogAuthorsOrderable" }, "author_name": "Test", "author_website": null, "author_status": false, }, { "id": 121, "title": "Test Blog 1", "blog_authors": [ { "id": 81, "meta": { "type": "blog.BlogAuthorsOrderable" }, "author_name": "Test", "author_website": null, "author_status": false, }, } The main problem I am fetching is that I want to filter by author name. I have done this query in the URL ?author_name=Test & ?blog_authors__author_name=Test & ?author__name=Test But the response was { "message": "query parameter is not an operation or a recognised field: author_name" } I have added these fields in known_query_parameters but the response was the same as api/v2/stories/. I have tried DjangoFilterBackend but I got the same response every time. How Can I filter by author_name & author_status in the API? Here is my api.py class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] pagination_class = CustomPagination filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] known_query_parameters = frozenset( [ "limit", "offset", "fields", "order", "search", "search_operator", # Used by jQuery for cache-busting. See #1671 "_", # Required … -
Can't associate the correct IDs using the reverse ManyToMany relationship
**Hello, I'm trying to merge two models that are related through a ManyToMany field. Basically I want to establish a reverse relationship between the model "Position" and the model "Sale". Each sale can have multiple positions, but each position should be specific to its sale. Here is what happens. I filter through dates I know there's data (sales) and I get: sale_df sales_id transaction_id total_price customer salesman 0 11 3B6374D5ED85 300.0 Test Testuser 2022-10-25 1 12 D52E5123EDBE 900.0 Test Testuser 2022-10-24 (I purposefully removed "created" and "updated" because they didn't fit nicely here) position_df position_id product quantity price sales_id 0 10 TV 3 300.0 11 1 10 TV 3 300.0 11 2 11 Laptop 1 600.0 12 WHEN positions_df sales_id *should be* => position_id product quantity price sales_id 0 10 TV 3 300.0 11 1 10 TV 3 300.0 12 2 11 Laptop 1 600.0 12 It seems like when I get the sale_id in reverse through the method "get_sales_id()" it associates it with the first instance of the position, instead of prioritizing the sale_id Here is the code: models.py from django.db import models from products.models import Product from customers.models import Customer from profiles.models import Profile from django.utils import timezone … -
Is it OK to use Django development server for single-user applications?
I'm developing an application that controls some piece of complex hardware and exposes a front-end to the users (currently with Django templates, but soon with a separate front-end through DRF calls). My main points of interest are: user management. Admin users have more access session management. Ideally, one cannot login from multiple IPs at the same time. web-socket support for asynchronous notifications and real-time monitoring. asynchronous background operations. e.g. with celery workers Note that the users of these application are the hardware operators which are usually no more than 3-5 tops, and most of the times, only one of them is actively working on it so no real user concurrency, neither real need to scale. So my question is: Is there a real reason I would need to distribute my application using a production server such as gunicorn instead of simply running manage.py runserver? -
How to get exact values of the foreignkeys in django admin
class Mio_terminal(models.Model): terminal = models.CharField(max_length = 50) gate = models.CharField(max_length = 50) gate_status = models.CharField(max_length = 50, default = 'open') #open, occupied, under_maintenance class Meta: unique_together = [['terminal', 'gate']] class Mio_flight_schedule(models.Model): fact_guid = models.CharField(max_length=64, primary_key=True) airline_flight_key = models.ForeignKey(Mio_airline, related_name = 'flight_key', on_delete = models.CASCADE) source = models.CharField(max_length = 100) destination = models.CharField(max_length = 100) arrival_departure = models.CharField(max_length=12) time = models.DateTimeField() gate_code = models.ForeignKey(Mio_terminal, related_name = 'terminal_gate', null = True, on_delete = models.SET_NULL) baggage_carousel = models.CharField(max_length = 100) remarks = models.CharField(max_length = 100) terminal_code = models.ForeignKey(Mio_terminal, related_name = 'airport_terminal', null = True, on_delete = models.SET_NULL) this is models for terminal and flight schedule. I want to have terminal name and gate code instead of the object ... i know we can get this by using str method in models....but we get only single value for this...not more than one please let me know how should i deal with this?