Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hi, I want to add trainer model to django , so I start to download "tensorflow" library in command line , but it gives me errors
I use python 3.9 and i work on windows 10 what steps to let the code about machine learning execute? what libraries I need to run a classification image model in django ? I am so confused and do I need jupyter? and is django rest framework is necessary to run !! -
Is there a way to call form values into checkbox value
I want to get value of {{form.tag_af}} into the value of checkbox as show on image enter code here <div class="form-group row"> <label class="col-sm-2 col-form-label">tag_af:</label> <div class="selected col-sm-4"> {{ form.tag_af }} </div> <input type="checkbox" class="checkboxstyle" id="tagaf" value="id_tag_af" />Include in ItemName<br> What I need is the value of {{form.tag_af}} to be given to checkbox value As I want to call this checkbox value to append to a final item list In current situation instead of the value of {{form.tag_af}} id_tag_af is printed as it is -
multi-filter search in django not working
There are 3 filters namely description, categories and locations. For description, I want to search a job by a company name, job title or job description. Even if the user inputs, "company name and job title", i should retrieve a correct match not exactly but somewhat close. How do I get this? models.py class Internship(models.Model): recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True) internship_title = models.CharField(max_length=100) internship_mode = models.CharField(max_length=20, choices=MODE_CHOICES) industry_type = models.CharField(max_length=200) internship_desc = RichTextField() class Recruiter(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) company_name = models.CharField(max_length=100) views.py def user_search_internship(request): if request.method == "POST": internship_desc = request.POST['internship_desc'] //can be title, desc, company or a combo internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] internships = Internship.objects.all() if internship_desc != "" and internship_desc is not None: internships = internships.filter(internship_title__icontains=internship_desc) context = { } return render(request, '', context) -
"Mpesa.Paid_user" must be a "User" instance. - Repost
I would like to save to the database the currently logged-in user but I keep getting the same error AnonymousUser although the user is logged in, I am using the custom user model and I cannot find a solution anywhere, I would be grateful for any assistance. below are some snippets. views.py our_model = Mpesa.objects.create( Paid_user = request.user, MpesaReceiptNumber = mpesa_receipt_number, PhoneNumber = phone_number, Amount = amount, TransactionDate = aware_transaction_datetime, ) our_model.save() models.py class Mpesa(models.Model): Paid_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) MpesaReceiptNumber = models.CharField(max_length=15, blank=True, null=True) PhoneNumber = models.CharField(max_length=13, blank=True, null=True) Amount = models.IntegerField(blank=True, null=True) TransactionDate = models.DateTimeField(blank=True, null=True) Completed = models.BooleanField(default=False) -
"unresolved library" warning in pyChram working with User Filters in Django
I've made a simple user filter to add class styles to form fields. The code works well, but pyCharm shows a warning: Fliter code is: from django import template register = template.Library() @register.filter def addclass(field, css): return field.as_widget(attrs={"class": css}) Template code is: {% extends "base.html" %} {% block title %}Зарегистрироваться{% endblock %} {% block content %} {% load user_filters %} ... <div class="col-md-6"> {{ field|addclass:"form-control" }} ... And the warnings are: {% load user_filters %} and {{ field|addclass:"form-control" }} -
How to make my ManytoMany field not automatically populate
Hi so i am working on commerce from cs50 web development. I currently have a problem where when i create a new listing, my auction.watchlist (which is a manytomany field) automatically populates itself with all the users when i want it to be blank.) This is my models.py class User(AbstractUser): pass class Auction(models.Model): title = models.CharField(max_length=64) description = models.TextField() starting_bid = models.DecimalField(max_digits=10, decimal_places=2,null=True) highest_bid = models.DecimalField(max_digits=10, decimal_places=2, null=True) creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name="my_listings", null=True ) created_date = models.DateTimeField(auto_now_add=True) current_winner = models.ForeignKey(User, on_delete=models.PROTECT, related_name="my_winnings", null=True) image = models.URLField() category = models.CharField(max_length=64, null=True) watchlist = models.ManyToManyField(User, related_name="my_watchlist", blank=True) This is my views.py def create_listing(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] bid = request.POST["bid"] image = request.POST["image"] category = request.POST["category"] creator = User.objects.get(id = request.user.id) try: listing = Auction.objects.create(title = title, description = description, starting_bid = bid, highest_bid = bid, image=image, category=category, creator = creator) except IntegrityError: return render(request, "auctions/create_listing.html", { "message": "Title already taken" }) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/create_listing.html") And this is my html file create_listing.html {% extends "auctions/layout.html" %} {% block body %} <h2>Create Listing</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'create_listing' %}" method="post"> {% csrf_token %} <div … -
How to get the list of durations of any two elements with common field value
data = [ { "id": '24', "deleted": 'null', "date_created": "2021-06-05T10:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '1', "field_target": "is_seen", "field_value": "false", "by": 'null', "related_to": 'null', "seen_by": '[]' }, { "id": '25', "deleted": 'null', "date_created": "2021-06-05T11:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '1', "field_target": "is_seen", "field_value": "true", "by": 'null', "related_to": 'null', "seen_by": '[]' }, { "id": '26', "deleted": 'null', "date_created": "2021-06-05T12:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '2', "field_target": "is_seen", "field_value": "false", "by": 'null', "related_to": 'null', "seen_by": '[]' }, { "id": '27', "deleted": 'null', "date_created": "2021-06-05T13:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '2', "field_target": "is_seen", "field_value": "true", "by": 'null', "related_to": 'null', "seen_by": '[]' }, ] df = pd.DataFrame(data) df['date_created'] = pd.to_datetime(df['date_created']) # pivot df = df.reset_index().pivot('object_id','field_target','date_created') print(df) Error ---> 64 df = df.reset_index().pivot('object_id','field_target','date_created') ValueError: Index contains duplicate entries, cannot reshape goal summary I need to konw the duration it take to field_value to change from false to true detail I need to get the list of durations of any two elements with common (have the same) object_id between changing the field_value from false to true df['durations'] = df['true'].sub(df['false']).dt.days print(df) You don't need this explanation but just because StackOverflow requires that I need the get the date_created time difference for every two elements that have the … -
can't create API endpoint djnago
I recently started learning python then moved to django and drf and came across a question (the title of this post) in which I had to create an POST endpoint which accept address in request body and returns longitude and latitude using geocoding api by google. I tried to do it with Django rest framework but in DRR have to create a model which is serialised to give us json output but here we already have an api(geocoding) . I wanted to ask how can we create a POST endpoint when we already have an existing api that we want to use to return a response I hope this question makes sense -
The 'header_image' attribute has no file associated with it
When I create a new post with a picture, everything is ok, but if I edit it, want to, for example, change the picture or delete, then this error appears here is models.py ` from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)])` here is views.py ` from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = ['title', 'author', 'body', 'header_image'] class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', 'body', 'header_image'] class BlogDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('home') @property def image_url(self): """ Return self.photo.url if self.photo is not None, 'url' exist and has a value, else, return None. """ if self.image: return getattr(self.photo, 'url', None) return None` post_base.html `{% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> … -
Django - most efficient way to get context of model in selected language
Let's suppose we have Author and Book models and we want our end-users to be able to select language (EN/FR) for displaying information. We have added language suffix (_en, _fr) to the fields we want to be translated. class Author(models.Model): first_name_fr = models.CharField(max_length=60) first_name_en = models.CharField(max_length=60) last_name_fr = models.CharField(max_length=60) last_name_en = models.CharField(max_length=60) class Book(models.Model): title_fr = models.CharField(max_length=60) title_en = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) In my views.py, I know I can get current language using get_language() (imported from django.utils.translation). Being new to Django, I am looking for the most efficient way to pass translated context to templates using a ListView. What I thought is overriding the get_context_data method to keep only fields in selected language and remove their suffix. But that could be somewhat complex (assuming we have model relationships) and I am not sure it's in the right direction. What would be the best practice for this? -
Django - show images with src from python list
I am trying to show few images on my website, I've collected the sources of all of them in a list. In html file I've created a loop to iterate through each of them. HTML body : <body> <div class="content"> {% for output in outputs %} <h1> {{ output }} </h1> <img src="{% static '{{output}}' %}" alt="Mountains" style="width:100%"> <img src="{% static 'images/1.jpg' %}" alt="Mountains" style="width:100%"> {% endfor %} </div> </body> So, the thing is - I am able to show image "1.jpg" from "images" directory (so the problem is not due to static files). I've also checked that "output" has the right content. This is the output of my code : enter image description here And this is directory where I store my images : enter image description here please, let me know if you have any idea what should i do next. Any advise will be helpful. -
(haystack with elasticsearch) {{ result.object.get_absolute_url }} doesn't work( I have get_absolute_url() method )
I have elastichsearch and haystack. I can search, autocomplete works just fine but when I get my search results I can't follow any link, they point to the same page I am on. This is my models.py: class Product(TranslatableModel): translations = TranslatedFields( category = models.ForeignKey(Category, related_name = 'products', on_delete = models.CASCADE), name = models.CharField(max_length = 200, db_index = True), slug = models.SlugField(max_length = 200, db_index = True) ) # image = models.ImageField(upload_to = 'products/%Y/%m/%d/', blank = True) description = models.TextField(blank = True) price = models.DecimalField(max_digits = 10, decimal_places = 2) available = models.BooleanField(default = True) created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args = [self.id, self.slug]) This is my search_indexes.py: from haystack import indexes from . models import Product, ProductTranslation class IndexProduct(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) description = indexes.CharField(model_attr = 'description') def get_model(self): return Product class IndexProductTranslation(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document = True, use_template = True) name = indexes.CharField(model_attr = 'name') name_auto = indexes.EdgeNgramField(model_attr = 'name') def get_model(self): return ProductTranslation I tried get_absolute_url() method in the shell: >>> from shop.models import Product >>> p = Product.objects.latest('id') >>> p.get_absolute_url() '/uk/shop/10/test/detail/' It doesn't even have anything in the href attribute … -
Update queryset with dictionary values
I am writing custom List filter and inside filter call i have a Django queryset as below queryset =[qs1, qs2, qs3] queryset have a attribute Count_val = 0, UUID = (unique id) for all objects in queryset so lets say qs1 = {uuid: 123, count_val: 0} qs2 = {uuid: 456, count_val: 0} qs1 = {uuid: 789, count_val: 0} Also I have a dictionary like {uuid: count_val} example {123: 5, 456: 10 , 789: 15 } I want to update queryset attribute count_values for all objects before returning queryset as response Maybe annotate but how i pull each uuid for each value queryset=queryset.annotate(count_val = Case(When(uuid_in=dictionary.keys(), then=dictionary[uuid]), field_type=Integer)) ## not correct syntax just an example # inserting to new field is also fine #queryset.extra(value={count_val : dictionary[uuid]}) return queryset Thanks for help -
Django admin panel css not working as expected in digital ocean server
I am trying to deploy django project in digital ocean ,my site’s css is working perfectly but my admin panel css is not working good, the dashboard of the datbase window overrides my entry page always before few days it seems to be working good but now the css makes the whole page messy enter image description here enter image description here -
How to get data from firebase database in Django Framework?
I am new to Firebase database and python. I am trying to get data from Firebase database in Django framework. It gives me order dictionary.I want feedback from the database.enter code here import pyrebase config={ "apiKey": "AIzaSyBQ_Lx4HC9aaElDShvQUE7AxCeCExC2R88", "authDomain": "eventmanagementdatabase.firebaseapp.com", "databaseURL": "enter your firebase url here", "projectId": "eventmanagementdatabase", "storageBucket": "eventmanagementdatabase.appspot.com", "messagingSenderId": "62525256630", "appId": "1:62525256630:web:e8750943665ef765430717", "measurementId": "G-J2R75159BC" } firebase=pyrebase.initialize_app(config) auth =firebase.auth() database=firebase.database() def postsign(request): email=request.POST.get("email") passw=request.POST.get("pass") d=database.child('YogaFeedback').get().val()[enter image description here][2] try: user=auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials" return render(request,"signIn.html",{"messg":message}) return render(request,"postsign.html",{"e":email,"feedback":d}) enter image description here enter image description here -
Refer an object that just after the current loop index in jinja
{% for i in posts %} {% if i.loop.index++.user == i.user %} <!-- Do something --> {% endif %} {% endfor %} posts is the variable that is being looped, it has a ForeignKey that is user. i.loop.index is evaluated as i.0, i.1, i.2 ..., I want the index just after the current loop index, if the index is i.0 I want i.1, to achieve that I am doing this {% if i.loop.index++.user %}, which should be evaluated to {% if i.1.user %} if 0 is the index. But it is not working Any help is highly appreciated! Thank you -
nginx API url https → http
Using nginx,AWS. javascript contains url as a variable. But the actual request url has been changed to https. Can't you just request it as it is in the variables? enter image description here -
Preventing race conditions when iterating through formset
I am a novice, I wrote a Django app over a year ago and it's been running ever since, however I have a problem with race conditions. I've read a few articles on Django race conditions but can't find a solution relating to formsets. My app has a web hook. My bank sends credit card transactions made on my card. My app lists the transactions which have not yet been imported (copied) into the financial journal table, lets me select which ledger they should go into, and then copies them over. It has to work this way as the bank lists the transactions in single entry format (one transaction, one line) whereas a proper financial book keeping app uses a more complex double entry format. The issue I have is that the copying is slow due to a large amount of logic needed, and if the import is triggered in another browser then transactions get copied over twice. The formset checks that the transactions are not yet imported as part of the is_valid() operation and then marks them as imported at the end. Whats' the best way to prevent race conditions here? def import_transactions(request): transactions = Transaction.objects.filter(imported=False) FormSet = modelformset_factory(Transaction, … -
Django auth_login giving Value error("cannot force an update in save() with no primary key.")
This Question is not similar to others who have answers. Recently I had changed my database engine to "Djongo" from "sqlite3". After finishing successful migrations and executing runserver command successfully, When I tried to log in Django admin I'm getting this error. Traceback Error: Environment: Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 3.1.7 Python Version: 3.9.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'map.apps.MapConfig', ] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "E:\atom_django\mapping\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\atom_django\mapping\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\contrib\admin\sites.py", line 410, in login return LoginView.as_view(**defaults)(request) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\contrib\auth\views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\generic\base.py", … -
How can I call a java script function from django html page?
Looking for help to call a java script function from a html page, I have no idea about java script. js function to be called window.purpose.postMessage({ type: 'collection' }, {accesstoken: '1234rr55r3'},'*'); my html page in which this js function needs to be called <!DOCTYPE html> <html> <head> <title>User Redirect</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body onload="document.frm1.submit()"> <form action="{{url}}" name="frm1" method="post"> <p>Please wait.......</p> <input type="hidden" name="customerName" value="{{postData.customerName}}" /> <input type="hidden" name="customerEmail" value="{{postData.customerEmail}}" /> <input type="hidden" name="customerPhone" value="{{postData.customerPhone}}" /> </form> </body> </html> -
I have getting a problem in django url when I am at url ...abc/pqr and I click on xyz than It is not getting to the ...xyz but ...abc/xyz
I am new to django and on this plateform so for now I dont know how to post a question here, but is someone see this please help. I am getting a problem in my project of college management system. I have try to add a assignment submition functionality in my project. In which a student will click on a assignment created by teacher which will land him to a page either submition page of assignment or if he already submitted that assignment than update or only showing information about that. ***this is my url file.*** urlpatterns = [... path('studentattendancereport', studentviews.student_attendance_report, name='studentattendancereport'), path('fetchstudentattendance', studentviews.fetch_student_attendance, name='fetchstudentattendance'), path('applyforleavestudent', studentviews.applyforleave, name='applyforleavestudent'), path('marksreportstudent', studentviews.marksreportstudent, name='marksreportstudent'), path('assignment', studentviews.assignments, name='assignment'), path('assignmentupload/<int:id>', studentviews.assignment_upload, name='assignmentupload'), ] ***this is my views.py*** def assignments(request): subject = Subject.objects.filter(course=Student.objects.get(admin=request.user.id).course) assignments = [] for s in subject: for a in Assignment.objects.filter(subject_id=s.id): assignments.append(a) context = {'assignments': assignments} return render(request, 'cmsapp/student/assignments.html', context) def assignment_upload(request, id): if request.method == 'POST': student_id = Student.objects.get(admin=request.user.id) assignment = Assignment.objects.get(id=id) assignment_file = request.FILES['assignment'] try: Student_Assignment.objects.create(assignment_id=assignment, student_id=student_id, document=assignment_file) messages.success(request, 'Assignment is submited successfully.') return redirect('assignment') except: messages.error(request, 'There is some problem, Please try again later.') return redirect('assignment') else: assignment = Assignment.objects.get(id=id) student_id = Student.objects.get(admin=request.user.id) assignment_report = Student_Assignment.objects.filter(assignment_id=assignment.id, student_id=student_id).first() if assignment_report: context … -
How to check if json data has empty value or not in django
I have created a CRUD application in Django. and want to know how I can check if the input JSON data is empty or not for example: I am getting a JSON input dictionary as {'firstname':'abc','lastname':'xyz','username':'abc@123','email':'abc@abc.com'} I want to check if username is not empty and email is not empty. I don't want a required field in model but to handle the JSON data. If the JSON input is not valid i.e if username and email is valid then save the data into database else give a warning 400. -
how to fix Pylance missingImports? cannot import my app.How to add extra paths in settings.json?
image image2 I cannot import my "todolist_app" in my "urls.py", I get the message "Import "todolist_app" could not be resolved Pylance(reportMissingImports)" the code in urls.py is from todolist_app import views from django.contrib import admin from django.urls import path urlpatterns = [ path('/', views.todolist, name='todolist') ] I don't know what the problem is. I'm new to coding. I tried to add path in settings.json { "python.pythonPath": "tmenv\\Scripts\\python.exe", "python.analysis.extraPaths": ["todolist_app","E:\Django Projects\Django_projects\\taskmate\\todolist_app"] } and I get an error "Invalid escape character in string.jsonc(261)" -
Django unable to send email behind nginx proxy
My django project sends email verification correctly till its not put behind nginx proxy, when i add a nginx proxy i am unable to send email, it sometimes sends as well sometimes it doesnt. it doesnt show any error in console Nginx config: upstream django { server unix://ucurs/ucurs.sock; # for a file socket } # configuration of the server server { # the port your site will be served on listen 7000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /log { access_log off; error_log off; uwsgi_pass django; include /ucurs/uwsgi_params; } # Django media location /media { alias /ucurs/media; # your Django project's media files - amend as required } location /static { alias /ucurs/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /ucurs/uwsgi_params; # the uwsgi_params file you installed } } Django library used for sending email : https://pypi.org/project/django-email-verification/ Django email config EMAIL_FROM_ADDRESS = 'noreply@ucurs.com' EMAIL_MAIL_SUBJECT = 'Confirm your email' EMAIL_MAIL_HTML = 'mail_body.html' EMAIL_MAIL_PLAIN = 'mail_body.txt' EMAIL_TOKEN_LIFE … -
How can i get the id related to specfifc user in django
I am trying to get the saloon id related to specific employee. After the login employee can add the service, but my filter query show the error "Field 'id' expected a number but got <bound method MultiValueDict.get of <QueryDict: {}>>." i don't know how can i get the saloon id Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() is_active = models.BooleanField(default=False) class SignUp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) contact_no = models.BigIntegerField() class Men(models.Model): saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Service = models.CharField(max_length=30) price = models.BigIntegerField() View.py class MenView(TemplateView): template_name = 'men.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): saloonId = SaloonRegister.objects.filter(signup__user__signup__saloon=self.request.GET.get) try: men = Men( saloon_id=saloonId, user_id=request.user, Service=self.request.POST.get('service'), price=self.request.POST.get('price') ) men.save() return redirect('saloonMenu') except Exception as e: return HttpResponse('failed{}'.format(e))