Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where do I store user personal information
I am creating an application in which a user registers with a username, email, and password. This data is stored in one table. But then the user enters profile information such as photo, bio, activity and such. Do I store this data in the same table as the username, email, and password? Or do I create another table in which I link those in some way? -
Celery instantly kill running task
i want to implement api endpoint for start/stop button with celery (when is running, on backend in while(True) loop do some work) celery version 4.4.6. As broker i use rabbit i stuck with task revoking(i need just instantly kill task) i use this code for that(but it not works) app.control.revoke(started_task.id, terminate=True, signal='SIGKILL') my task looks like that def _grind(): count = 1 while True: count += 1 print(count) # here are many parrallel aihttp requests and database writes... @shared_task(bind=True) def grind(self): asyncio.run(_grind()) and i need is_running state to provide him to my frontend my vain tries... the idea is that when you click on the stop at the task entry, a signal is set to stop and while saving, I cause an exception that interrupts the execution of the task (but the save signal never works) class Task(models.Model): id = models.CharField(max_length=50, primary_key=True) type = models.CharField(max_length=20, choices=TaskType.choices) signal = models.CharField(max_length=20, choices=TaskSignal.choices, null=True, blank=True) user = models.ForeignKey(CustomUser, related_name='tasks', on_delete=CASCADE) @shared_task(bind=True) def grind(self): task_id = self.request.id def cancel_task(instance: Task, **kwargs): print('Never trigger') if instance.id == task_id and instance.signal == TaskSignal.STOP: post_save.disconnect(cancel_task, sender=Task) instance.delete() raise Ignore() post_save.connect(cancel_task, sender=Task) count = 1 while True: count += 1 print(count) # ---- on start-stop click def toggle_grind(user: … -
How to make a constructor through which the user can create a template by adding any field from the model to it, including nested fields?
I have 5 entities that are related to each other. I have successfully described the models and the relationships between them. Everything is good here. But they require a certain constructor from me, which assumes that the administrator can, in user mode (in the admin panel, or on any other page), change the appearance of the check that is printed for the client without changing the source code of the program (i.e. add or remove ticket fields). For example, a user can create 2 receipt templates - "regular" and "reduced". A "regular" check will include the name of the voyage, itinerary, carrier, departure_station and arrival_station, departure_date and arrival_date, place_number, etc., while "abbreviated" will only contain the name of the voyage, departure_date and place_number I will briefly describe the models here: class BusStation(models.Model): name = models.CharField(max_length=64) city = models.CharField(max_length=32) region = models.CharField(max_length=32) class Carrier(models.Model): name = models.CharField(max_length=64) inn_number = models.PositiveBigIntegerField(verbose_name='ИНН', unique=True) class Itinerary(models.Model): name = models.CharField(max_length=64) number = models.CharField(max_length=64) departure_station = models.ForeignKey(BusStation, related_name='departure_busstations', on_delete=models.CASCADE) arrival_station = models.ForeignKey(BusStation, related_name='arrival_bus_stations', on_delete=models.CASCADE) class Voyage(models.Model): departure_date = models.DateTimeField() arrival_date = models.DateTimeField() itinerary = models.ForeignKey(Itinerary, related_name='itineraries', on_delete=models.CASCADE) bus_station_platform = models.PositiveIntegerField() class Ticket(models.Model): TYPE_TICKET = [ ('1', '1'), ('2', '2'), ] passengers_name = models.CharField(max_length=128) voyage = models.ForeignKey(Voyage, … -
having trouble installing django on centos 7
enter image description here been trying to install django on my venv on centos 7. I'm new to using centos and linux in general so i'm having trouble finding out what's causing these errors shown on the screenshot. If it's not clear on the picture I've also pasted it here below. Also, I'm not sure if having two versions of python is maybe causing this. I installed 3.6.8 using the package manager because i did not have an idea that that was the latest version available there so i downloaded 3.10.5 and installed it too. However on the error message that is showing, it seems like 3.6.8 is being mention. I can't understand. Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/pip/_vendor/urllib3/response.py", line 302, in _error_catcher yield File "/usr/lib/python3.6/site-packages/pip/_vendor/urllib3/response.py", line 384, in read data = self._fp.read(amt) File "/usr/lib/python3.6/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 60, in read data = self.__fp.read(amt) File "/usr/lib64/python3.6/http/client.py", line 459, in read n = self.readinto(b) File "/usr/lib64/python3.6/http/client.py", line 503, in readinto n = self.fp.readinto(b) File "/usr/lib64/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) File "/usr/lib64/python3.6/ssl.py", line 971, in recv_into return self.read(nbytes, buffer) File "/usr/lib64/python3.6/ssl.py", line 833, in read return self._sslobj.read(len, buffer) File "/usr/lib64/python3.6/ssl.py", line 590, in read v = self._sslobj.read(len, buffer) socket.timeout: The read … -
How can I pass HTML data from Python to an already created HTML page for display?
I am working on a Django project and would like to take markdown texts, convert them to HTML, and then display them on the browser. I did some research and tried different ways, but none worked as I wanted. This is my code: Python: class HTMLFilter(HTMLParser): text = "" def handle_data(self, data): self.text += data def display_entry(request, entry): if util.get_entry(entry.capitalize()) != None: markdowner = Markdown() data = markdowner.convert(util.get_entry(entry.capitalize())) html = HTMLFilter() html.feed(data) body = html.text return render(request, "encyclopedia/display.html", { "title": entry, "body": body }) else: return render(request, "encyclopedia/error.html", { "entry": entry.capitalize() }) This is how the function (get_entry()) from the util module looks like: def get_entry(title): try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None I use the python-markdown2 package to convert markdown language to HTML and it works perfectly. Below is an example of the text that was converted into HTML. <h1>Django</h1> <p>Django is a web framework written using <a href="/wiki/Python">Python</a> that allows for the design of web applications that generate <a href="/wiki/HTML">HTML</a> dynamically.</p> My biggest challenge is displaying this text as normal HTML to the browser. This is what my HTML file looks like: {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock … -
Django Admin One-To-Many-To-One (Site->Product->Price) Relationship
I'm developing a web app for fun and the goal is to use Django Admin and only Django Admin, without any custom templates (yet). I'm unable to figure out how I should structure my models.py and admin.py files, where what I'm trying to do is: There are many items and many departments: Each item can only belong to one department and each department can have several items. This currently works. Now, what I can't seem to figure out is: There are many sites. Each site can have many items, but the PRICE of each item at each site can be different. For example: Site #123 can have a can of coke for $1.00 Site #124 can also have a can of coke, but at a price of $0.95 Site #123 can have a bag of chips for $1.50 Site #124 can also have a bag of chips, but at a price of $1.95 etc... How do I establish this relationship in Django models.py/admin.py? Also, how could I edit the price using the inline (screenshot below)? In other words, how could the price be shown to the right of the description? Thanks in advance Current Code: admin.py: from django.contrib import admin … -
Django Project Multitenancy Structure
I would like to develop a saas structure made on django. I have the virtual env installed, also the project created. I would need to find a video or help of some how on knowing how to set up the structure for a SAAS CRM System. Basically the structure would be: SUPERADMIN ROLE WITH PERMISSIONS Superadmin (ME) Superadmin Team ( MY TEAM) ADMIN (CLIENT) TEAM MEMBER ( CLIENT TEAM) Also since there are many permissions to define it would be perfect if superadmin can manage the users, roles, profiles and create new ones and delete them. Superadmin would be able to check boxes and uncheck boxes that allow users permissions. Hope someone can help! Thank you -
How can i get actual path of the docx file uploaded to the database using django models?
I am developing a simple web application using django that can take three .docx files containing tables and merge those tables in a single file and return that file to user in downloadable form. I used python-docx library for docx file processing. All three files are uploaded successfully without having any issue but the problem arises when i try to open those document files using doc.Document(file path) constructor of docx library. But the problem is that doc.Document() can't open the word file and it shows error like docx.opc.exceptions.PackageNotFoundError: Package not found at '/media/documents/word/SS_SMS39_CE3_InQfp7c.docx' while it clearly shows the path and while checking on the /media/documents... i can clearly locate that file. I tried a lot on searching about this issue went through docx documentation and even django's fileStorage documentations. But i cannot solve this problem. If you could help me figure out this issue, i will be grateful. I have provided all the models.py, views.py, urls.py, and my templates models.py from django.db import models class Mydocument(models.Model): file1 = models.FileField(upload_to='documents/word/') file2 = models.FileField(upload_to='documents/word/') file3 = models.FileField(upload_to='documents/word/') file_processed = models.FileField(upload_to='documents/word/',null=True,default='documents/word/ssm.docx') views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import DocumentForm from .models import Mydocument import docx as dc def … -
django-jsonforms how to limit how many fields can add from object properties collapsable?
Is there a way so set a range or limit on how many fields a person can add from the object properties collapsable? or any docs on how to configure it? I looked at the docs I could find, but. options = {'additionalProperties': True } form = JSONSchemaForm(schema=jsonschema, options=options, ajax=False) -
request.Meta.get is not working in django appdeployed on heroku
I want to limitize user accessing the endpoints, I have used request.Meta for that, IT is workig properly on local but when I deployed it on heroku, its not working. PLease let me know where I am wrong class ResetPasswordPhoneView(View): def get(self, request, *args, **kwargs): if request.META.get('HTTP_REFERER') != 'http://127.0.0.1:8000/login/' or request.META.get('HTTP_REFERER') != 'https://auth.herokuapp.com/login/': return redirect('login') reset_form = Reset_Password_phones_Form() return render(request, 'phone.html', {'reset_form': reset_form}) -
Capturing Data of a User Visiting my website
How can I capture data of someone visiting my website via a shortened link? I want to be able to capture the OS, IP, divide ID etc. Would capturing the user agent string be the best option? What are some other ways? In my case I'm building a website with DJAGNO. -
Django-Ckeditor editor issues
I can't install Django CKEditor in virtual environment, I tried with pip install django-ckeditor. Where did the actual problem occurred? It's shown below error. Note: I used ckeditor before in a project, there worked perfectly. In my prvious project wherse I used ckeditor, I didn't create virtual environment. But in the current project I created virtual environment. error: ERROR: Exception: Traceback (most recent call last): File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher yield File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 90, in read data = self.__fp.read(amt) File "c:\users\dcl\appdata\local\programs\python\python39\lib\http\client.py", line 455, in read n = self.readinto(b) File "c:\users\dcl\appdata\local\programs\python\python39\lib\http\client.py", line 499, in readinto n = self.fp.readinto(b) File "c:\users\dcl\appdata\local\programs\python\python39\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) File "c:\users\dcl\appdata\local\programs\python\python39\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "c:\users\dcl\appdata\local\programs\python\python39\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_internal\cli\base_command.py", line 167, in exc_logging_wrapper status = run_func(*args) File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_internal\cli\req_command.py", line 205, in wrapper return func(self, options, args) File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_internal\commands\install.py", line 339, in run requirement_set = resolver.resolve( File … -
ImportError: cannot import name 'url' from 'django.conf.urls' in packages
I have a project of migrating django web app from Django-3.2.14 to Django-4.0. Immediately after migration, when I run the server I get the error as shown in Console output. When I traced the changes, it traced to django-compat package, which was being called by django-background-tasks package. my_env is my virutal environment. We have latest version of django-compat, which is 1.0.15 and django-background-tasks, which is 1.2.5. Could you please look into this? Thank you in advance. Console: (myenv) D:\New_Folder\github\project\project_name>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\New_Folder\github\myenv\lib\site-packages\compt\__init__.py", line 46, in <module> from django.conf.urls import url, include, handler404, handler500 ImportError: cannot import name 'url' from 'django.conf.urls' (D:\New_Folder\github\myenv\lib\site-packages\django\conf\urls\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "D:\New_Folder\github\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\New_Folder\github\myenv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "D:\New_Folder\github\myenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\New_Folder\github\myenv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "D:\New_Folder\github\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\New_Folder\github\myenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\New_Folder\github\myenv\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() … -
DJ-Stripe metadata not attaching to product
I am following this guide: https://www.saaspegasus.com/guides/django-stripe-integrate/#contents I get to "Adding metadata to your Stripe objects" and am told to create a metadata.py file. It doesn't tell me where to import @dataclass and List from so I had to guess. The issue is that, moving forward from this point in the guide, the metadata does not print to my template but I can retrieve product information. I'm thinking this guide is missing or assuming I know stuff about metadata that is required to make it work. my metadata.py: from dataclasses import dataclass from pip import List from project.subscriptions import features @dataclass class ProductMetadata(object): """ Metadata for a Stripe product. """ stripe_id: str name: str features: List[str] description: str = '' is_default: bool = False PREMIUM = ProductMetadata( stripe_id='<prod id>', name='Premium', description='yerp', is_default=False, features=[ features.UNLIMITED_WIDGETS, features.LUDICROUS_MODE, features.PRIORITY_SUPPORT, ], ) features.py: UNLIMITED_WIDGETS = 'Unlimited Widgets' LUDICROUS_MODE = 'Ludicrous Mode' PRIORITY_SUPPORT = 'Priority Support' views: from django.shortcuts import render from djstripe.models import Product def pricing_page(request): context = { 'products': Product.objects.all() } return render(request,'subscriptions/pricing_page.html', context=context) urls: path('pricing_page/', view=pricing_page, name='pricing_page'), template: {% extends "base.html" %}{% load static socialaccount %} {% block content %} <h1>Plans</h1> <section> <p class="title">Pricing Plans</p> <div class="columns"> {% for product in products %} … -
Django: How to get all objects related to a model by another model?
I have 3 models: User, Course and Homework. Each course has some homework and some users(students). How can I have all homeworks of all courses a user is in? These are the models: class User(AbstractUser): # ... class Course(models.Model): students = models.ManyToManyField(User, blank=True, related_name='student_courses') # ... class Homework(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='course_homeworks') # ... -
Where to add udp socket initialization in django project
I am a newbie to python django framework. Currently i am working on a django project which listens to udp messages and act accordingly. Initially i initialized the socket and starts a thread to receives the messages on that socket in one of the views.py where it handles the request from URL. Now i have to make these initialization and starting the thread when the server is up. Which is the ideal place to put this piece of code ? I tried out so many places, i am facing an issue here. Whereever i put "python manage.py makemigrations" executes this code and gets stuck in receiveing the messages. I even tried in ready() method overridden in apps.py. This method also gets executed with makemigrations. Is there any way i can bypass makemigrations and initialze the sockets only during runserver ? -
Error while deploying application on heroku
I am getting an error while deploying app on heroku Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Everything is working perfectly fine on heroku local here are some of settings that I did ALLOWED_HOSTS = ['0.0.0.0'] Any idea why am I getting this error -
Is this the correct way to get information from forign-key model Django
In the model declaration, I make property: @property def author(self): book_id = getattr(self, 'book_id') book = Book.objects.get(id=book_id) author_id = getattr(book, 'author_id') author = Author.objects.get(id=author_id) author_name = getattr(author, 'first_name') return author_name To get data on the front. It works. But how is this possible and how can it be done better? -
How to send data to a websocket from outside of consumer django channels
I'm trying to send data to a websocket from outside of the consumer so i did following: settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } routing.py from django.urls import path from .consumers import CoinsListConsumer websocket_urlpatterns = [ path('ws/coins/', CoinsListConsumer.as_asgi()) ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from apps.coins.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( websocket_urlpatterns, ) ) ) }) consumers.py class CoinsListConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info('Websocket was connected.') await self.accept() async def disconnect(self, code): logger.warning('Websocket was disconnected.') pass async def receive(self, text_data=None, bytes_data=None): return await super().receive(text_data, bytes_data) well this is ok and when i go to a view... the websocket will connect very well but when i want to send data to the websocket. def send_data_to_websocket_coins_list_view(data: List[Dict]) -> None: """Send data to websocket coins list view """ async_to_sync(channel_layer.send)(json.dumps(data)) This did not work and raised following error TypeError: send() missing 1 required positional argument: 'message' Also in the documentation this is should work by following code async_to_sync(channel_layer.send)("channel_name", {...}) its also not worked and raise the following error AssertionError: message is not a … -
Want to design a promotion model in Django
Brand partner creates a plan a. Creates a plan in the database with planID, planName, amountOptions and tenureOptions, benefitPercentage (for example: 10), benefitType (cashback/extraVoucher) and any other attributes needed. Brand partner creates promotion for an existing plan a. Promotion can be limited in two ways i. By the number of users to get the promotion (for example: 500 users) ii. By a time period (for example: 22th May 2022 to 24th May 2022) b. Assume that promotion can only affect benefitPercentage for a given plan Code I have written for Plan Model class Plan(models.Model): planID = models.BigAutoField(primary_key=True) planName = models.CharField(max_length=255, null=True, blank=True) amountOptions = models.CharField(max_length=15, choices=AMOUNT_CHOICES, default="cash") tenureOptions = models.IntegerField(default=1, choices=TENURE_CHOICES) benefitPercentage = models.FloatField(default=0) benefitType = models.CharField(max_length=10, choices=BENIFIT, default="cashback") def __str__(self): return self.planName -
Filtering data using age group in django
I want to filter my products based on for what age group they are intended to. My plan of doing that is using a boolean field and filter the products by that. I have a dropdown menu which lists the different age groups and when a person clicks on one, a page will be displayed with the products which have boolean true for that age group. Here is my models. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=150) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2, default=0) amount = models.IntegerField(default=0) detail = RichTextUploadingField() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) child = models.BooleanField(default=False) teen = models.BooleanField(default=False) adult = models.BooleanField(default=False) def __str__(self): return self.title Is this the way I should do it? If it is the case should I use 3 different views.py for each boolean or is there any efficient way? Thank you in advance! -
I can't submit multiple images with django
I have tried to submit multiple images to my Django website without using Django forms but I can't seem to get it working. I have watched multiple tutorials doing the exact same thing but it's not working. Can you please simplify the answers please, Thank you. views.py @login_required(login_url='/') def addlisting(request): if request.user.is_realtor == True: if request.method == 'POST': header_image = request.FILES.getlist('header_image') property_images = request.FILES.getlist('property_images') for image in property_images: image.save() description = request.POST['description'] built_on = request.POST['built_on'] video_link = request.POST['video_link'] agent = request.user new_property = Property.objects.create( full_bathrooms=full_bathrooms, half_bathrooms=half_bathrooms, one_quarter_bathrooms=one_quarter_bathrooms, three_quarter_bathrooms=three_quarter_bathrooms, garage=garage, lot_size=lot_size, yard_size=yard_size, header_image=header_image, description=description, built_on=built_on, video_link=video_link, agent=agent, ) new_property.save() return render(request, 'dashboard-add-listing.html') else: return render(request, 'index.html') html <div class="dasboard-widget-box fl-wrap"> <div class="custom-form"> <div class="clearfix"></div> <div class="header-image"> <div class="upload-options upload-options-header"> <label class="file-upload-label"> <input class="upload" type="file" accept="image/*" name="header_image"> <span>Upload Header Image</span> </label> </div> </div> <div class="clearfix"></div> <div class="listsearch-input-item fl-wrap"> <div class="fuzone"> <div class="fu-text"> <span><i class="far fa-cloud-upload-alt"></i> Click here or drop files to upload</span> <div class="photoUpload-files fl-wrap"></div> </div> <input type="file" name="property_images" class="upload" multiple> </div> </div> </div> </div> -
InvalidCursorName at cursor "_django_curs_6134247424_sync_4" does not exist
Whenever I try to add a user from djangos user_auth I get this error. models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(blank=True, null=True) def __str__(self): return self.user admin.py: class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomUserAdmin(UserAdmin): inlines = (AccountInline,) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) Being new to django, I don't understand what the error means and how to get rid of it. Any help will be greatly appreciated. -
Django .order_by() related field returns too many items
I'm trying to return a list of users that have recently made a post, but the order_by method makes it return too many items. there is only 2 accounts total, but when I call test = Account.objects.all().order_by('-posts__timestamp') [print(i) for i in test] it will return the author of every post instance, and its duplicates. Not just the two account instances. test@test.gmail.com test@test.gmail.com test@test.gmail.com test@test.gmail.com foo@bar.example Any help? class Account(AbstractBaseUser): ... class Posts(models.Model): author = models.ForeignKey('accounts.Account',on_delete=models.RESTRICT, related_name="posts") timestamp = models.DateTimeField(auto_now_add=True) title = ... content = ... -
How to solve "TypeError: Field.__init__() got an unexpected keyword argument 'choices'"?
I recently decided to update my forms.py file of my Django project to make one of the fields into a drop down menu rather than an empty text box. In my forms.py file, I changed the class for customers from; class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email_address = forms.EmailField(required=True) membership_tier = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def data_save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.is_customer = True user.save() customer = Customer.objects.create(user=user) customer.email_address = self.cleaned_data.get('email_address') customer.membership_tier = self.cleaned_data.get('membership_tier') customer.save() return user to the following class CustomerSignUpForm(UserCreationForm): member_tiers = ( 'Basic', 'Intermediate', 'Beast' ) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email_address = forms.EmailField(required=True) membership_tier = forms.CharField(choices = member_tiers, default = 'Basic', required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def data_save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.is_customer = True user.save() customer = Customer.objects.create(user=user) customer.email_address = self.cleaned_data.get('email_address') customer.membership_tier = self.cleaned_data.get('membership_tier') customer.save() return user And here is my customer class in my models.py as well if that will help, class Customer(models.Model): member_tiers = ( 'Basic', 'Intermediate', 'Beast' ) username = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) email_address = models.EmailField(max_length=30) membership_tier = models.CharField(max_length = 30, choices = member_tiers, default = 'Basic') What my question boils down to is: …