Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: displaying all fields of all tables, the dumbest view possible
I've inherited a Django PostGres application with a model containing around 40 tables. I've redesigned the model from head to toe, and now I'm setting in to re-build the web front end. I haven't used Django previous to this project - and no HTML for many years - but I'm happy enough with the ORM end of Django. As a raw default, I just wanted to display all the fields of a class on an individual html page. Any references (i.e. ForeignKeys, or ManyToOne references) should appear as html links to another html page, which displays that class' data. The application that I've inherited does more or less that, but uses about 50 modules containing hundreds of boiler-plate views, forms, and serializers - absolutely none of which contain anything remotely intelligent in. The "active" code on each form just sayd 'all'. Rather than autogenerate this code (yuk!), is there a quick way of asking Django to display a basic tabular view unless there is a bespoke view for the table? -
(Django) I am wondering how I should approach to make an customized order app for the Subway clone
I have been working on cloning Subway sandwich website(https://order.subway.com/en-US/restaurant/12608/menu) And I have been trying to copy the API they have for customizing and was wondering how I should do such task. Or maybe it's not even possible to clone this website? Below is the example of the customization https://order.subway.com/en-US/restaurant/12608/customizer/productSummary/3001/product/30101/category/3/# -
How to create a link in the Django website
I am working on the Django blog. I have created a url column in the admin post as follows. however when I click the link in the page, the page jumps to the link which contains the localhost:8000 at the head of the url. e.g. http://127.0.0.1:8000/Yahoo/www.yahoo.com I made a link as <a href="{{ post.url }}">Visit yahoo.com!</a> however this is probably a wrong way to do it. Can you please advise me how to fix this issue? my class in model.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) url = models.CharField(max_length=200, unique=True, default='') class Meta: ordering = ['-created_on'] def __str__(self): return self.title my html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-3 left top"> <div class="card-body"> <h1>{% block title %} {{ object.title }} {% endblock title %}</h1> <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p> <p class=" text-muted">{{ post.url }}</p> <a href="{{ post.url }}">Visit yahoo.com!</a> <p class="card-text ">{{ object.content | safe }}</p> </div> </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> {% … -
im getting page not found at / i, trying to create a django python form
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in repo.urls, Django tried these URL patterns, in this order: home/ [name='name'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.[this is urls.py and views.py 1and this is home.html][this is base.html] -
The current path, customer, didn't match any of these. even when all other path runs correctly
ERROR :Using the URLconf defined in crm1.urls, Django tried these URL patterns, in this order: admin/ [name='home'] products/ [name='products'] customer/<str:pk_test>/ [name='customer'] create_order/<str:pk>/ [name='create_order'] update_order/<str:pk>/ [name='update_order'] delete_order/<str:pk>/ [name='delete_order'] The current path, customer, didn't match any of these. even when i run this.....accounts/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), path('products/',views.products, name='products'), path('customer/<str:pk_test>/',views.customer,name='customer'), path('create_order/<str:pk>/',views.createOrder,name='create_order'), path('update_order/<str:pk>/',views.updateOrder,name='update_order'), path('delete_order/<str:pk>/',views.deleteOrder,name='delete_order'), ] all path are working out correctly and even when i run http://127.0.0.1:8000/customer/2 it runs properly....but when i run http://127.0.0.1:8000/customer/ error out -
Django. How to restrict a user to put review only once?
Hello guys I am making a ecommerce website as part of learning django. I have a review model but I want to make sure that a customer can only put a review once. How to do that with my existing model and views. Please have a look at my codes: views def product_review(request, slug): user = request.user product = get_object_or_404(Product, slug=slug) reviews = ProductFeedback.objects.filter(product=product).order_by('-id') if request.POST: if product.user == request.user: messages.error(request, 'You can\'t review your own product') return redirect('store:product_detail', product.slug) else: p_review_form = ProductReviewForm(request.POST or None) if p_review_form.is_valid(): product_rating = request.POST.get('product_rating') product_review = request.POST.get('product_review') p_review = ProductFeedback.objects.create(product=product, user=user, product_rating=product_rating, product_review=product_review) p_review.save() return redirect('store:product_detail', product.slug) else: p_review_form = ProductReviewForm() context = { 'product':product, 'p_review_form':p_review_form, 'reviews': reviews, } return render(request, 'store/product/product_detail.html', context) model class ProductFeedback(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product') product_rating = models.CharField(choices=RATINGS, max_length=10, null=True) product_review = models.TextField(max_length=1000) reply = models.ForeignKey('ProductFeedback', null=True, related_name='replies', blank=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user.username}--{self.product.title} review' -
Getting link of latest article in Models
I have a post signal in my Models so that when I create a new post thru the admin, it will send a mail. It works, but I want the message to include the link of the article I just created. How can I do this? def send_mails(sender, **kwargs): if kwargs['created']: message = 'Hello!\nWe have a new post: mysite.net/{latest article id}\nEnjoy!\n\nKind regards,\nThe Analyst' subject = 'New Article Published!' to = Email.objects.values_list('email', flat=True).distinct() from_email = settings.EMAIL_HOST_USER send_mail(subject, message, from_email, to, fail_silently=True) post_save.connect(send_mails, sender=Post) -
Django template directory not loaded on Heroku
I have a Django app that I just deployed on Heroku. Problem is that templates in my /app/templates directory are not being searched and so going to the root URL returns a 404: TemplateDoesNotExist at / home_landing.html The template that should be served up is /templates/home_landing.html. When I hit the root URL, /templates is not being searched: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/my_app/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.8/site-packages/django/contrib/sitemaps/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.8/site-packages/tinymce/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/accounts/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/orgs/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/orgadmin/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/orgemail/templates/home_landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/blog/templates/home_landing.html (Source does not exist) Here's the relevant code from prod_settings.py: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", 'DIRS': [os.path.join(BASE_DIR, 'templates')], "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", ] }, } ] In the Heroku console it looks like /app/templates should be searched: Feels like I'm missing something obvious here. Thanks! -
Cannot assign "<QuerySet [<PaymentType: Regular>]>": "StudentsEnrollmentRecord.Payment_Type" must be a "PaymentType" instance
i know my filtering is totally messed up, and im not very good on filtering. any ideas on how to solve my problem? educlevel = request.POST.get('gradelevel') s=EducationLevel.objects.filter(id = educlevel) paymenttype = ScheduleOfPayment.objects.filter(Education_Levels__in = s.values_list('id')) payment = PaymentType.objects.filter(id__in=paymenttype.values_list('Payment_Type')) V_insert_data = StudentsEnrollmentRecord.objects.create( Payment_Type=payment ) this is my models class EducationLevel(models.Model): Description = models.CharField(max_length=500,blank=True,null=True) class PaymentType(models.Model): Description = models.CharField(max_length=500,blank=True) class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, blank=True, null=True) this is the full traceback this is the error -
How to mock a function present inside another function in Python?
I want to mock a function present inside another function like this: def parent_function(): def child_function(): # mock this function return something_1 child_function() # calling the child function and doing other things return something_2 Here is how I tried to mock it: @patch('package.parent_function.child_function') def test_some_method(self, mocked_function): # doing testing It threw the below error: AttributeError: <function parent_function at 0x7f7d46a2d170> does not have the attribute 'child_function' What am I doing wrong? and how can I solve this problem. P.S. Please don't suggest me to modify the main code as I am not allowed to do that, I have to do just the testing. -
'Post' object has no attribute 'get_content_type' in django Photo Blog App
I am really lost and trying to solve this issue for hours. I am working on this social media for photographers, where they can comment each other's photos. I set up forms for comments, but I am getting AttributeError : 'Post' object has no attribute 'get_content_type' This is my Views.py - photo_detail, where is the error : def photo_detail(request, id): instance = get_object_or_404(Post, id=id) comments = Socialmedia.objects.filter_by_instance(instance) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } socialmedia_form = SocialmediaForm( request.POST or None, initial=initial_data) if socialmedia_form.is_valid(): print(socialmedia_form.cleaned_data) context = { "title": instance.title, "photo": instance.photo, "instance": instance, "comments": comments, "socialmedia_form": socialmedia_form, } return render(request, "photo_detail.html", context) When I comment out line "content_type": instance.get_content_type,, the error disaapers, but after writing comment its saying field is required and not posting anything , so it doesnt load the data from comment. And here is my models.py : from django.db import models from django.urls import reverse from django.contrib.auth.models import User from socialmedia.models import Socialmedia, SocialmediaManager from django.contrib.contenttypes.models import ContentType def upload_location(instance, filename): return '%s/%s' % (instance.id, filename) class Post(models.Model): # category = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=200) updated = models.DateTimeField(auto_now=True, auto_now_add=False) time = models.DateTimeField(auto_now=False, auto_now_add=True) photo = models.ImageField(upload_to=upload_location, null=True, blank=True, … -
Django, call application view function dynamically
I have following project structure: django_project: app1 view_function_a app2 view_function_a app3 view_function_a management_app call_all_functions Functions have same name. How to dynamically call all "view_function_a" from within "call_all_functions"? -
Dynamic form choices is not being displayed without refresh
I am trying to add form choices dynamically which are loaded after user enters some data and click a button. An empty choice field is displayed after button click [image1] But choice options are not displayed until i refresh the page and click the button again [image2]. views.py from django.shortcuts import render from .forms import sampleForm, action, displayLists import requests import json RDS = '' option = '' link_list = [] hostname_list = [] receiver_link = [] sender_link = [] receiver_name = [] sender_name =[] def get_Nodes(request): if request.method == 'POST': form = sampleForm(request.POST) if form.is_valid(): RDS = form.cleaned_data['RDS'] session = requests.Session() session.trust_env = False response = session.get(RDS) data_list = json.loads(response.content) index = 0 while index < len(data_list)-1: link_list.append(data_list[index]["href"]) hostname_list.append(data_list[index]["hostname"]) data_req = session.get(data_list[index]["href"] + '/x-nmos/connection/v1.1/single/receivers/') data = json.loads(data_req.content) if not data: sender_link.append(data_list[index]["href"]) sender_name.append(data_list[index]["hostname"]) else: receiver_link.append(data_list[index]["href"]) receiver_name.append(data_list[index]["hostname"]) index += 1 sl_show = tuple(zip(sender_link,sender_name)) print(sl_show) form = sampleForm() form2 = displayLists(choices=sl_show) if request.method == 'POST': form2 = displayLists(request.POST) if form2.is_valid(): option2 = form3.cleaned_data['Device_list'] print(option2) tmp = { 'form': form, 'form2' : form2 } return render(request, 'form.html', tmp) form.html <body style="padding: 20px;"> <div id="form1"> {% csrf_token %} {% crispy form form.helper %} </div> <div > <form id="f" style="display: none;"> {% csrf_token %} {{ … -
Pass Vars from Django template to views
Im creating a filter for product categories and would like to pass the category name from the appropriate image on my template. Part of the filter bar: <a href="{% url 'product-filter' MISC%}"> <img src="{% static 'store/images/skateboard.png' %}" alt=""> </a> Urls: path('search/<category>/', store_views.product_filter ,name='product-filter'), I want MISC from the template to pass and become the category so that i can use it in views: # ? Filter Products by Catagory def product_filter(request, category): products= Product.objects.all() filter=ProductFilter(category,queryset=products) context={'products':filter} return render(request,'store/filter.html',context) Getting this currently even just on my home page: NoReverseMatch at / Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category>[^/]+)/$'] And this when on /search/MISC: NoReverseMatch at /search/MISC/ Reverse for 'product-filter' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category>[^/]+)/$'] -
How to access context list using JavaScript passed by a Django view?
I am new to Django and I want to access the content of the context that was passed using view. I have city and locality in my model. I am trying to make dropdown in which user selects the city then locality and for that I used the following logic in views.py file views.py def homepage(request): restaurant=Restaurant.objects.all() city_list=[] locality_dict={} for object in restaurant: city_list.append(object.city) if object.city in locality_dict: locality_dict[object.city].append(object.locality) else: locality_dict[object.city]=[object.locality,] print(city_list) print(locality_dict) for item in locality_dict: locality_dict[item]=set(locality_dict[item]) city_list=set(city_list) print(locality_dict) context={'city_list':city_list,'locality_list':locality_dict} return render(request,'main/index.html',context=context) In my html template I am able to fetch city details from the context html file <select class="custom-select custom-select-sm" id="select_city" onclick="chooseCity()"> <option selected>Select your city</option> {% for item in city_list %} <option value="{{item}}">{{item}}</option> {% endfor %} </select> <br> <div id="locality" > <p id="paragraph" >City</p> <select class="custom-select custom-select-sm" > <option selected>Select your nearby locality</option> {% for item in locality_list %} <option value="{{item}}">{{item}}</option> {% endfor %} </select> </div> But when I try to fetch the locality using the city that was selected I get empty string. Suggest the solution js file <script type="text/javascript"> // myVarTest = myFunction( {{locality_list}} ); function chooseCity() { var temp=document.getElementById('select_city') var city = temp.options[temp.selectedIndex].value console.log("{{ locality_list.city }}") // {% endfor %} console.log(city) } </script> I … -
How do i start this, created the classes
My name is Federico I need to make a system for my company, we sell perfumes, in a first stage I only need an app where people can choose between 5 perfumes types, when they chose the type, the have to choose the "family" of the perfume, and then the perfume itself (name of the perfume), and this perfumes have a price so , for example: Perfume for pets (type) - puppys ("family") - citrus (the name of the scent) - 10 usd (price) for understanding how it works, first I want to make a web where i can order the products and they add up in a detailed order where I can see the products, the price, the total, etc, standard stuff, so I need this to add up and store in a form i think. I have created the class and they're like this : from django.db import models class TipoProducto(models.Model): nombre = models.CharField(max_length=20) precio_mayorista = models.IntegerField(default=0) precio_final = models.IntegerField(default=0) def __str__(self): return self.nombre class LineaProducto(models.Model): nombre = models.CharField(max_length=40) def __str__(self): return self.nombre class Productos(models.Model): aroma = models.CharField(max_length=30, null=False, blank=False) tipo = models.ForeignKey(TipoProducto, on_delete=models.CASCADE) linea = models.ForeignKey(LineaProducto, on_delete=models.CASCADE, null=True) def __str__(self): return self.aroma I would really apreciate if … -
Accessing Django HttpResponseRedirect cookies in Express endpoint
I have a use case where I set a cookie on Django HttpResponseRedirect which redirects to an expressjsendpoint. These services for now run on the same origin localhost but different ports. I set the cookies in Django as follows: class TestView(views.View): def get(self, request): response = HttpResponseRedirect("http://localhost:<expressPort>/testView") response.set_cookie(key='client', value=2) print(response.cookies) # Prints `Set-Cookie client=2; Path=/` return response The testView endpoint in express is written as: app.use(cookieParser()); app.get("/testView", (req, res, next) => { console.log(JSON.stringify(req.cookies)); // This prints an empty object {} next(); }); What am I doing wrong? How can I access the cookies from django in the express endpoint? -
How to Handle response messages in django rest framework like spintboot ? How to load it from a properties file?
How can we load error messages and other response messages load from the property file with internationalization in the Django rest framework? return HttpResponse('meesage should come here') I want to return a message not hardcoded -
Django: Passing an Object Variable from html form to views
I have a list of nested dictionaries that I am iterating through to create a html list. Each list entry has button, which on submit should trigger a function on views.py to create a django model object. How do I pass pass a dictionary as the post data when the button is pressed? {% if NewStudentsExists %} <div class="container-fluid m-3"> <h3>New Students</h3> </div> <div class="container-fluid m-1"> <ul class="list-group"> {% for NewStudent in NewStudents %} <li class="list-group-item">{{ NewStudent.name }} <div class="float-right m-1"> <form action="{% url 'add_student' %}" action="post"> <button type="submit" class="btn btn-sm btn-info" {{ NewStudent.Added }}> Add </button> </form> </div> </li> {% endfor %} </ul> </div> {% endif %} -
How to split django views request into several ones
I have Django app which makes lots of different analysis Here is the structure of the view: def analysis(request): making analysis 1 ... making analysis 2 ... making analysis 3 ... ........ making analysis 50 ... return render(request, 'checkapp/shots.html', var) The problem is that all these analysis takes about 1-2 minutes. While development I tested my app locally and it is working fine there. But when I deployed it on Heroku, it turned out, that heroku has 30 sec timeout limit. How can I split this process into several smaller ones, so I could get responses each 10 sec, for example? Or maybe there is some other solution for my problem? -
How to avoid saving subfolders when saving a file?
The function creates a folder and saves a file into it. Then the folder is packed into a rar archive and sent to the user, and the newly created folder and archive are deleted from the server after. code.py new_file_name = self.generate_file_name(rfi, vendor, current_scoring_round) path_to_temp_folder = os.path.dirname(BASE_DIR) if not os.path.exists(f'{path_to_temp_folder}/temp_folder'): pathlib.Path(f'{path_to_temp_folder}/temp_folder').mkdir(parents=True, exist_ok=True) wb.save(f'{path_to_temp_folder}/temp_folder/{new_file_name}') #save xlsx file from openpyxl library archive = self.generate_zip_name(rfi) # generate name for archive to_rar = f'{path_to_temp_folder}/temp_folder' patoolib.create_archive(archive, (to_rar,)) # patoolib - to .rar converter to_download = f'{path_to_temp_folder}/{archive}' if os.path.exists(to_download): try: with open(to_download, 'rb') as fh: response = HttpResponse(fh.read(), content_type="content_type='application/vnd.rar'") response['Content-Disposition'] = 'attachment; filename= "{}"'.format(archive) return response finally: shutil.rmtree(to_rar, ignore_errors=True) default_storage.delete(to_download) Everything work, but the problem is that the downloaded archive contains subfolders - paths to the saved file. Expected result: folder.rar file.xlsx Actual result: folder.rar /home /y700 /projects file.xlsx -
django adding multiple model image instances using form
I want to save 400 picture to my Image model using one single file field and i dont know how tp get each image from the form and create an instance on the Image model here is my model function: class Image(models.Model): image = models.ImageField(null=True, blank=True) and here is my form: class AddImageForm(forms.ModelForm): image = forms.FileField(widget=forms.FileInput(attrs={'class':'form-control','multiple':'true'})) class Meta: model = Image fields = ['image'] and here is my view which i know is wrong just to make sure i share everything: def imagesform(request): form = AddImageForm() if request.method == 'POST': if form.is_valid(): for i in form['image']: Image.objects.create(image=i) context = {'form':form} return render(request, 'members/imagesform.html', context) -
"TemplateDoesNotExist at / home1.html"whereas {%load static%} creating 'UNWANTED TOKEN ' error in <DOCTYPE html>
I am getting error in my HTML file'home.html' when I add {% load static %} command at the first row, it shows an error as UNWANTED TOKEN ON I am new to the pyhton and learning from online classes , whenever i enter load static static file an error comes out on doctype html with ziggly red line ,I dont know how to solve it and when i run server it gic=ves me this :- TemplateDoesNotExist at / home1.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.6 Exception Type: TemplateDoesNotExist Exception Value: home1.html Exception Location: C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\admin\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\admin\\PycharmProjects\\magezine\\telusko', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\admin\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages'] MY HTML file error <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> settings STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MY project name is telesko and installed app name is travello -
Django: Cannot assign "<Booking: loader2>": "Booking.b_price" must be a "Loader_post" instance
Hi am working on a project where user upload the post, on the other hand, the driver checks the user post and adds price on a particular post , then user sees that a driver add a price on his post, then user can reject or accept that price, when it going to accept the price it gives an error, now my question is am passing a primary of a particular post of the user ...when driver add the price then it selects the same primary key of the post but when it going to accept the post pk is changed this is first models of user post class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) this is my second model where the pk is used in second model class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE,null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) now the view of that model @login_required def add_price_to_post(request, pk): post = get_object_or_404(Loader_post, pk=pk) user = request.user if request.method == "POST": form = price_form(request.POST) if form.is_valid(): ps = form.save(commit=False) ps.user = request.user ps.status = True ps.my_post = post ps.save() return redirect('Driver:Driverview') else: form = price_form() return … -
Django foreignkey insert data
Why i cant get the ID and save it to the database? eventhough i already display it in my html. in my window html, i already display the id of payment <h3><b>Payment Type</b></h3> <select id="payments" name ="payments" onchange="payment(this.value)" style="border-radius:8px 8px 8px 8px; outline: none; padding:4px 10px 4px 10px" required> <option value="0">-- Payment Type --</option> {% for paymentschedule in payment %} <option value="{{paymentschedule.Payment_Type.id}}" name ="payments">{{paymentschedule.Payment_Type.id}} {{paymentschedule.Payment_Type}}</option> {% endfor%} </select> That 1 number is the ID this is my logic on how to save in my database id = request.POST.get('payments') payment = PaymentType(id=id) V_insert_data = StudentsEnrollmentRecord( Payment_Type=payment, ) V_insert_data.save() this is the error says did i miss something?