Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Queryset Dataframe - turn decimals into floats
I am turning a queryset into a dataframe. The thing is that the type of the items are 'Decimals' (for instance: Decimal('-1800000.00') ) . I would like these to turn into normal floats so I can make computations with them. How can I do this? Thanks to all !! dataframe = pd.DataFrame(list(Item.objects.filter(item__slug=fundslug).values('date','amount'))) -
How to update initial value of a field in django form
I am trying to update the initial value in the form based on the user input. My form has two fields, ID (with initial value 18-955) and Name (with no initial value). The form should display 18-956 in ID field and user input in the Name field after the submit button has been clicked. Here's my code: views.py def formbact(request): form = formsp(request.POST) if request.method == 'POST': if form.is_valid(): contentdict = form.cleaned_data userinput = contentdict["SOMEID"] newinput = userinput.split("-")[0]+"-"+str(int(userinput.split("-")[1])+1) #Increment id by 1 nameinput = contentdict["NAME"] form = formsp(newinput, nameinput) else: form = formsp() mydict = { 'inputinfo':form, } template = loader.get_template ('bacteria/masterlist.html') return HttpResponse(template.render(mydict, request)) forms.py class formsp(forms.Form): def __init__(self, *args): super(formsp,self).__init__(*args) if len(args) == 2: self.fields["SOMEID"].initial = args[0] self.fields["NAME"].initial = args[1] SOMEID = forms.CharField(label='ID', initial="18-955", widget = forms.TextInput()) NAME = forms.CharField(label='Name', widget = forms.TextInput()) masterlist.html <form autocomplete="off" action="" method="post"> {% csrf_token %} {% for field in inputinfo %} {{ field.label_tag }} {{ field }} {% endfor %} <br><input type="submit" value="Submit" /></br> </form> How do I get the form to display 18-956 in ID field and user provided name after the form has been posted? I am getting AttributeError : 'unicode' object has no attribute 'get' message. -
How to filter ModelAdmin autocomplete_fields results with the context of limit_choices_to
I have a situation where I wish to utilize Django's autocomplete admin widget, that respects a referencing models field limitation. For example I have the following Collection model that has the attribute kind with specified choices. class Collection(models.Model): ... COLLECTION_KINDS = ( ('personal', 'Personal'), ('collaborative', 'Collaborative'), ) name = models.CharField() kind = models.CharField(choices=COLLECTION_KINDS) ... Another model ScheduledCollection references Collection with a ForeignKey field that implements limit_choices_to option. The purpose of this model is to associate meta data to a Collection for a specific use case. class ScheduledCollection(models.Model): ... collection = models.ForeignKey(Collection, limit_choices_to={'kind': 'collaborative'}) start_date = models.DateField() end_date = models.DateField() ... Both models are registered with a ModelAdmin. The Collection model implements search_fields. @register(models.Collection) class CollectionAdmin(ModelAdmin): ... search_fields = ['name'] ... The ScheduledCollection model implements autocomplete_fields @register(models.ScheduledCollection) class ScheduledCollectionAdmin(ModelAdmin): ... autocomplete_fields = ['collection'] ... This works but not entirely as expected. The autocomplete retrieves results from a view generated by the Collection model. The limit_choices_to do not filter the results and are only enforced upon save. It has been suggested to implement get_search_results or get_queryset on the Collection model. I was able to do this and filter the results. However, this changes Collection search results across the board. I am unaware β¦ -
Experiencing odd output from django.utils.timezone.now(), datetime.datetime.now() and pytz.timezone
I'm experiencing strange behavior when attempting to convert between UTC and specific timezones. I'd love for someone to explain why I'm seeing this behavior and what the more "correct" way of getting timezone information might be. Code: import pytz import datetime from django.utils import timezone print(timezone.now()) print(pytz.utc.localize(datetime.datetime.now())) print('\n') def get_local_and_utc_date_ranges(days=1500, days_ago=2, local_timezone="America/Asuncion"): seller_timezone = pytz.timezone(local_timezone) utc_timezone = pytz.utc seller_today = timezone.now().astimezone(seller_timezone) seller_days_ago = seller_today - timezone.timedelta(days=days_ago) local_date_end = seller_days_ago.replace(hour=23, minute=59, second=59, microsecond=999999) local_date_start = (local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0) utc_date_end = local_date_end.astimezone(utc_timezone) utc_date_start = local_date_start.astimezone(utc_timezone) date_ranges = { "local_date_end": local_date_end, "local_date_start": local_date_start, "utc_date_end": utc_date_end, "utc_date_start": utc_date_start, } return date_ranges def get_utc_and_local_date_ranges(days=1500, days_ago=2, local_timezone='America/Asuncion'): seller_timezone = pytz.timezone(local_timezone) utc_timezone = pytz.utc utc_today = datetime.datetime.utcnow() utc_days_ago = utc_today - datetime.timedelta(days=days_ago) local_date_end = seller_timezone.localize(utc_days_ago).replace( hour=23, minute=59, second=59, microsecond=999999 ) local_date_start = (local_date_end - datetime.timedelta(days=days)).replace( hour=0, minute=0, second=0, microsecond=0 ) utc_date_end = local_date_end.astimezone(utc_timezone) utc_date_start = local_date_start.astimezone(utc_timezone) date_ranges = { 'local_date_end': local_date_end, 'local_date_start': local_date_start, 'utc_date_end': utc_date_end, 'utc_date_start': utc_date_start, } return date_ranges days = 1500 days_ago = 2 dates = get_local_and_utc_date_ranges(days=days, days_ago=days_ago) dates2 = get_utc_and_local_date_ranges(days=days, days_ago=days_ago) print('dates1:') print('local_date_start:', dates['local_date_start']) print('local_date_end:', dates['local_date_end']) print('utc_date_start:', dates['utc_date_start']) print('utc_date_end:', dates['utc_date_end']) print('\n') print('dates2:') print('local_date_start:', dates2['local_date_start']) print('local_date_end:', dates2['local_date_end']) print('utc_date_start:', dates2['utc_date_start']) print('utc_date_end:', dates2['utc_date_end']) print('\n') Output: 2019-03-25 18:57:55.929908+00:00 2019-03-25 18:57:55.930005+00:00 dates1: local_date_start: 2015-02-12 00:00:00-04:00 local_date_end: β¦ -
Django redirect interrupted by browser?
I have a very simple view that is purposed to track a user's click and redirect them to an external page: def redirect_view(request, uu_id): my_model = MyModel.objects.get(uuid = uu_id) my_model.clicked_link = True my_model.save() return redirect('https://www.some-other-site.com') For about half of the users that interact with this view it works perfectly! Our logs show a 302 response and then nothing further from the user. For the other half of our users they are strangely redirected to the base url of our site in http, then because we have SECURE_SSL_REDIRECT = True they are redirected to https, and finally because they are not authenticated they are redirected for authentication. Our logs for this type of user look something like this: Feb 21 10:04:51 myapp heroku/router: at=info method=GET path="/redirect-url" host=mysite.com request_id=123 fwd="..." dyno=web.1 connect=0ms service=25ms status=302 bytes=268 protocol=https Feb 21 10:04:51 myapp heroku/router: at=info method=GET path="/" host=mysite.com request_id=456 fwd="..." dyno=web.1 connect=1ms service=3ms status=301 bytes=262 protocol=http Feb 21 10:04:52 myapp heroku/router: at=info method=GET path="/" host=mysite.com request_id=789 fwd="..." dyno=web.1 connect=0ms service=2ms status=302 bytes=360 protocol=https There is nothing in our code that would suggest a redirect to our base url so my only thought is that they have some sort of browser setting that limits external redirects. β¦ -
Using Django RequestFactory, this error is thrown: "Requested setting DATABASES, but settings are not configured."
This is an example test from Django's documentation. from django.test import RequestFactory, TestCase class SimpleTest(TestCase): def setUp(self): self.factory = RequestFactory() def test_hello(self): request = self.factory.get('/hello') Running the test throws this error: Failure Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/suite.py", line 146, in _handleClassSetUp setUpClass() File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/test/testcases.py", line 1026, in setUpClass if not connections_support_transactions(): File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/test/testcases.py", line 991, in connections_support_transactions for conn in connections.all()) File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/db/utils.py", line 226, in all return [self[alias] for alias in self] File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/db/utils.py", line 223, in __iter__ return iter(self.databases) File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/myuser/dev/pythonagent-my_package/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't see where I can access settings to call configure() on it. Neither the request factory nor the test object has any such field. -
Slow Postgres Query using Limits
I'm experiencing an issue similar to PostgreSQL query very slow with limit 1 and Extremely slow PostgreSQL query with ORDER and LIMIT clauses although in my case it doesn't matter if the LIMIT is 1, 5 or 500. Basically, when I run a query generated by Django's ORM without a limit, the query takes half a second but with the limit (added for pagination) it takes 7 seconds. The query that takes 7 seconds is: SELECT "buildout_itemdescription"."product_code_id", MIN("buildout_lineitem"."unit_price") AS "min_price" FROM "buildout_lineitem" INNER JOIN "buildout_itemdescription" ON ("buildout_lineitem"."item_description_id" = "buildout_itemdescription"."id") WHERE (("buildout_lineitem"."report_file_id" IN (154, 172, 155, 181, 174, 156, 157, 182, 175, 176, 183, 158, 177, 159, 179, 178, 164, 180, 367, 165, 173, 166, 167, 168, 368, 422, 370, 169, 1335, 1323, 161, 160, 162, 170, 171, 676, 151, 163, 980, 152, 369, 153, 963, 1718, 881, 617, 1759, 1780, 636, 1199, 1243, 947, 1163, 1422, 1009, 1407, 1035, 1241, 1077, 1271, 1111, 1130, 1489, 1507, 1555, 1600, 1619, 1663) AND "buildout_lineitem"."unit_price" > 0 AND NOT ("buildout_itemdescription"."product_code_id" IS NULL) AND "buildout_lineitem"."date" >= '2014-04-20'::date AND "buildout_lineitem"."date" <= '2019-03-25'::date)) GROUP BY "buildout_itemdescription"."product_code_id" ORDER BY "buildout_itemdescription"."product_code_id" LIMIT 5 And the other query is the same without the LIMIT 5. Postgres is using very β¦ -
Django m2m how to use name instead of name_id
i want to add tags for new posts. I use bootstrap tags input. It works only if I write tags_id, not tag title. And if I write new numbers, it saves post with new number tag. How to change tag_id to tag_title in m2m db table or other way to fix it? class Tag(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, blank=True, unique=True) body = RichTextField() date_pub = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, blank=True, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(blank=True, default=0) view def post(self, request): tags = request.POST.getlist('tags') for tag in tags: objs, created = Tag.objects.get_or_create(title=tag, slug=tag) bound_form = self.model_form(request.POST)) if bound_form.is_valid(): post = bound_form.save(commit=False) post.author = request.user post.save() post.tags.add(objs) post.save() new_obj = bound_form.save() return redirect(new_obj) return render(request, self.template, context={'form': bound_form}) form class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'slug', 'body', 'tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'slug': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'tags': forms.SelectMultiple(attrs={'class': 'form-control', 'data-role': 'tagsinput'}), } exclude = ['author',] I want to have tags as words not id's. Now when I add words is display error: "qwe" is not a valid value. It wants numbers and maybe to fix displaying all tags in β¦ -
progressing operations after closing site
I am currently working on a Django project. I have a feature that takes hours to get completed.(Math operations) I want to do like this; User will input their demandings through a form. Then They will see a message that "Your operation queued, it will be sent to you as an email after getting completed." Even after they close this site, their operations are being done in my server. And after getting completed, The system let the user know in the way I want such as email or sms. Thank you for helping. -
Looking for the best and simple-to-setup notification handler app for Python Django
I'm setting up a django user platform with user notifications. I have the following requirements for my notifications I'd like users to have a notification feed visible on-hover the menu entry "Notifications". The notification feed (in every site inheriting base.html + a menu) should show a maximum of the newest 5 unread notifications in every user site. The notifications should be saved into the database as objects. optional: live reload via AJAX send via mail + user preferences for notifications What I found so far: I looked at the django documentation, but I had the feeling none of the above worked smoothly for my purpose. Stream framework was way too complicated to set-up for me with a custom database. django-notifications (like GitHub) was way too buggy and is maintained very slowly. I like pinax-notifications, could set it up, but I don't see from the documentation how to show all notifications in my base.html template for the logged in user and also I don't see how it saves notifications to the database. I also found django-pusherable, don't know if it works for notifications? Can you give me any tips on how to set-up or any app recommendations? Kind regards -
Django template search
I've read the docs, but I'm struggling to understand exactly the order in which django looks for templates. My template settings: TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": [], "APP_DIRS": True, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, }, ] I have a "templates" folder at the root of the project, which has this structure: templates βββ jinja2 βββ emails βββ base_email.html βββ base_email.plain And each app has its own "templates folder", like this: templates βββ jinja2 βββ emails βββ account βββ validate_email.html βββ validate_email.plain The templates are called like this: render_to_string( "jinja2/emails/account/validate_email.html", context ) This seems to be able to find the initial template (validate_email), but when validate email tries to extend the "base_email": {% extends "base_email.html" %} I've tried replacing this extends tag with: {% extends "jinja2/emails/base_email.html" %} but it made no difference. -
How to globally disable autoescape of Django templates?
I am using Django templates in a non HTML environment, so naturally I'd like to turn off HTML auto escaping. How do I turn it off on a global level? I know about the plethora of options to suppress auto escape locally: django.utils.safestring.mark_safe safe filter autoescape tag autoescape constructor argument of Context These options suppress a globally enabled auto escape, where in my use case I'd like to have the reverse. According to the docs there should be an 'autoescape' option for the DjangoTemplates backend. I even found the feature request and commit that added it. Yet it does not seem to work for me. Minimal example: from django.template import Context from django.template import Template import django from django.conf import settings TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "autoescape": False } } ] settings.configure(TEMPLATES=TEMPLATES) django.setup() template = Template("My name is {{ my_name }}.") context = Context({"my_name": "<FooBar>"}) print(template.render(context)) Expected output: My name is <FooBar>. Actual output: My name is &lt;FooBar&gt;. I am probably missing something stupid. Could someone enlighten me? My virtual environment: python==3.6.5 Django==2.1.7 pip==9.0.3 pytz==2018.9 setuptools==39.0.1 -
Fetch related ID's and aggregate in a new column
So my problem is coming from a poor understanding of the complexity of my querry. A bit of a background story to this ask. It's a car rental and search website, which started as a personal project of mine. I am using Django 2.1 for this, as well as Postgres. The setup is as follow: I have a car, which has an ID, a category, a car model, an engine etc. What I would like to do now is the following: I want to create Google Ads specific .csv files. I dont really have a problem making a csv, but my problem is rather in contructing the query for this to work. I have the following as a first step: cars = Car.objects .select_all_related() .only( 'id', 'name', 'address__city', 'address__city_area', 'images' ) 1 select_all_related joins the address table, because that's where the car is located. works. 2 only gives me only the fields I want, since i dont wanna sent the whole model anyway, this also works. Now onto the problem: The following code should give me a column in the table. This column should have aggregated IDs of the cars that are in a similiar area. And this is sadly β¦ -
How to redirect a ListView to DetailView if queryset is a single object?
I have a ListView with a custom get_queryset() method and a DetailView, but I would like to avoid showing the ListView when the queryset returns only one object (I want to redirect the user to the DetailView of that object). Is there a way to accomplish that using class based views? I tried with a redirect inside the get_queryset() of ListView, but it doesn't work and I can't find anything useful in the ListView class documentation. -
Can i create models in django after creating tables in the database?
I created a table and inserted all records into it in PostgreSQL, so i did not create models for it in django. Can i create models for it now ? -
valueError: invalid literal for int() with base 10: '' while migrate
I wrote this simple model in django-2 and when I tried to migrate I got ValueError: invalid literal for int() with base 10: '' from django.db import models class Teacher (models.Model): name = models.CharField(max_length=50) user= models.IntegerField(default='',blank=True) passcode= models.IntegerField(default='',blank=True) def __str__(self): return self.name class Student (models.Model): name= models.CharField(max_length=50) user= models.IntegerField(default='',blank=True) passcode= models.IntegerField(default='',blank=True) teacher= models.ManyToManyField(Teacher) def __str__(self): return self.name class Lesson (models.Model): name = models.CharField(max_length=50) cource = models.IntegerField(default='',blank=True) teacher = models.ForeignKey("Teacher", on_delete=models.CASCADE) Student= models.ManyToManyField(Student) def __str__(self): return self.name class Score (models.Model): score= models.FloatField(default='',blank=True) student= models.ForeignKey(Student, on_delete=models.CASCADE) lesson= models.ForeignKey(Lesson, on_delete=models.CASCADE) -
How do I write a Django query and include a PostGres function (current_time) in my WHERE clause?
I'm using Django, Python 3.7 and PostGres 9.5. I want to write the following WHERE clause in Django ... WHERE date_part('hour', current_time) = s.hour ... so in reading some other documentation, I'm led to believe I need to write a "Func" create an annotation before running my query ... qset = ArticleStat.objects.annotate( hour_of_day=Func( 'current_time', Value('hour'), function='date_part', ) ).filter(hour_of_day=F("article__website__stats_per_hour__hour")) However, this results in a Cannot resolve keyword 'current_time' into field. Choices are: article, article_id, elapsed_time_in_seconds, id, score error. It seems like Django is tryhing to treat "current_time" as a column from my table but I really want it to be treated as a PostGres function. How do I do that? -
Django forms does not update?
I want to put an email field in my form. The main problem that even changing the forms.py does not change anything in the interface, I already took up code I already had and form is still there and cleared the browser cache. form.py: class TeacherSignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'password1', 'password2') def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.is_teacher = True if commit: user.save() return user -
How to avoid permission denied with caching files in Django?
I keep getting this issue from my django website, every time I have to go the path to remove the root access for all files and give access to the current user with chown user_name:user_group *, and it works. But after the website generating some new cached files, the problem gets back. Internal Server Error: / PermissionError at / [Errno 13] Permission denied:'/var/tmp/project_cache/a92ccb8f0f5dc3d17dbaae74ac7.djcache' I use django cache based on files. Here is my settings CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/project_cache', 'TIMEOUT': 60 * 15, 'OPTIONS': { 'MAX_ENTRIES': 1000 } } } Do I need to never user cache with files? -
Django querysets, less than or greater than versioning number
My project model Software has a value called version with inputs like "3.2.4.98" Now in my webapp you select 2 numbers eg. (0 , 4.2) And i grab the versions that are greater than or equal to 0 and less than or equal to 4.2. with a queryset like this to then show only data within the two versions : Software.objects.filter(version__gte= self.versionA, version__lte=self.versionB) versionA = 0 and versionB = 4.2 in this scenario. And this obviously doesn't work because it doesnt make comparisons with strings and multiple decimal digits like "3.2.4.98". I take in the value of version as a string and save it to the model like so: def insert_created_bug_data(self, data): values = list((item['version']) for item in data['issues']) for x in values: insert_model = Software(key=bug[0]) insert_model.save() And my views.py will give me a query set and give back context that is in between the 2 versions Views.py class VersionView(LoginRequiredMixin, TemplateView): template_name= 'app/version_report.html' def get(self, request, *args, **kwargs): self.versionA = request.GET.get('versionA','') self.versionB = request.GET.get('versionB','') return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(VersionView, self).get_context_data(**kwargs) context['version_total'] = Software.objects.filter(version__gte= self.versionA, version__lte=self.versionB) return context The Problem: How can i set up the version value so i am able to create a queryset β¦ -
How to refresh values in Django-form dropdown list?
In my django project I have a form with dropdown list of options from database. When server starts up all options are there, but if there is an option added while it runs, the new option won't show up in dropdown list. forms.py class filter(forms.Form): filterOption=forms.CharField(widget=forms.Select(choices=getOptions()) functions.getOptions() returns a list of options from mySQL (database is not the problem here). It is then rendered in views.py and put into html form. from .forms import filter def index(request): filter = filter() return render(request, 'homePage/home.html',{'filter':filter}) I understand that the form object is created when the server starts, but if a new option is added and getOptions() should return one more option, how can I re-initialise that form object without restarting the server. Sometimes it is added after ~10min, but I need it instantly. -
How to add a new input in a form for a model related (by foreign key) to the main model of the form?
PERSONS have one NAME and they have none or one or several ATTRIBUTES. I want to create a webpage to edit a person's name and attributes at the same time, like this: Editing person named : PETER His attributes are : CHILL (editable field) "Delete" (button to delete chill) COOL (editable field) "Delete" (button to delete cool) "Add" (button to add a new blank editable attribute field to peter) "Save" (One single button to save all changes) My model is : from django.db import models class Person(models.Model): name = models.CharField(max_length=80, unique=True) class Attribute(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) attribute = models.TextField(max_length=200) In my views.py, I can send the right person and attributes to my templates: person = Person.objects.get(pk=person_id) attributes = Attribute.objects.filter(person=person_id) context = {'person': person, 'attributes':attributes} return render(request, 'sub_app/edit_person.html', context) My problem is I have no idea how to build my template to allow the possibility to add a NEW attribute field (without losing/saving a potential change of the person's name) and send the changes back to my view. Note : If that is useful, I use VueJS 2 as Front. Thanks for the help ! -
How to get different substring of a filed in Django model?
I want to get substring set of a field in Django model. the data format like this 1, 20001, a 2, 20002, a 3, 21002, a 4, 51003, b 5, 51001, a I only want to get first two charactor of the second column with distinct: [20, 21, 51] How can I get the result using django model function? I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. -
what document i need to put in .gitignore when I start a new django project
So I want to start a project with django2 and I want to know what kind of doc I can ignore when push them to github. -
How can I insert foreign key values into forms?
I am setting up a web app, which allows to book transports from one destination to another. My problem is that the form shows all attributes, but it doesn't let me insert a foreign key nor am I able to choose the right foreign key from a list. class Loading_location(models.Model): address = models.CharField(max_length=40) postal_code = models.CharField(max_length=10) place = models.CharField(max_length=30) class Deloading_location(models.Model): address = models.CharField(max_length=40) postal_code = models.CharField(max_length=10) place = models.CharField(max_length=30) class Customer(models.Model): company = models.CharField(max_length=40) address = models.CharField(max_length=40) postal_code = models.CharField(max_length=10) place = models.CharField(max_length=30) class Truck(models.Model): mark = models.CharField(max_length=20) brand = models.CharField(max_length=20) type = models.CharField(max_length=20) class Order(models.Model): order_date = models.DateField() customer = models.ForeignKey(Customer, on_delete=models.PROTECT, null=True, default=None) loading_location = models.ForeignKey(Loading_location, on_delete=models.PROTECT, null=True, default=None) deloading_location = models.ForeignKey(Deloading_location, on_delete=models.PROTECT, null=True, default=None) truck = models.ForeignKey(Truck, on_delete=models.PROTECT, null=True, default=None) price = models.FloatField(max_length=7) forms.py from django import forms from .models import Auftrag class CreateOrder(forms.ModelForm): class Meta: model = Order fields = [ 'order_date', 'customer', 'loading_location', 'deloading_location', 'truck', 'price' ] ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, views.py from django.shortcuts import render from .models import Order from .forms import CreateOrder def creating_order_view(request): form = CreateOrder(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "transporter/order_creation.html", context) The expected output would be that I can choose the foreign keys from β¦