Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ignore queryset filter based on field value, django
I have: today = timezone.now() Product Model: id = Integer (PrimaryKey) expiry = Date (not DateTime) allow_below_zero = Boolean (if quantity can fall below zero) stock = Integer (quantity of product) price, size... etc Now I want to filter products where stock__gte=0 and expiry__gte=today but on a condition, if allow_below_zero for product is true then ignore stock__gte=0 else condition stock__gte=0 holds, I was thinking of using allow_below_zero__in but that wouldn't help. Simply filter product for given store_id, and expiry__gte=today and check stock__gte=0 only if allow_below_zero is False else check for stock. The first 2 constrains are simple, how do I ignore queryset filter based on field value. Or an SQL query will be helpful. Am trying to get product id's or name, point is ignoring filter on condition. -
Would it be advisable to upload my Django Project to github?
I know that Django websites contain a secret key which is not to be disclosed to anyone. However, I really want to showcase my website on GitHub, as I feel it is nice. Unfortunately, I am worried about the secret key's security, and if it would be safe to upload that website to GitHub where everyone can see. The website type is a personal portfolio website that showcases my projects and more. So, would it be okay to upload my entire Django Project to GitHub? The only sensitive information I can think of would be my superuser information, and maybe my database, where I store all my project Models for displaying on the website. Pretty much all I know I need to guard is my superuser information -
Django failed to build wheel for python-ldap
I'm new to Python Django, I have integrated my Django application on Windows 7 machine. When I tried to integrate LDAP by using pip install django-auth-ldap but unfortunately I got an error Failed building wheel for python-ldap Running setup.py clean for python-ldap Failed to build python-ldap django-python3-ldap 0.11.1 has requirement pyasn1==0.3.2, but you'll have pyasn1 0.4.4 which is incompatible. Please help me to escape me from this issue, bcz I have been struck here for a couple of days -
How to pass post data with redirect in django
I am using third party payment gateway for receiving payments, for that I have to post some data to payment gateway url, but the problem is, in that form I am having some sensitive data also. This is my Html code for posting data: <form action="https://test.payu.in/_payment" name="payuForm" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="pOz2jZlcwLuLJRfBor9xqr4KIXtqGUCmcUSdZl6QeIXZnKc00ApNU2BxInA94Esy"> <input type="hidden" name="key" value="123456789"> <input type="hidden" name="hash" value="98231e7321875de86639070b07a1940effad7cac37e15e277f62e6d9c9488085cd060a3b9963864f2b10a334f2c04be4387b3fe24422d01cf5ed49d1a54c39f0"> <input type="hidden" name="txnid" value="833657e26b12fde34b620c67a3a8646c"> <input type="hidden" name="amount" value="1.0"> <input type="hidden" name="email" value="pankaj@gmail.com"> <input type="hidden" name="firstname" value="Pankaj"> <input type="hidden" name="phone" value="9950542612"> <input type="hidden" name="productinfo" value="Message showing product details."> <input type="hidden" name="surl" value="http://127.0.0.1:8000/orders/payment/success"> <input type="hidden" name="furl" value="http://127.0.0.1:8000/orders/payment/failure"> <!-- <input type="hidden" name="service_provider" value="" /> --> <div class="form-group"> <div class="col-md-12 col-sm-12"> Amount : 1.0 </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Purpose : Message showing product details. </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Name : Pankaj </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Email : pankaj@gmail.com </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Mobile : 9950542612 </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> Transaction ID : 833657e26b12fde34b620c67a3a8646c </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12" style="padding-bottom:20px;padding-top:20px;"> After clicking 'Pay Now' button, you will be redirected to PayUMoney Secure Gateway. </div> </div> <div class="form-group"> <div class="col-md-12 col-sm-12"> <input type="submit" class="btn btn-success btn-sm" value="Pay Now"> </div> … -
invalid keyword argument in django for course_id
I am trying to populate a models.table with data but I have an error TypeError: 'course_id' is an invalid keyword argument for this function models.py class Course(TimeStampedModel, models.Model): course_id = models.AutoField(primary_key=True), title = models.CharField(verbose_name=_(u"title"), max_length=40, blank=True, null=True) example of data(dataframe ==) Course Code title 719176 lorem ipsu #1 719177 lorem ipsu #2 script for i in range(0, len(df1)): all_courses_ids = [l.course_id for l in Course.objects.all()] if( df1.iloc[i]['Course Code'] not in all_courses_ids): Course.objects.create( course_id=df1.iloc[i]['Course Code'] ) Error <ipython-input-2-0a2a41ded7eb> in <module>() 3 if( df1.iloc[i]['Course Code'] not in all_courses_ids): 4 Course.objects.create( ----> 5 course_id=df1.iloc[i]['Course Code'] 6 ) 7 ... ... TypeError: 'course_id' is an invalid keyword argument for this function -
Django | Aggregate Values from Foreign Key
I have two databases, A and B. B contains a ForeignKey to A. When I do B.objects.filter(a_id=3).values('bags').count(), I get the number I want, Y. What is the set of commands I need in order to add this number, Y, as an annotation into database A? Ideally, this would be an annotate type of command. -
Django CMS - Clients Account
I'm new to python and Django CMS. I want to create a website where users can log in and update their own profile information, but cannot edit the website. I'm just wondering if it's possible to integrate an account system in Django CMS. If yes, how? Thank you. -
anaconda navigator trouble shotting
Idk why my anaconda navigator won't work anymore! showed sth like: Navigator Error An unexpected error occurred on Navigator start-up Report Please report this issue in the anaconda issue tracker Main Error byte indices must be integers or slices, not str Traceback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\exceptions.py", line 75, in exception_handler return_value = func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 115, in start_app window = run_app(splash) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\app\start.py", line 58, in run_app window = MainWindow(splash=splash) File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window.py", line 160, in init self.api = AnacondaAPI() File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\anaconda_api.py", line 1205, in AnacondaAPI ANACONDA_API = _AnacondaAPI() File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\anaconda_api.py", line 65, in init self._conda_api = CondaAPI() File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\conda_api.py", line 1622, in CondaAPI CONDA_API = _CondaAPI() File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\conda_api.py", line 340, in init self.set_conda_prefix() File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\conda_api.py", line 489, in set_conda_prefix self.ROOT_PREFIX = info['root_prefix'] TypeError: byte indices must be integers or slices, not str enter image description here -
Inconsistent data between database and django-shell
When I look in my the databse via the MySql shell I see N records on a model, and when I look in the django admin I see those same data. However, when I try ModelName.objects.all() in the django shell, it only shows N-2 records. Similarly, when I wrote a custom managemnt command, and call ModelName.objects.all() it only presents a subset of those N records. Any thoughts? -
Docker dev environment, pylint unable to import error
I have a problem, I have been using a docker environment for my django 2.0 project and pylint was working fine but now it's showing the unable to import module error. I'm aware that the import error question has been asked many times but it was always for a venv setup rather than docker environment setup. I'm not sure what triggered the error, but possibly because I deleted my old containers, volumes, images and started from scratch. I'm using Python 3 and VSCode. Thanks in advance if anyone can help. -
Django: Preventative measures for SQL Injection
I have a few text fields in my django project and I've been learning about SQL injection. Is it important to strip the text fields of potential bad characters taht might make SQL injection easier? I imagine stripping possible bad characters such as { ;, but I am not sure. These fields are short bios about a person or a contact page and so I don't imagine that they would require such characters. To be clear, I have taken other steps to protect my website such as am using these fields things such as generating dynamic sql queries. -
How to sum values based on filter and group by Year-Month
I have the following table: 2018-01-01 ------- 10 2018-01-15 ------- 20 2018-01-31 ------- 30 2018-02-01 ------- 10 2018-03-01 ------- 10 2018-03-20 ------- 20 I need to Sum the values filtering it with 1 - sum(values) where date < the first day of the month 2 - sum(values) where date < last day of the month Expected result(something like that): [ {'year-month': '2018-01'}, {'sum_before_month_day_one': 0}, {'sum_before_last_month_day': 60}, {'year-month': '2018-02'}, {'sum_before_month_day_one': 60}, {'sum_before_last_month_day': 70}, {'year-month': '2018-03'}, {'sum_before_month_day_one': 70}, {'sum_before_last_month_day': 100}, ] So far I manage to sum values and group by month: In [12]: result = Sale.objects \ ...: .annotate(date=TruncMonth('event_date')) \ ...: .values('date') \ ...: .annotate(quantity=Sum('quantity')) \ ...: .values('date', 'quantity') \ ...: .order_by('date') In [13]: for i in result: print(i) {'date': datetime.date(2018, 1, 1), 'quantity': 60.0} {'date': datetime.date(2018, 2, 1), 'quantity': 10.0} {'date': datetime.date(2018, 3, 1), 'quantity': 30.0} -
Relative import beyond top-level package Error
I have a project named tweetme which has two apps account and tweets,i have serializers.py file in both of the apps to serialize data. So when i try to relative import the serializer class from account/api/serializers.py to another app tweets/api/serializers.py, the relative import shows error. 1- 1st i tried full path from src.account.api.serializers import UserDisplaySerializer, it gave error in console that ModuleNotFoundError: No module named 'src' 2- Then i tried from ...account.api.serializers import UserDisplaySerializer,its showing error ValueError: attempted relative import beyond top-level package. So what am i doing wrong? How to do relative import properly? [![User Serializer class in account app][4]][4] -
DRF Model permissions fail for LDAP auth'd users
I'm working on an application with a DRF base, requiring LDAP authentication. I have run across a problem, by which I am seeing different behaviours for users logging in directly via the DRF API and those accessing it from an external application - ie Curl/Postman. In the application, once logged in I present a series of views/urls that users can access, ie the url below to view 'samples': http://:8000/api/samples I have applied DjangoModelPermissions using a custom permission class to my Sample view which requires model permission to view the model, ie: class HasModelPermission(permissions.DjangoModelPermissions): perms_map = { 'GET': ['%(app_label)s.read_%(model_name)s'], 'OPTIONS': ['%(app_label)s.read_%(model_name)s'], 'HEAD': ['%(app_label)s.read_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class SampleView(generics.ListAPIView): queryset = Sample.objects.all() serializer_class = SampleSerializer permission_classes = [HasModelPermission] As per https://django-auth-ldap.readthedocs.io/en/latest/permissions.html#group-mirroring, I've configured my ldap setup with AUTH_LDAP_FIND_GROUP_PERMS=true and have created matching DJANGO groups for LDAP groups I care about - and I have allocated model permissions to these groups. This is working as I'd expect - only users who are members of groups with permission to view the list are able to see it. The key issue I am seeing is that while the internal DRF API is correctly determining user permissions, users logging in … -
Send post request to django rest framework
I'm trying to send a post request with file by using fetch api to django rest framework. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^lead/$', views.LeadListCreate.as_view()), url(r'^test/$', views.test, name='test') ] views.py from rest_framework import generics from rest_framework.decorators import api_view from rest_framework.response import Response from api.models import Lead from api.serializers import LeadSerializer, FileUploadFuelSerializer class LeadListCreate(generics.ListCreateAPIView): queryset = Lead.objects.all() serializer_class = LeadSerializer @api_view(['POST']) def test(request): print(request.data) print(type(request.data['file'])) serializer = FileUploadFuelSerializer(data=request.data) if serializer.is_valid(): # serializer.save() print('ok') return Response({'res': 'Everything's ok'}) print(serializer.errors) return Response({'res': 'none'}) serializers.py from rest_framework import serializers from api.models import Lead, FileUploadFuel class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' class FileUploadFuelSerializer(serializers.ModelSerializer): class Meta: model = FileUploadFuel fields = '__all__' models.py from django.db import models class Lead(models.Model): name = models.CharField(max_length=100) email = models.EmailField() message = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) class FileUploadFuel(models.Model): file = models.FileField(upload_to='fuel/') My request handleSubmit = (event) => { event.preventDefault(); let body = new FormData() body.append("file", this.state.file) fetch("/api/test/", { body, headers: new Headers({ "Cache-Control": "no-cache", "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", }), method: "POST" }).then(res => { console.log(res.status) return res.json() }).then((data) => { console.log(data) }).catch(err => console.log(err)); } When I send request by using postman, it works. And the type of request.data['file'] is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> … -
Heroku is unable to install the dependencies in my "requirements.txt" when pushing my django project
Whenever I try pushing my Django project to Heroku, I see errors referring to the dependencies listed in my "requirements.txt" file(for example: Collecting anaconda-client==1.6.9 (from -r /tmp/build_45e030bb239f553887437d4bfa754b90/requirements.txt (line 2)) remote: Could not find a version that satisfies the requirement anaconda-client==1.6.9 (from -r /tmp/build_45e030bb239f553887437d4bfa754b90/requirements.txt (line 2)) (from versions: 1.1.1, 1.2.2) remote: No matching distribution found for anaconda- client==1.6.9 (from -r /tmp/build_45e030bb239f553887437d4bfa754b90/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. I should note that I forgot to setup a virtual environment before creating my project(I'm just beginning to see what a big mistake that may have been). Could this be what's causing me problems? Is it too late to set up a virtual environment now that the project has been completed and is ready for production? If that isn't the problem, do I maybe need to update or install something? I apologize if this has already been answered or if its a stupid question, but Heroku support was unable to help me out and I wasn't able to find a solution on here. Any input or suggestions would be immensely appreciated. -
Django where is celery task information saved?
I am wondering where the celery task info. is saved. I checked the tables in the database and find no relevant items. It seems when I shut down the local server and restart it later, celery knows the tasks which are in the queue. -
Data from PostgreSQL sql not all inserting to another Sql Server DB
I have to manually push data from my django app to be inserted on another DB which using using another desktop application . Nearlly all the data saved on my postgress db for that particular id is inserted on that other DB . But it seems only one data is missing. Could it be that i have not set any Connection timeout on my setting.py file fro my DB . -
Fork a Python subprocess to survive interpreter, SSH death, nuclear war
This has been a two day struggle, and I am quite stuck. TLDR: From within a Python shell (>>> "like this"), start a Python script that survives quit() and me@terminal:~$ exit. I have tried: various daemonizing functions that implement os.fork() creating/calling a shell script with Popen and & appended subprocess.Popen(["nohup", "command.py"]) in several forms Toy Code - Python 3.6 class MyClass(threading.Thread): def __init__(self, filepath): super().__init__() self.filepath = filepath def run(self): import time i = 0 while True: # Count to 50 in a file forever if i > 50: i = 0 with open(self.filepath, "a") as afile: afile.writelines("This is msg {}\n".format(i)) i += 1 time.sleep(1) How can I run this Thread from within the Python shell in such a way that it doesn't die when I close my interpreter and close my SSH terminal? Real Code Django-managed DB consumption of PubNub messages See # TODO line, near center. The PNRunner class instances will be started and killed dynamically within the construct of a Django app, so I can't just start them at boot with a shell script. -
Django PostgreSQL filter vs exclude performance
Suppose I have the following model: class Fruit(models.Model): flavor = models.CharField(max_length=20) flavor can be either sweet, sour, or bitter Let's say I want to find all the fruits that are sweet. Is there a significant performance difference between the following operations? Fruit.objects.filter(flavor='sweet') Fruit.objects.exclude(flavor='sour').exclude(flavor='bitter') -
Django: perform action after related objects are saved
I have two models: class Author(models.Model): name = models.CharField(max_length=100) create_report = models.BooleanField(default=False) class Book(models.Model): author = models.ForeignKey(Seller, on_delete=models.PROTECT) title = models.CharField(max_length=100) They are registered in admin like this: class BookInline(admin.TabularInline): model = PurchaseOrderItem @admin.register(PurchaseOrder) class AuthorAdmin(admin.ModelAdmin): inlines = (PurchaseOrderInline,) I create an author and two books through Django admin. After I hit the 'Save' button, if Author.create_report == True I would like to see a report saying the following: Author However-he-is has written the following books: Title-of-the-first-book Title-of-the-first-book (Where the raport should appear or how to render the template are not relevant questions here, let's skip them.) My first idea was to overwrite Author.save() method: def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.create_report: self.write_report(name=self.name, books=self.book_set.all()) The problem is that Author.save() method is executed before Book objects are saved and so self.book_set.all() is empty. One workaround would be to use some other ModelAdmin function (for instance log_addition()), which fires after Book objects are saved, but as I wish to use the same functionality out of admin, too, it is not the best solution. Can I somehow achieve the result without using the admin layer functions? -
Filters chain rather than Q() combination in Queryset
I have an article model with m2m relationships to model Tag, I intend to filter articles which have tags both "python" and "django" I tried Q along with & In [184]: from django.db.models import Q In [185]: articles = Article.objects.filter(Q(tags__name="python") & Q(tags__name= ...: "django")) In [186]: articles Out[186]: <QuerySet []> It return a null Queryset Alternatively I tested In [202]: articles = Article.objects.filter(Q(tags__name="python")).filter(Q(tags_ ...: _name="django")) In [203]: articles Out[203]: <QuerySet [<Article: Test new tags>, <Article: Django Tutorial>]> I worked and solved the problem. However, I am very confused with the failing of Q()&Q(), should I alway utilize filter chain rather than Q() combination to avoid mistakes? -
django - nginx - "ERR: TOO MANY REDIRECTS"
I'm having an issue with my nginx configuration. I receive the error ERR: TOO MANY REDIRECTS If I change the var SECURE_SSL_REDIRECT = True to False the error goes away but I believe this is causing issue with my channels setup, my websockets are unable to complete handshake. I found this link which I think is my problem but I don't know how to fix it. I tried changing proxy_pass http://unix... to https://unix... which causes the redirects to stop but the page won't load. server { server_name myproject.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/xx/myproject/static/; } location /static/admin/ { alias /home/xx/myproject/static/admin/; } location /media/ { alias /home/xx/myproject/media/; } location / { include proxy_params; proxy_pass http://unix:/home/xx/myproject/myproject.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/myproject.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/myproject.com/privkey.pem; # managed by Certb$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = myproject.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name myproject.com; return 404; # managed by Certbot } -
Django Doesn't serve CSS code From Static Folder
Need some help with django. Seems that somehow i can't change the css of my home page. These are my static settings: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") In my index_home.html page i want to put a background image e.g. marea.jpg which is in static/img/marea.jpg. {% load staticfiles %} {% load static %} <!--DOCTYPE html --> <html> <head> <title>Romanii din Italia</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous"> <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' > <script src="http://code.jquery.com/jquery-1.12.2.min.js" integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js'></script> <link rel='stylesheet' href='{% static "css/base.css" %}' /> </head> <body> <div class='container'> <ol class='breadcrumb'> <li><a href='{% url "posts:home" %}'>Acasa</a></li> <li><a href='{% url "posts:list" %}'>Stiri</a></li> {% if not request.user.is_authenticated %} <li class='pull-right'><a href='{% url "register" %}'>Register</a></li> <li class='pull-right'><a href='{% url "login" %}'>Login</a></li> {% else %} <li class='pull-right'><a href='{% url "logout" %}'>Logout</a></li> {% endif %} </ol> </div> <div class="container" id="primapoza"> <h2>Bine ati venit pe site-ul romanilor din Italia!</h2> <img src="static/img/roma.jpg" %}, class="img-fluid"> <div class="row"> <div class="col-xs-12 offset-xs-0 col-sm-12 offset-sm-4" > … -
Django - Forms - autofill & hide foreign key field
I have models.py, and forms.py that looks like this: class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) depth_in = models.CharField(max_length=111) depth_out = models.CharField(max_length=111) class BHA_overall_Form(forms.ModelForm): class Meta(): model = BHA_overall fields = '__all__' In my template, if I just use: <form method="POST"> {% csrf_token %} {{ form.as_p }} <button name='action' value='login' type="submit">Sign in</button> </form> the foreign key field bha_number is displayed as a combo box where I can select the specific bha_number model instance it belongs to, like this: Here, I want to remove Bha number field from the user side, and just let my code auto fill that field for the user, and hide it. So from the user side, there will be only 3 fields displayed. How can I do this? Here is my views.py: class BHA_UpdateView(UpdateView): model = BHA_List success_url = reverse_lazy('well_list') # this is wrong form_class = BHA_overall_Form def post(self, request, **kwargs): api = get_well_api(self.request) current_bha = BHA_List.objects.filter(id=get_current_bha_id(self.request))[0] form = BHA_overall_Form(request.POST, instance=BHA_overall.objects.filter(bha_number__well__api=api, bha_number=current_bha)[0]) if form.is_valid(): form.save() return super().post(request, **kwargs)