Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and channels, expose model data via websockets after save
I am new to websocket and channel with django. In my django project i would to expose saved data after a post_save event occur in a specific model via websocket. I have django 3.2 and i install: channels==3.0.4 channels-redis==3.3.1 then in my settings.py i add channels to my app list and set: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': ["redis://:myredishost:6379/0"], }, 'ROUTING': 'backend.routing.channel_routing', } } chenge my application from WSGI to ASGI: ASGI_APPLICATION = "backend.asgi.application" then i try to create the routing.py file like this: from channels.routing import route from alarms.consumers import ws_connect, ws_disconnect channel_routing = [ route('websocket.connect', ws_connect), route('websocket.disconnect', ws_disconnect), ] and connect and disconnect methods (insert every connected user ubto User group for now): from channels import Group def ws_connect(message): Group('users').add(message.reply_channel) def ws_disconnect(message): Group('users').discard(message.reply_channel) now i have an Results_Alarms model: # Model of Alarms data class Results_Alarm(models.Model): id = models.AutoField(primary_key=True) var_id = models.ForeignKey('modbus.ModbusVariable', null=True, on_delete=models.SET_NULL) calc_id = models.ForeignKey(CalcGroup, null=True, on_delete=models.SET_NULL) templ_id = models.ForeignKey(AlarmsTemplate, null=True, on_delete=models.SET_NULL) a_trigger = models.CharField(max_length=200, verbose_name="Alarm trigger") dtopen = models.DateTimeField(verbose_name="Date of error") e_status = models.ForeignKey(AlarmStatus, null=True, on_delete=models.SET_NULL) dtclose = models.DateTimeField(verbose_name="Date of resolution", null=True, blank=True) u_involved = models.ForeignKey('accounts.CustomUser', related_name='oumanager', on_delete=models.CASCADE, null=True) ... I also create the signals.py file for manage the post_save event: … -
Django/authentification: how to make login page = home page?
I develop Django web app using Django authentification backend. It works without having to define any views or forms, only template to 'bootstrap' it. But I would like to change 'navigation' url and probably 'redesign' template using django-crispy-form. But the first step is make user directly access Login page when the 'root' url (https://<my_domain>/) is enter in the navigation adress bar. Currently, user access home page of my web app that contain a login button that redirect to https://<my_domain>/registration/login Do I need to override all authentification views (and forms for design) and change url as needed? Or is there an easiest way, maybe using settings.py to make user redirect to login page from root url? project - app - core - settings - base.py - ... - views.py - urls.py - app1 - forms.py - views.py - templates - app1 - registration # <= currently no forms.py nor views.py - templates - registration - login.html - password_change_done.html - ... - static - templates - layout - base.html - home.html core/urls.py urlpatterns = [ path('', views.home, name='home'), # <= 'root' url # path('registration/', include('registration.urls')), # <= registration views override path('registration/', include('django.contrib.auth.urls')), ] core/settings.py LOGIN_URL = 'home' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = … -
How to add both integer field and choices in a single attribute of a model class in django?
I want to add both choices of days and hours in my assigned_time field, along with adding how many days or how many hours. Here is what I tried that doesn't work. Here is my model.py class Timesheet(models.Model): DAYS= 'D' HOURS = 'H' STATUS= [ ('D', 'Days'), ('H', 'Hours') ] employee= models.ForeignKey(Employee, on_delete=models.CASCADE) date= models.DateField(verbose_name='Date') designation=models.ForeignKey(Designation, on_delete=models.CASCADE) projects= models.CharField(max_length=256, verbose_name='Project Name') assigned_time= models.IntegerField(verbose_name='Assigned Hours/days', choices=STATUS, default=DAYS) time_spent=models.IntegerField(verbose_name='Spent Hours/Days', choices=STATUS, default=DAYS) description=models.TextField(max_length=1000, verbose_name='Description') def __str__(self): return f'{self.employee.user.first_name} {self.employee.user.last_name} {self.project}' Check for assigned_time or time_spent field. I want to do the same thing on both as I explained above. Here is my admin.py @admin.register(Timesheet) class TimesheetAdmin(admin.ModelAdmin): list_display=('first_name', 'last_name', 'date', 'assigned_time', 'projects', 'time_spent', 'description', 'designation_name') def first_name(self, obj): return obj.employee.user.first_name def last_name(self, obj): return obj.employee.user.last_name def designation_name(self, obj): return obj.designation.designation_name Here is the image of what I am getting What should I do to add both things in a single field? -
Will upgrading the class of the DB instance speed up my lambda application
I have a Django application that is connected to a PostgreSQL database located on AWS RDS. Right now, because it's still in development we use a small tier (db.t3.small) which has 2vCPUs, 2GiB RAM and 2.085 Mbps. My application is running smooth and fast, except for one model because it has over 6 million rows. It takes about 25 seconds to load even when working on localhost. When I then switch to a local postgreSQL database on my computer with the same data it takes around 3s to load So I'm wondering, if I upgrade to db.t3.medium or even db.t3.large that both double in RAM size from his previous tier. will this make any diffrence in speed for my application -
How to deploy Django project on Heroku
Its been 2 days since i have trying to deploy my django project on heruko everytime it give me some kind of error so is there anyone who know how to deploy django project on heruko My requirement.txt file is asgiref==3.4.1 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.6 cryptography==3.4.8 defusedxml==0.7.1 Django==3.2.7 django-allauth==0.45.0 django-countries==7.2.1 django-crispy-forms==1.14.0 idna==3.2 oauthlib==3.1.1 Pillow==9.0.0 pycparser==2.20 PyJWT==2.1.0 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 sqlparse==0.4.2 stripe==2.65.0 urllib3==1.26.7 and currently I am using python version 3.9.5 and I am using sqlite3 database which is default database for everynew python project IF any need anykind of information just ask me in the comments -
Django rest framework group by
I want to group by my data on the basis of ingredient_id so that it does not repeat in response, as you can see am querying on the basis of ingredient_id which is a foreign key so it can be repeated in the database. But I want all the ingredient data to be once and then the supply_chain information around it. model.py class SupplyChainStops(models.Model): ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE) stop_name = models.CharField(max_length=1024, null=True, blank=True) stop_longitude = models.CharField(max_length=500, null=True, blank=True) stop_latitude = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return f'{self.stop_name}' query @api_view(['GET']) def supply_chain_response_detail(request, id): ingredient_detail = SupplyChainStops.objects.filter(ingredient_id=id).all() serializer = SupplyChainStopsSerializer(ingredient_detail, many=True) return Response(serializer.data) Serializer class IngredientSerializer(serializers.ModelSerializer): ingredient_category = IngredientCategorySerializer() supplier = SuppliersSerializer() origin = OriginSerializer() allergies = AllergiesSerializer(many=True) class Meta: model = Ingredients fields = '__all__' class SupplyChainStopsSerializer(serializers.ModelSerializer): ingredient = IngredientSerializer(many=False) class Meta: model = SupplyChainStops fields = '__all__' -
How to auto login a user in django if the tab was closed and he wasn't logged out?
I am working on a Django project. I have a backened(Django) and frontend(HTML, CSS,JS). Everything is working as expected like login, registration, logout, etc. However, one requirement, and I know it's a very common one, is that if the tab is closed after user logs in(he didn't logout), and the user reopens the url of login, he should be taken to the dashboard instead of again asking for login credentials on login screen. What Have I tried? I saw some other answers and I tried putting this check in the "login/" url of my page: request.user.is_authenticated It always gives false if I place this check on the login page. I put it on login page's Get method because I want that if user was logged in and he tries to go to the login url, he gets redirected to dashboard. But it always gives False. What I want help with? It would be very kind if anyone can guide me on how to achieve the above objective. -
session expiry changes every time
After creating session when i tried to get session the value of expiry date changes every time may I why is this happening. 1st get request - "session_expiry": "2022-02-21T22:42:38.231938Z" 2nd get request - "session_expiry": "2022-02-21T22:53:00.524236Z" 3rd get request - "session_expiry": "2022-02-21T22:53:26.022811Z" In all three cases values are of same session. -
How can i prefill the field in admin site?
I have a model which has two fields file and person who uploaded it when i register my model in admin it should prefill the uploaded field according to the user(only admins) how can i acheive this. models.py: class TemplateModel(BaseModel, SingletonModel): file = models.FileField( upload_to='', validators=[FileExtensionValidator(['', ''])] ) person_uploaded = models.ForeignKey( 'accounts.Account', related_name='', null=True, on_delete=models.SET_NULL, ) -
dj-rest-auth error setting up custom registration serializer
I wrote a custom register serializer according to the docs. I also made a dictionary for REST_AUTH_REGISTER_SERIALIZERS in settings.py and added my REGISTER_SERIALIZER there but I am getting this weird error on the terminal which appears to be coming from dj_rest_auth.registration.app_settings which says that: "RegisterSerializer = import_callable(serializers.get('REGISTER_SERIALIZER',DefaultRegisterSerializer)) AttributeError: 'tuple' object has no attribute 'get' -
django model property not showing up in object
so i have the mentioned model down here which I created a property for , for some reason my properties started to NOT show up in my objects class Cars(models.Model): datetime = models.DateTimeField() source = models.CharField(max_length=200) url = models.CharField(max_length=200) color = models.CharField(max_length=200,null=True,blank=True) year_built = models.CharField(max_length=200,null=True,blank=True) submission = models.CharField(max_length=200,null=True,blank=True) sell_type = models.CharField(max_length=200,null=True,blank=True) chassis = models.CharField(max_length=200,null=True,blank=True) engine = models.CharField(max_length=200,null=True,blank=True) city = models.CharField(max_length=200,null=True,blank=True) id = models.CharField(primary_key=True,max_length=200) title = models.CharField(max_length=200,null=True,blank=True) insurance_left = models.IntegerField(null=True,blank=True) body = models.CharField(max_length=200,null=True,blank=True) gearbox = models.CharField(max_length=200,null=True,blank=True) mileage = models.BigIntegerField(null=True,blank=True) price = models.BigIntegerField(null=True,blank=True) model_year = models.IntegerField(null=True,blank=True) category = models.CharField(max_length=200,null=True,blank=True) car = models.CharField(max_length=200,null=True,blank=True) car_type = models.CharField(max_length=200,null=True,blank=True) neighborhood = models.CharField(max_length=200,null=True,blank=True) img = models.CharField(max_length=300,null=True,blank=True) company = models.CharField(max_length=50,null=True,blank=True) @property def letstestproperty(self): return 'hello world' class Meta: verbose_name_plural = 'Car Records' I output my objects using Cars.objects.values() but there are no property field added to it -
RowNumber Window Query for Hiscores Ranking - Django
I'm trying to build a game hiscore view with rankings for my Django site, and I'm having some issues. The query I have is the following: row_number_rank = Window( expression=RowNumber(), partition_by=[F('score_type')], order_by=F('score').desc() ) hiscores = Hiscore.objects.annotate(rank=row_number_rank).values() The query above works perfectly, and properly assigns each row a rank according to how it compares to other scores within each score type. The result of this is the following: { 'id': 2, 'username': 'Bob', 'score_type': 'wins', 'score': 12, 'rank': 1 } { 'id': 1, 'username': 'John', 'score_type': 'wins', 'score': 5, 'rank': 2 } { 'id': 4, 'username': 'John', 'score_type': 'kills', 'score': 37, 'rank': 1 } { 'id': 3, 'username': 'John', 'score_type': 'kills', 'score': 5, 'rank': 2 } { 'id': 5, 'username': 'Bob', 'score_type': 'kills', 'score': 2, 'rank': 3 } The issue comes in when I want to retrieve only a specific user's scores from the above results. If I append a filter(username="Bob") the query is now: row_number_rank = Window( expression=RowNumber(), partition_by=[F('score_type')], order_by=F('score').desc() ) hiscores = Hiscore.objects.annotate(rank=row_number_rank).filter(username='Bob').values() Unexpectedly, adding this filter step has yielded the following incorrect results: { 'id': 2, 'username': 'Bob', 'score_type': 'wins', 'score': 12, 'rank': 1 } { 'id': 5, 'username': 'Bob', 'score_type': 'kills', 'score': 2, 'rank': 1 } Randomly, … -
How can i display the name of the MenuCard, the MenuCardCategories and the associated MenuCardFood in the .html document with jinja2?
i want to buld a menuCard, with categories and food. It should be possible to create multiple menusCards. #My Try enter image description here How can i display the name of the MenuCard, the MenuCardCategories and the associated MenuCardFood in the .html document with jinja2? The result should look like this... #first menuCard menuCardName menuCardCategoryName foodName foodName foodName menuCardCategoryName foodName foodName foodName #second menuCard menuCardName menuCardCategoryName foodName foodName -
TypeError: 'int' object is not iterable when passing arguments to function
I have a function that does some calculations based on a filtered queryset. I am seeking to pass arguments to the function to inform the filter. The basics: A view to test the output: def TestPlayerData(request): data = PlayerData(1,2) print(data) return HttpResponse(data) The function called is: def PlayerData(game, player): """This is a function based on EventFilterView""" opponent = [2] qs = Event.objects.filter(g_players=player).filter(g_name__in=game).filter(g_players__in=opponent) count_wins = len(qs.filter(g_winner=player)) count_played = len(qs.filter(g_players=player)) if count_played == 0: win_ratio = 'na' else: win_ratio = count_wins/count_played return count_wins, count_played, win_ratio The error received: "TypeError: 'int' object is not iterable" However, if I explicitly name the variables in the function rather than pass them from the view, the function works as expected -- like this: def PlayerData(): """This is a function based on EventFilterView""" game = [1] player =2 opponent = [2] qs = Event.objects.filter(g_players=player).filter(g_name__in=game).filter(g_players__in=opponent) count_wins = len(qs.filter(g_winner=player)) count_played = len(qs.filter(g_players=player)) if count_played == 0: win_ratio = 'na' else: win_ratio = count_wins/count_played return count_wins, count_played, win_ratio I am obviously missing some basic python understanding here and would appreciate a point in the right direction. -
PYTHON- Return minimum three digits
I want to return minium three digits maximum whatever it has it should return. I have tried following function, def get_code(model, prefix): content = model.objects.filter(code__startswith=prefix).last() last = None code_prefix = prefix if content: a_string = content.code split_strings = [] n = len(prefix) for index in range(0, len(a_string), n): split_strings.append(a_string[index: index + n]) last = int(split_strings[1]) if last is not None: suggested = last + 1 else: suggested = 1 return "{}{:03d}".format(code_prefix, suggested) Above code returns threedigits only if i have 4 didits it skips for calculation also. it takes only three digits for calucualtion also. how can i fix this??? -
can't open file '.manage.py': [Errno 2] No such file or directory
im trying to follow this tutorial > https://www.youtube.com/watch?v=JD-age0BPVo&t=793s and I'm getting the following error.. I'm using VSC on mac "" Sourav@Souravs-MBP Settle_Guide % python .\manage.py makemigrations /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file '.manage.py': [Errno 2] No such file or directory Sourav@Souravs-MBP Settle_Guide % "" I made sure that I'm on the ri8 directory while running the code..any suggestion? -
Disable custom action in Django based on some condition ( Value of some field in Model )
Disable custom action in Django based on some condition ( Value of some field in Model) . Created a custom action to publish excel in admin panel . I want to disable the publish action once data is published and status is changed to published ( Status is field in model ) -
Django - How to create groups per tenant?
I have a tenant model like this: class Tenant(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: db_table = "tenants" How do i modify groups field from PermissionsMixin, so that i can have separate groups per tenant. class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports email. """ email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) tenant = models.ForeignKey( Tenant, on_delete=models.CASCADE, null=True, db_column="tenant_id", blank=True ) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) mobile = PhoneNumberField(null=True) objects = UserManager() USERNAME_FIELD = "email" class Meta: db_table = "users" I want to use django-guardian for object level permissions. Im not sure how modifying the existing Group model will impact the working of that library. -
Display Multiple BlogPosts on Blog(Index)Page
I am trying to have the PostPage and EditorialPage show on the Blog(IndexPage). I know it has something to do with the fact that it's only calling the EditorialPage because of: def get_posts(self): return EditorialPage.objects.descendant_of(self).live().order_by("-post_date") But I don't know how to implement multiple pages. I seriously need help on this one. The code is below: ''' BLOG SECTION ''' class BlogPage(RoutablePageMixin, Page): banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [ ImageChooserPanel("banner_image"), FieldPanel("description", classname="full"), ] # PAGINATOR def get_context(self, request, *args, **kwargs): context = super(BlogPage, self).get_context(request, *args, **kwargs) context['blog_page'] = self # https://docs.djangoproject.com/en/3.1/topics/pagination/#using-paginator-in-a-view-function # Paginate all posts by 2 per page paginator = Paginator(self.posts, 3) # Try to get the ?page=x value page = request.GET.get("page") try: # If the page exists and the ?page=x is an int posts = paginator.page(page) except PageNotAnInteger: # If the ?page=x is not an int; show the first page posts = paginator.page(1) except EmptyPage: posts = paginator.object_list.none() context['posts'] = posts context['authors'] = BlogAuthor.objects.all() # Loop through all Authors of Single Posts return context # PAGINATOR END def get_posts(self): return EditorialPage.objects.descendant_of(self).live().order_by("-post_date") @route(r"^(\d{4})/$") @route(r"^(\d{4})/(\d{2})/$") @route(r"^(\d{4})/(\d{2})/(\d{2})/$") def post_by_date(self, request, year, month=None, day=None, *args, **kwargs): self.filter_type = 'date' self.filter_term = … -
Getting pg_config not found error while using docker-compose build command
I am trying to setup a new django project which has docker compose reuquirement , while setting up the project it is stalling while installing psycopg2 and giving errors , I am using a Macbook Air M1. Is this a docker issue or macbook issue? Attaching error screenshot for more details -
How do I prevent csrftoken error when sending via button with JSON?
I have very little knowledge of JSON and JavaScript yet I can't see what seems to be the problem to my code. I already tried this csrf validation for my reference, yet I still get the csrftoken error. I really need this to work on my Django project so please tell me what seems to be the problem here. app.js onSendButton(chatbox) { var textField = chatbox.querySelector('input'); let text1 = textField.value if (text1 === "") { return; } let msg1 = { name: "User", message: text1 } this.messages.push(msg1); fetch( $SCRIPT_ROOT+'/predict',{ method: 'POST', body: JSON.stringify({ message: text1 }), mode: 'cors', headers: { 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, }) .then(r => r.json()) .then(r => { let msg2 = { name: "Sam", message: r.answer }; this.messages.push(msg2); this.updateChatText(chatbox) textField.value = '' }).catch((error) => { console.error('Error:', error); this.updateChatText(chatbox) textField.value = '' }); } views.py def predict(request): text=request.get_json().get('message') #check if text is valid response=get_response(text) message= {'answer':response} return JsonResponse(message) base.html <body> <div class="container"> <div class="chatbox"> <div class="chatbox__support"> <div class="chatbox__header"> <div class="chatbox__image--header"> <img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image"> </div> <div class="chatbox__content--header"> <h4 class="chatbox__heading--header">Chat support</h4> <p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p> </div> </div> <div class="chatbox__messages"> <div></div> </div> <div class="chatbox__footer"> <input type="text" placeholder="Write a message..."> <button class="chatbox__send--footer send__button">Send</button> </div> … -
Pytest: Database access denied while running unit test
When I run my unit test using Django-pytest I keep getting the following error. django.db.utils.OperationalError: (1045, "Access denied for user 'ruach'@'localhost' (using password: YES)"). I am using an sqlite database locally which requires no password and using the decorator @pytest.mark.django_db to allow access to the database so I am unsure what else could be causing this. I have run unit tests successfully in the past in the exact same so I am puzzled as to what is causing test runner to be denied access. -
Django - AWS S3 Bucket - Showing images/css but not javascript/webfont and file uploads
I am making a portfolio website using django. Everything is working well on my local machine. I decided to use AWS S3 buckets to host my static files. After following a few tutorials I was able to make a bucket and link my account over. The issue I have now is that the images and css loads fine on my website, however the webfonts and javascript files seem to not work. I also have a link to download my resume, but that does not work. When clicking on the files it gives me an error of: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>resume.pdf</Key> <RequestId>xxx</RequestId> <HostId>xxx</HostId> </Error> Interestingly the url in the browser seems to be attempting to pull from AWS. When I go into the S3 bucket I see all files available. When opening images on my website they are properly pulling from AWS. My CORS is set to: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "POST", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] And settings.py is: AWS_S3_REGION_NAME = 'us-east-2' # Your region … -
Django conversation categories for messages with ManyToMany
I am making a kind of social network in Django. This explains basically what I'm doing: Django - Private messaging conversation view The conversations are exclusively between two people, not more. I have a conversation model because when they to their messages, I want the user to have a list of the other users that they have messages with. Here is the relevant view: def writemessage(request, id): profile = Profile.objects.get(id=id) context = { 'profile': profile, } if request.method == 'POST': sender = request.user receiver = profile.user content = request.POST['content'] timestamp = datetime.now() print(sender, receiver, content, timestamp) record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp) record.save() senderprofile = Profile.objects.get(user=sender) receiverprofile = Profile.objects.get(user=receiver) record.conversation.add(senderprofile) record.conversation.add(receiverprofile) print(senderprofile, receiverprofile) return redirect('messagespage') return render(request, 'thecode/writemessage.html', context) Here are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=60) country = models.CharField(max_length=60) skillstolearn = models.CharField(max_length=200) skillstoteach = models.CharField(max_length=200) description = models.TextField() def __str__(self): return self.user.username class Conversation(models.Model): participants = models.ManyToManyField(User) def __str__(self): return self.participants class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') content = models.TextField() conversation = models.ForeignKey(Conversation, default=None, on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField() def __str__(self): return self.sender.username + ' … -
Django argparse: Unrecognized Arguments --settings?
I've looked at the other SO threads about unrecognized argparse arguments, but none of them seem to match up with my situation. Here's my argparse code, located at apps/create_pdf/management/commands/create_pdf.py: from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'html to pdf for specified website.' def add_arguments(self, parser): print('cp#1') parser = argparse.ArgumentParser(description='html to pdf for specified website') parser.add_argument('-w', '--website', nargs =1, action = 'store', choices = ['SITE_1', 'SITE_2'], default='', help='site to be scraped.') args = parser.parse_args() print(args) breakpoint() def handle(self, *args, **options): print('cp#2') # create_pdf_from_html() I run this from the terminal like so: python3 manage.py create_pdf --website=SITE_1 --settings=server_config.settings ...and I'm getting this error: manage.py: error: unrecognized arguments: create_pdf --settings=server_config.settings The settings path is correct and if I'm not using argparse, everything runs fine. What am I missing?