Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to sum up numbers in django
i want to calculate the total sales and display the total price, i dont know how to write the function to do this. I have tried writing a little function to do it in models.py but it working as expected. This is what i want, i have a model named UserCourse which stored all the purchased courses, now i want to calculate and sum up all the price of a single course that was sold. models.py class Course(models.Model): course_title = models.CharField(max_length=10000) slug = models.SlugField(unique=True) price = models.IntegerField(default=0) class UserCourse(models.Model): user = models.ForeignKey(User , null = False , on_delete=models.CASCADE) course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) and also how do i filter this models in views.py so i can display the total price of courses a particular creator have sold. -
Django error - QuerySet,Matching Query DoesNotExist
This is the Memo text where User can submit their Memo form. I need to add(update) new message this record via Update button in DJANGO,but when I sumbit it error: Query Matching Does Not Exist. by the way I used PK and FK db table. How can I modify it? Tks. Error Message : DoesNotExist at /addshowmemo/32/ Software matching query does not exist. Request Method: POST Request URL: http:/127.0.0.1/addshowmemo/32/ Django Version: 3.1.5 Exception Type: DoesNotExist Exception Value: Software matching query does not exist. Exception Location: d:\project\python\it\venv\lib\site-packages\django\db\models\query.py, line 429, in get Python Executable: d:\project\python\it\venv\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\project\python\it', 'c:\Users\tou52\.vscode\extensions\ms-python.python-2022.4.1\pythonFiles\lib\python\debugpy\_vendored\pydevd', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\tou52\AppData\Local\Programs\Python\Python310', 'd:\project\python\it\venv', 'd:\project\python\it\venv\lib\site-packages'] Models: class Memo(models.Model): notes = models.TextField() software = models.ForeignKey(Software, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return self.notes # QuerySet class Software(models.Model): STATUS_CHOICES = [ (0, 'Planning'), (1, 'Development'), (2, 'Using'), (3, 'Obsolete') ] name = models.CharField(max_length=100, verbose_name="SysName") url = models.CharField(max_length=100, verbose_name="SysAdd") status = models.PositiveIntegerField(default=0, choices=STATUS_CHOICES, verbose_name="Status") company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Company") team = models.ForeignKey(Team, on_delete=models.DO_NOTHING, verbose_name="Team") def __str__(self): return self.name # QuerySet Templates: <form method="POST" name="myform" action="." > {% csrf_token %} <table class="table table-striped"> <tr> <td align=right>Memo:</td> <td> <input type=text size=50 name="Cmemo" value='{{Nmemo.notes}}'> </td> </tr> <tr> <td> </td> <td> <input type=submit value="Confirm" class="btn btn-primary">||<a … -
return self.cursor.execute(sql, params) django.db.utils.DataError: value too long for type character varying(3)
This happens after python manage.py makemirgations which works okay. Then when I run python manage.py migrate I get this error. I've tried changing the max_length in the charfield, same error. I tried deleting and changing the default value and null and run makemigrations which states no change detected. class Casting_Role(models.Model): name = models.TextField() min_age = models.IntegerField(default='18', blank=False) max_age = models.IntegerField(default='100', blank=False) ETHNICITIES = ( ('BA', 'Black / African Descent'), ('WC', 'White / European Descent'), ('A', 'Asian'), ('H', 'Hispanic'), ('I', 'Indian'), ('ME', 'Middle Eastern'), ('PI', 'Pacific Islander'), ('EA', 'Ethnically Ambiguous'), ('IP', 'Indigenous People'), ('OP', 'Open'), ) ethinicity = models.CharField( max_length=30, choices=ETHNICITIES, default='Open') -
Django: Alert the user that he hasn't yet completed something specific in the app
I would like to create a feature that alerts the user that he has not completed his profile. Just like it is on LinkedIn. Any ideas how to do this in Django? -
Element added to DOM has HTML / SVG attributes, but not the corresponding JS properties
I am using HTMX with Django to render a page which is basically an SVG with a lot of sticky notes () that you can move around on the page, like you might use for brainstorming. When you edit the text, htmx POSTs that back to a Django view which returns the updated content. This is the Django template for a single form: <g id="g1-{{form.instance.pk}}" hx-post="{% url 'architech:updatetech' form.instance.map.pk form.instance.pk %}" hx-swap="outerHTML" hx-trigger="focusout" hx-include="#fo-{{form.instance.pk}}"> <g id="g2-{{form.instance.pk}}" transform="{{form.instance.presentation|safe|default:"matrix(1,0,0,1,50,50)"}}" class="ui drags" draggable="true"> <foreignObject id="fo-{{form.instance.pk}}" height="203" width="319"> <form class="card" id="form-{{form.instance.pk}}" draggable="true"> <div id="header-{{form.instance.pk}}" class="card-header" draggable="true"> {{ form.name.errors}} {{ form.name }} {{ form.presentation }} <input type="button" value="x" hx-post="{% url 'architech:deletetech' form.instance.map.pk form.instance.pk %}" hx-swap="outerHTML" hx-target="#g-{{form.instance.pk}}" hx-trigger="click"> </div> <div id="body-{{form.instance.pk}}" class="card-body" draggable="true"> {{ form.notes.errors}} {{ form.notes }} </div> </form> </foreignObject> </g> </g> I've been using hx-swap="outerHTML" (and more recently "morphdom") to re-render and replace this block of code. When its reloaded, the same SVG/HTML doesn't get rendered correctly or respond to javascript. The key element is the second group, with id beginning g2. When loaded with the whole page, height and width are honored, and attributes like 'transform' are accessible with element.transform: # console interaction on initial state using 'save to a global variable' >temp1 … -
Static File Hosting, WhiteNoise not Updating - Django
I have a Django website in production and a while back I successfully hosted my static files using Whitenoise so I could use them in production. Now a few months later I want to add a new .png along with a bunch of other code and push it to production. I added the .png I wanted into my static files then deleted my 'staticfiles' folder in my code and reran python manage.py collectstatic. The files all collected like normal but when I ran my local server the page is no longer hosting that new .png using whitenoise. All the other static files that were hosting successfully before are STILL hosting fine now and being hosted by whitenoise. Its just the new one that is not being hosted through whitenoise. I checked the 'static files' folder and the new .png is in there fine with a copy of itself and additional characters added to its name like whitenoise usually does and like how all the other files are that are being successfully hosted. How do I update/refresh Whitenoise to acknowledge a new static file added? Thanks! -
How do I clean multiple files at once on a FileField with multiple attachments?
I am looking to throw a validation error if the user tries to upload more than 1 video file (they are allowed to upload more than 1 image). Here is the code for the field: media = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), label="Add image/video", required=False, validators=[validate_file_size, validate_file_extension], ) I am able to go through each file one by one using a validator on the field (checking the file extension of each file), or by using the clean function. -
Making an instagram story using rest framework django
How can i make an Instagram story using rest framework Django How can anyone make a story and how can every body in app see it -
compare between 2 codes in django
I want to add (add comment form) but I face a problem in views.py you will see codes down below. in views.py there are 2 different codes 1- that code works for me 2- that code didn't work with me and I want to know why code num 2 didn't work with me # in models.py class Comment(models.Model): user = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE) product = models.ForeignKey(Product, verbose_name="Product", on_delete=models.CASCADE, related_name="comments") is_active = models.BooleanField(verbose_name="Is Active?",default=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created Date") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated Date") content = models.TextField(verbose_name="comment") # in forms.py class AddComment(forms.ModelForm): content = forms.CharField(label='التعليق', widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder':'ما رأيك في المنتج؟'})) class Meta: model = Comment fields = ['content',] and # in urls.py path('product/<slug:slug>/', views.detail, name="product-detail"), and # in details.html {% if request.user.is_authenticated %} <form action="" method="post"> {% csrf_token %} {{AddComment}} <br> <input type="submit" value="إرسال"> </form> {% endif %} now my problem in views.py # in views.py def detail(request, slug): product = get_object_or_404(Product, slug=slug) related_products = Product.objects.exclude(id=product.id).filter(is_active=True, category=product.category) comment = Comment.objects.filter(is_active=True,product=product) # start add comment system # that code work for me form = AddComment() if request.method == 'POST': if form.is_valid(): content = request.POST.get('content', '') user = request.user c = Comment.objects.create(product= product, user= user, content=content, created_at = datetime.now(), updated_at … -
How to find static files using regex in django in view?
I have django project that has a staticfile with the structure staticfiles/bundles/static/js/main.[hash of 8 random characters].js I want to get the name of main.[hash].js in my view. Though I can use python glob to find such file but is there any clean way that is specific to django that I can use to find such file. Maybe using regex with django.contrib.staticfiles.finders ? -
user & request.user displaying different objects - Django
Not even sure where to begin here. Currently running into an issue where users are intermittently loading pages to find themselves "logged in" as other users (Templates rendering with wrong context). The error seems to come down to request.user showing the incorrect user while user has the correct user context. I currently use {{request.user}} in my templates and recognize that I could just switch to {{user}} but don't want to look over anything deeper that is going wrong. Any idea what would cause this? I've confirmed this issue is only contained to the site proper templates. The Admin site as well as some AJAX requests I have going to the server all seem to be processing the correct user context. EX. This is from a template render captured while the issue presented itself. UID is the user id from request.user.pk while User-UID is from user.pk I thought it could be the context processors, but I don't think my ordering is any cause for concern: "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.messages.context_processors.messages", I've done my fair share of googling and head-banging so any help would be appreciated -
Django app for docking using autodock vina without conda env
I want to create an app that can calculate binding through molecules, with autodock vina, but it requires a conda enviroments. Its there other way to do this? This is my first app project with Django. -
Packaging django app that includes management commands
I am working on a django app that includes a custom management command. This app should be packed for pip. Layout of the app is standard django-simpl_ssg simple_ssg management commands __init__.py testcommand.py migrations __init__.py __init__.py admin.py .... setup.cfg setup.py pyproject.toml based on django 4.0 docu setup.cfg is setup like this .... [options] include_package_data = true packages = find: python_requires = >=3.8 install_requires = Django >= 3.2 # Replace "X.Y" as appropriate Now the problem is when running python setup.py sdist the app gets packaged but the management command is omitted running sdist running egg_info writing requirements to django_simple_ssg.egg-info/requires.txt writing django_simple_ssg.egg-info/PKG-INFO writing top-level names to django_simple_ssg.egg-info/top_level.txt writing dependency_links to django_simple_ssg.egg-info/dependency_links.txt reading manifest file 'django_simple_ssg.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*' under directory 'django-simple_ssg/static' warning: no files found matching '*' under directory 'django-simple_ssg/templates' warning: no files found matching '*' under directory 'django-simple_ssg/docs' writing manifest file 'django_simple_ssg.egg-info/SOURCES.txt' running check creating django-simple_ssg-0.1 creating django-simple_ssg-0.1/django_simple_ssg.egg-info creating django-simple_ssg-0.1/simple_ssg creating django-simple_ssg-0.1/simple_ssg/migrations copying files to django-simple_ssg-0.1... copying LICENSE -> django-simple_ssg-0.1 copying MANIFEST.in -> django-simple_ssg-0.1 copying README.md -> django-simple_ssg-0.1 copying setup.cfg -> django-simple_ssg-0.1 copying setup.py -> django-simple_ssg-0.1 copying django_simple_ssg.egg-info/PKG-INFO -> django-simple_ssg-0.1/django_simple_ssg.egg-info copying django_simple_ssg.egg-info/SOURCES.txt -> django-simple_ssg-0.1/django_simple_ssg.egg-info copying django_simple_ssg.egg-info/dependency_links.txt -> django-simple_ssg-0.1/django_simple_ssg.egg-info copying django_simple_ssg.egg-info/requires.txt -> django-simple_ssg-0.1/django_simple_ssg.egg-info copying django_simple_ssg.egg-info/top_level.txt … -
Python manage.py runserver gives error of raise ImportError('win32 only') ImportError: win32 only, using python 3.9, OS Ubuntu 18.04
I'm new to Django, creating my first project. everything was working fine and suddenly got an error of ImportError('win32 only') ImportError: win32. Searched a lot online but didn't find a solution. try to install pip install pywin32, got an error ERROR: Could not find a version that satisfies the requirement pywin32 (from versions: none) ERROR: No matching distribution found for pywin32 try to install pypiwin32, got error as below, Collecting pypiwin32 Using cached pypiwin32-223-py3-none-any.whl (1.7 kB) Using cached pypiwin32-219.zip (4.8 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [7 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 34, in File "/tmp/pip-install-e3895f2v/pypiwin32_a7f6ac392d7c456a8f054610add7c850/setup.py", line 121 print "Building pywin32", pywin32_version ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Building pywin32", pywin32_version)? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. Nothing working and do not know how to solve … -
download to csv the result of a search in Django
I am trying to download a CSV from the result of a search. I have the following views: First is the search view def binder_search(request): if request.method == "POST": searched = request.POST['searched'] binders_searched = Binders.objects.filter(Q(description__contains=searched) | Q(step__name__contains=searched) | Q(status__name__contains=searched)) return render(request, "binder_search.html", {'searched': searched, 'binders_searched': binders_searched}) else: return render(request, "binder_search.html", {}) Then is the csv. This view creates the list of all items in the database. What I am trying to do is get the search result from the above view, and then create the csv file. I would end up with a CSV file that has only the search result in it. def binders_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=binders_result.csv' # create a csv writer writer = csv.writer(response) # designate the model binders = Binders.objects.all() # add column at the heading of csv file writer.writerow(['Item Code', 'Description', 'Item Type', 'Current Step', 'Current Status', 'Last change by']) # loop thru and output for binder in binders: writer.writerow([binder.itemcode, binder.description, binder.itemtype, binder.step, binder.status, binder.user]) return response I look around at different solutions, but none actually debugged me. Any idea how to do this? -
python request.post raise unexpected eof while reading
i was upgraded recent version pyopenssl package in django project after that request.post raise eof while reading error import requests headers = { 'Content-Type': 'application/json', 'someheader': 'SOMEVALUE', } json_value = { 'value1': 'value1', 'value2': 'value2', } url = 'https://url.s.o/m/e/u/r/l/' res = requests.post(url, json=json_value, headers=headers) this code raise error [('SSL routines', '', 'unexpected eof while reading')] i use python 3.6 Django==2.1.2 pyopenssl==22.0.0 requests==2.27.1 openssl==1.1.1f how can i solve it? -
Generating thumbnail manually and uploading it in S3 bucket
My web app is image-centric and when a user uploads an image (any size), I need to create a thumbnail and store so that I can use the thumbnail and not the original image. I use AWS S3 bucket, boto3, django-storages. The file upload works flawlessly, my issue is when I generate a thumbnail and upload to the S3 bucket with different file name (it does not throw error, but I cannot see any thumbnail images generated or stored) This is my settings.py Media root MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS Specific settings (I did not override MEDIA_ROOT) AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME') AWS_QUERYSTRING_AUTH = False AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = os.getenv('AWS_DEFAULT_ACL') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_S3_FILE_OVERWRITE=False # s3 static settings STATIC_LOCATION = 'static' STATIC_ROOT = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' CKEDITOR_BASEPATH = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/ckeditor/ckeditor/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' #MEDIA_ROOT = f'https://{AWS_S3_CUSTOM_DOMAIN}/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The code where I upload generated thumbnail files (if it ever generates): I use the Pillow library for generating thumbnail Version 1 of code: tfname = os.path.join(os.path.join(settings.BASE_DIR,"media"), file_name) image.save(tfname) Version 2 of the code (saw it somewhere on this site and … -
how to send longitude and latitude to javascript script from def django
I can't figure out how to replace digital longitude and latitude values with dynamic fields from postgres in javascript how to get the longitude and latitude of a particular place in this script? <div id='map' style='width: 100%; height: 400px;'></div> <script> mapboxgl.accessToken = '{{ mapbox_access_token }}'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v10', center: [20.890438, 52.256002], // {{venue.lat}}, {{venue.long}} How to pass fields in a similar way as all other django fields zoom: 9 }); var marker= new mapboxgl.Marker() .setLngLat([20.890438, 52.256002]) // {{venue.lat}}, {{venue.long}} .addTo(map) </script> All rendering functions in django. Here's how to send a specific longitude and latitude for a specific event. def show_venue(request, venue_id): venue = Venue.objects.get(pk=venue_id) venue_owner = User.objects.get(pk=venue.owner) long = Venue.objects.get(pk=venue.long) lat = Venue.objects.get(pk=venue.lat) #addresses = Venue.objects.all() mapbox_access_token = 'pk.eyJ1IjoicGF2ZWxzdHJ5a2hhciIsImEiOiJjbDI2ZmJmcTkyajBwM2lscDd6aDVwOG4xIn0.15o8i7eD1qwyQcnsx2iBmg' return render(request, 'events/show_venue.html', { 'venue': venue, 'venue_owner':venue_owner, #'addresses': addresses, 'mapbox_access_token': mapbox_access_token, 'lat':lat, 'long':long, }) I will be very grateful for your help -
How to send react form to an email and also save into database
How to send react form to an email and also save into database.. (We need to use Django for backend) and react js for frontend. is there anything else we can do without using the method mentioned below? Fill the form Send to Django Views Save to Database from Django View Send an email to corresponding email -
How to set up developing Django, JavaScript with Docker and static files? To get real time web page changes
Currently I have Docker container. The process with main.js: npm renders main.js and store it in static folder (out of the docker container) Docker compose and docker file collects static files in static-volume, including main.js Nginx serves main.js from static-volume But when I make changes to the source code, I can see the results only after restarting container and "docker volume prune" command. I want to have changes of the web page right after code is changed. And what is the best practise in this scenario? -
Improving efficiency around Django's ORM and serialization while importing external data
I have a celery worker that periodically fetches data from an API that I need to be in sync with. I create or update a particular model instance depending on whether I have the external id stored already. However, as the API I'm syncing with has grown, this task has become increasingly expensive. Here's the relevant code: for d in api.fetch_items(): attempted_count += 1 try: existing_item = MyModel.objects.get(item_id=d["item"]) serializer = MySerializer( existing_item, data=d, partial=True, context={"company": company}, ) except MyModel.DoesNotExist: serializer = MySerializer(data=d, context={"company": company}) if serializer.is_valid(): serializer.save() imported_count += 1 else: logger.error(f"Invalid data when deserializing item: {serializer.errors}\nBased on: {d}") I think because the response is so long (often 50,000+ items), those queries make the task eat up lots of time. I'm hoping to get some suggestions on making this flow more efficient. Some things I've considered: Comparing the instances of MyModel via iterator() to the response the task receives to determine which internal items need to be updated or created (I don't even know if this would be faster) Bulk updating, though I'm not sure how to do bulk updates when the values that need to be updated for each item are different. Maybe an atomic transaction? I'm not even … -
How to Create Collection Like QuerySet in Django
#The below statement is valid medical = Medical.objects.filter(ref_no=ref_no) print(medical) #This is the output which contains two records <QuerySet [<Medical: Medical object (1)>, <Medical: Medical object (2)>]> #This is the model for Medical class Medical(models.Model): ref_no = models.CharField(max_length = 100) med_ref = models.CharField(max_length = 100) status = models.CharField(max_length = 50) #The value return from database are encrypted. I have a class that successfully decrypt the value. med = Setup.TransformData(medical) def TransformData(medicals): medList = [] if medicals.exists(): for med in medicals: medical = Medical() medical.radius = EncryptionDecryption.DataDecryption(med.ref_no) medical.radius = EncryptionDecryption.DataDecryption(med.med_ref) medical.radius = EncryptionDecryption.DataDecryption(med.status) medList.append(medical) return medList My challenge is that in this class, I am not able to re-create the medical collection to return the value like QuerySet or some other format so that i can loop through it to get the decrypted values for each records. Please can someone help me re-write the TransformData method to return an iterable values. Thanks -
Django Admin - Preventing staff from accessing admin panel
I'm fairly new to Django. How do I prevent staff users from logging into the Django admin panel? I still want them to be identified as staff, but do not want them to be able to log into the admin panel. I am using the default Django admin panel. Thanks -
Query with multiple foreign keys (django)
I'm making a searchbar for a site I'm working on and I'm having trouble when I want to filter different fields from different models (related between them) Here are my models: class Project(models.Model): name = models.CharField(max_length=250) objective = models.CharField(max_length=250) description = models.TextField() launching = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField( upload_to='imgs/', null=True, blank=True) image_thumbnail = models.ImageField( upload_to='thumbnails/', null=True, blank=True) slug = models.CharField(max_length=250) class Meta: db_table = 'project' def __str__(self): return self.name class Institution(models.Model): name = models.CharField(max_length=250) project = models.ManyToManyField(Proyecto) class Meta: db_table = 'institution' def __str__(self): return self.name And I want to be able to search by the name of the project or the institution, but my code only takes the institution's name. def searchbar(request): if request.method == 'GET': search = request.GET.get('search') post = Project.objects.all().filter(name__icontains=search, institution__name__icontains=search) return render(request, 'searchbar.html', {'post': post, 'search': search}) How can I search for all the projects that match by its name OR the institution's name? BTW, I'm using SQL, not sure if it's relevant, but I thought I should add that info. -
how to populate user field with current user in django models via forms?
hi i am working on a django app. functionality that i am implementing is to let my user buy a internet pack from the website. i have implemented the model, view, template and url so far. but in the form i am getting a drop down list of all the users registered on the app. i automatically want django to link the user with current logged in user and let him select the pack he wants to buy and populate the model(table) automatically. My models.py def get_deadline(): return dt.today() + timedelta(days=30) class CustomUser(AbstractUser): Address = models.CharField(max_length=500) def __str__(self): return self.username class Plans(models.Model): plan_name = models.CharField(max_length=50) speed = models.IntegerField() price = models.FloatField() def __str__(self): return self.plan_name class Orders(models.Model): user = models.ForeignKey(CustomUser, on_delete = models.CASCADE) pack = models.ForeignKey(Plans, on_delete = models.CASCADE) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(default=get_deadline()) is_active = models.BooleanField(default=True) def __str__(self): name = str(self.user.username) return name my views.py class UserBuyPlan(LoginRequiredMixin, View): template = 'plans/plan.html' #success_url = reverse_lazy('autos:all') success_url = reverse_lazy('home-home') def get(self, request): form = BuyPlanForm() ctx = {'form': form} return render(request, self.template, ctx) def post(self, request): form = BuyPlanForm(request.CustomUser,request.POST) if not form.is_valid(): ctx = {'form': form} return render(request, self.template, ctx) make = form.save() return redirect(self.success_url) my forms.py (i tried searching …