Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving data from a dynamically generated HTML table/grid to a database
I'm developing a web application and one of the requirements is for the user to enter data into a dynamically-generated HTML grid/table. An admin user can log into the Django Admin interface and create some entries which will represent the columns and rows of the grid, and then a dynamic grid is genereted based on these values. In this example, the admin user has entered "Store #1", Store #2", etc as the rows, and "Chips", "Chocolates", and "Soda" as the columns. These rows and columns are then used to generate a grid which is rendered in a Django template by the code below: <table class="tg"> <thead> <th rowspan="3"></th> <tr> <td class="tg-title" colspan="4">Inventory</td> </tr> <tr> {% for i in items %} <td class="tg-column">{{ i }}</td> {% endfor %} </tr> </thead> <tbody> {% for i in stores %} <tr> <td class="tg-column">{{ i }}</td> {% for i in items %} <td class="tg-cell"><input type="number" min="0" max="255" value="0"></td> {% endfor %} </tr> {% endfor %} <tr> <td class="tg-totals">Totals</td> {% for i in items %} <td class="tg-totals-values">0</td> {% endfor %} </tr> </tbody> </table> The above code renders like this: rendered_image Visually, this is fine, but I can't for the life of me figure out how I'm … -
When click a link in a link list generated by for loop, make the corresponding checkbox checked instead of the first checkbox
I have used Django to develop a web app. The front end used Django template engine. In the HTML, a link list is generated by a for loop, before which a check box is shown corresponding to this link. I want to achieve this: when click the link, the corresponding checkbox would be checked. But now as I only has one id(in the loop I do not know how to generate different id in one line), o matter I click which link generated by the loop, always see the first checked box checked instead of the corresponding one. HTML: <td>{% for course_for_select in query_results_2 %} &nbsp;<input type="checkbox" name="course_select" value=" {{course_for_select}}" id="addModal-body">&nbsp;<a href="#" name="course_select_2" id="href_course" onclick="document.getElementById('addModal-body').checked = true;this.closest('form').submit();return false;">&nbsp; {{course_for_select}}</a><br> {% endfor %}</td> How to let the corresponding checkbox checked after click the link behind, instead of constantly see the first one being checked? -
How to count video views for each user in django
In my recent project i want users to be able to see the number of videos they have watch. Like Total views today: Total views yesterday: Total views this month All time total views: I want all of this information in the user dashboard. I know how to get a total number of views on a video. But how do i make the video view count for each specific user. That when the user watchs a video on the website it counts as one in his or her dashboard..am using python and django. Any idea on how i can do this? -
Django- how to hyphenate TextField in URLs
I am trying to make my model so that the URL slug is hyphenated between spaces in the slug field by default. The slug should be limited to only the first six words in TextField. The TextField() called questionToProblem in the same model. Here's what I have: class Problem(models.Model): free = models.CharField(max_length = 1, choices = Free) questionToProblem = models.TextField() solutionToProblem = models.TextField() slug = models.CharField(max_length = 250, unique = True) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) plainText = models.TextField(default= 'temp') class Meta: ordering = ('questionToProblem',) def get_url(self): return reverse('solution_details', args = [self.topic.slug, self.slug]) def __str__(self): return self.questionToProblem Ideally, here's what I want the URL to look like, if the questionToProblem was "How many bananas do I have in total?", and the Topic key was "modeltopic": http://127.0.0.1:8000/modeltopic/How-many-bananas-do-I-have -
I want to keep a long process running in the background in django
I am a beginner in django. I want to keep running long processes in django in the background. And I want to keep it running unless I explicitly end that process. I can't figure out where and how to add the following code to django. import threading import asyncio class long_task: def __init__(self): self.continue_flag = True async def long_task(self,): print('long task start...') i = 0 while self.continue_flag: print(i) await asyncio.sleep(3) i = i+1 def stop(self): self.continue_flag = False def run_loop(loop): asyncio.set_event_loop(loop) print('main loop start...') loop.run_forever() def ask_loop_stop(loop): print("main loop stop") loop.call_soon_threadsafe(loop.stop) loop = asyncio.get_event_loop() threading.Thread(target=run_loop, args=(loop,)).start() print('main loop is ready') long_task_1 = long_task() asyncio.run_coroutine_threadsafe(long_task_1.long_task(), loop) I will elaborate on what I want to do. Run a loop when django starts. Add long_task to the loop at any given time (when a specific event occurs by monitoring an external site). Keep the program running in the background so that the site can be viewed. In the future I would like to display the results of this program on a page. Close the loop at another time (during maintenance). Here's what I've tried Register and execute as a task using celery and celery-beat. => Can't specify that a program should be run … -
check many to many field exists in parent class
this is my blog model class Blog(models.Model): title = models.CharField(max_length=80, blank=True, null=True) content = models.TextField(blank=True, null=True) pricing_tier = models.ManyToManyField(Pricing, related_name='paid_blogs', verbose_name='Visibility', blank=True) I want to create a notification with post save signal if pricing tier has free-trial slug exists, so I tried as follows def blog_notify_receiver(sender, instance, created, *args, **kwargs): if created and instance.pricing_tier.filter(slug='free-trial').exists(): try: BlogNotification.objects.create() except: pass post_save.connect(blog_notify_receiver, sender=Blog) this doesn't work as it always gives none, the following print shows empty queryset, eventhough the data exists in the pricing tier field if created: print(instance.pricing_tier.all()) How I can check if data exixts in the pricing tier field which is a many to many field of a parent class -
How to get Authorization token in views.py (DRF)
class RecordDetailView(generics.RetrieveAPIView): serializer_class = RecordsSerializer permission_classes = [IsAuthenticated] lookup_url_kwarg = 'pk' def get(self, request, format=None, *args, **kwargs): item = request.GET.get(self.lookup_url_kwarg) token = request.META.get('HTTP_AUTHORIZATION') print("token", token) user_from_token = Token.objects.filter(key=token).first() record = Records.objects.filter(id=item).first() if record.author.username != user_from_token.user.username: return Response({'response': "You dont have permission to view that"}, status=status.HTTP_403_FORBIDDEN) else: data = get_object_or_404(Records, id=item) return Response(data, status=status.HTTP_200_OK) i tried to get the data from postman and i filled authorization field in headers with the user token and I'm trying to print the token in my views but it returns None, Any idea how to get the token -
Download image on heroku
i have a simple function in fastapi python url="some_random_video_url_here" re = requests.get(url) with open("download/hello.png", 'wb') as file: #save hello.png to download folder file.write(re.content) file.close() this function work locally fine and download image and any files bot when upload on heroku not download image and save in staticsFiles folder please help -
Struggling to deploy django project on heroku
Build log: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.9.5 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.3.4 Downloading asgiref-3.3.4-py3-none-any.whl (22 kB) Collecting boto3==1.17.79 Downloading boto3-1.17.79-py2.py3-none-any.whl (131 kB) Collecting botocore==1.20.79 Downloading botocore-1.20.79-py2.py3-none-any.whl (7.6 MB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.2.3 Downloading Django-3.2.3-py3-none-any.whl (7.9 MB) Collecting django-environ==0.4.5 Downloading django_environ-0.4.5-py2.py3-none-any.whl (21 kB) Collecting django-on-heroku==1.1.2 Downloading django_on_heroku-1.1.2-py2.py3-none-any.whl (6.1 kB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) Collecting jmespath==0.10.0 Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB) Collecting psycopg2==2.8.6 Downloading psycopg2-2.8.6.tar.gz (383 kB) Collecting psycopg2-binary==2.8.6 Downloading psycopg2_binary-2.8.6-cp39-cp39-manylinux1_x86_64.whl (3.0 MB) Collecting python-dateutil==2.8.1 Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting pytz==2021.1 Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB) Collecting s3transfer==0.4.2 Downloading s3transfer-0.4.2-py2.py3-none-any.whl (79 kB) Collecting six==1.16.0 Downloading six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting sqlparse==0.4.1 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting urllib3==1.26.4 Downloading urllib3-1.26.4-py2.py3-none-any.whl (153 kB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py): started Building wheel for psycopg2 (setup.py): finished with status 'done' Created wheel for psycopg2: filename=psycopg2-2.8.6-cp39-cp39-linux_x86_64.whl size=523851 sha256=21de473d6954ed53994462119b202ca6439f637a2cd8ccea561280b7101f3516 Stored in directory: /tmp/pip-ephem-wheel-cache-gid0o7zt/wheels/a2/07/10/a9a82e72d50feb8d646acde6a88000bbf2ca0f82e41aea438a Successfully built psycopg2 Installing collected packages: asgiref, jmespath, … -
DRF get_queryset check if in ManyToManyField
I have a model like this: class Project(models.Model): name = models.CharField("Name", max_length=8, unique=True) status = models.CharField( "Status", max_length=1, choices=[("O", "Open"), ("C", "Closed")], default="O", ) description = models.CharField("Description", max_length=3000, default="") owner = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="project_owner" ) participants = models.ManyToManyField(User, related_name="project_participants", blank=True) created_at = models.DateTimeField(auto_now_add=True) Now in this model's ViewSet I have a get_queryset method: def get_queryset(self): if self.request.user.is_superuser: return Project.objects.all() else: return Project.objects.filter(owner=self.request.user.id) So when I get a project or projects, I only search for the projects that a user (hidden in the request, in JWT) owns. But now I thought about searching for the projects that user participates in (so the user appears in participants field list). How can I do that in get_queryset? -
How do I customize the Django "Password_reset_confirm" form?
I need to modify the labels and give a max_length to the django form for restoring password (The one after clicking on an email link to restore the password). I have done it for AuthenticationForm, UserCreationForm, UserChangeForm and PasswordChangeForm so far but i don't get to find a way to do it for the Password_reset_confirm Form. This example for the AuthenticationForm shows how I'm overriding all the forms. Forms.py from django.contrib.auth.forms import AuthenticationForm class loginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(), max_length=64) password = forms.CharField(widget=forms.PasswordInput(), max_length=64) class Meta: model = User fields = ( "username", "password" ) -
How to use a Django modelformset with extra fields?
Here is the example of an inline formset from Django's docs: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) >>> from django.forms import inlineformset_factory >>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',)) >>> author = Author.objects.get(name='Mike Royko') >>> formset = BookFormSet(instance=author) Suppose I want to let someone enter multiple book reviews at once, where each book review is for a particular book. (I'll have a query in my code to get the books to review.) How do I display a formset (model formset? inline formset?) of BookReview, but with some of the book data (e.g., title) on the form, so people know which book they are reviewing? So, the model is class BookReview(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) review_text = models.CharField(max_length=1000) Now how to initialize the formset? Below is some code, but based on my actual example (not book reviews), it's not going well. Sample code to initialize a formset (but incomplete): # pick some books to review # this could change, I don't want to couple it directly to the formset books_to_review = Book.objects.filter(author=an_author)[:3] class BookReviewForm(models.ModelForm): class Meta: model = BookReview fields = ('review_text') # How do I get Book.title (and possibly … -
Django EmalField form input is always set to active
so I have this form as on this image below. The point is that if the user clicks any of the fields, the text (which is essentialy a label, not a placeholder) rises up which shows that the clicked input field is active. However, I've tried to create a customized user creation in Django, which is just to have the email as the main user identificator, not the username. Now everything else works as supposed, but the thing is that the email field always appears as active (you know, the css attribute). I will now paste a scary amount of code and I will be happy if you could find out what's wrong. Sorry for the trouble `class UserManager(BaseUserManager): # handles user creation, havent' tested yet def create_user(self, email, username, password=None): # creates user with email as their id if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') if not password: raise ValueError('Users must have a password') user = self.model( email=self.normalize_email(email), password=password, username=username, ) user.set_password(password) user.save(user=self._db) return user class User(AbstractBaseUser): # user model, was just trying out some stuff username = models.CharField(verbose_name='username', max_length=30) email = models.EmailField(verbose_name='email', unique=True, max_length=60) date_joined = … -
In my PayPal server side integration, the payment popup immediately closes. How do I fix this?
I'm trying to setup paypal server side integration, but I keep stumbling on what is likely a very simple issue. The paypal payment browser window briefly appears to be loading, but it closes before I can do anything; it doesn't reach the login page or anything. In my django logs, I don't see any errors. Similarly, nothing stands out to me when I search the network activity. If I use a direct link to the paypal authorization page, I don't have any issues. Views.py def setUpAuthorization(request, max_price = 100): environment = SandboxEnvironment(client_id = settings.PAYPAL_CLIENT_ID , client_secret = settings.PAYPAL_CLIENT_SECRET) client = PayPalHttpClient(environment) # get_item request = OrdersCreateRequest() # Make initial authorization request.request_body( { "intent": "AUTHORIZE", "application_context": { "return_url": "https://www.example.com", "cancel_url": "https://www.examples.com", }, "purchase_units":[ { "description": "DESCRIPTION", "amount": { "currency_code": "USD", "value": max_price, }, } ]} ) response = client.execute(request) data = response.result.__dict__['_dict'] links = data['links'] for link in links: if link['rel'] == 'approve': paypal_link = link['href'] # redirect(paypal_link) return JsonResponse(data) html <div id="paypal-button-container"></div> <script src="https://www.paypal.com/sdk/js?client-id={{client_id}}"> </script> <script> var CSRF_TOKEN = '{{ csrf_token }}'; </script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; … -
How to load an online JS file in a webpage in Django Application
I have a Django application with a static folder which contains static files. I am loading them using this code: {% load static %} <script src="{% static 'cytoscape-chola.js' %}"></script> <script src="{% static 'layout-base.js' %}"></script> Now I need to add another script which is located online. When I use this script outside a Django app, it works totally fine. But when I am adding it to the html in the Django app, it is not being detected and gives an error when I try to access its functions: <script src="https://unpkg.com/cytoscape-cose-bilkent/cytoscape-cose-bilkent.js"></script> How can my code detect this file? -
Django send user an email with a user link for setting a password
I'm a newbie to Django and I'm learning from its documentation. In my Django app, I'm attempting to have the admin create the users and once they have been created, I would like them to be sent an email that contains a link that enables the user to set up their own password for logging in. Below is my admin.py file: class UserAuthenticationAdmin(admin.ModelAdmin): list_display = ('first_name','last_name','email','department',) list_filter = ('date_joined',) ordering = ('first_name',) search_fields = ('email',) add_form_template = 'admin/change_form.html' form = UserAuthenticationForm fieldsets = ( (None, { 'fields': (('first_name','last_name','password'),'email','department','is_active','is_staff','groups',) }), ) Below is the email html template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Successful Account Creation</title> </head> <body> <p>Dear {{ first_name }} {{ last_name }},</p> <p>Your account has successfully been created.</p> <p>Please follow this link, <a href="{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}"> your account </a>, to set up your password. </p><br> <p>Thanks</p> </body> </html> Below is the UserAuthenticationForm class in the forms.py file that creates a default password for the user: class UserAuthenticationForm(forms.ModelForm): password = forms.CharField( widget=forms.PasswordInput( attrs={ "placeholder" : "Password", "class": "form-control", "value":"pass@123", } )) class Meta: model = UserAuthentication fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, … -
Can't connect Django to AWS S3
I want to connect my AWS s3 with Django. I've already made a bucket and generated keys. When I want to post a photo it returns null in "photo" attribute instead of a path to s3 media folder. Here are my settings.py, models.py and views.py. What am I doing wrong? settings.py INSTALLED_APPS = [ ... 'storages', ... ] ... STATIC_URL = '/static/' MEDIA_URL = '/media/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') DEFAULT_FILE_STORAGE = 'storages.backend.s3boto3.S3Boto3Storage' AWS_QUERYSTRING_AUTH = False models.py class Horse(models.Model): name = models.CharField(max_length=30, blank=False, null=False) birthdate = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to = 'media/') class Meta: managed = True db_table = 'horse' ordering = ['name'] def __str__(self): return str(self.name) views.py class HorseView(APIView): def post (self, request, format = None): serializer = self.serializer_class (data = request.data) if serializer.is_valid(): horse_name = serializer.data.get('name') horse_birthdate = serializer.data.get('birthdate') horse_photo = serializer.data.get('photo') horse_data = Horse(name = horse_name, birthdate= horse_birthdate, photo = horse_photo) horse_data.save() return Response(CreateHorseDataSerializer(horse_data).data, status=status.HTTP_201_CREATED) return Response(serializer.errors) -
Django "Internal Server Error" and "MultiValueDictKeyError" when calling external function
I am running a django project on ubuntu that is supposed to build a website where I can upload an image run an external script to modify the image on click when uploaded The uploading process works fine, but when I try to run the external script I get an the internal server error as seen below. Is this because of the added b' and \n in the path? If so, how can I solve that, please? Full Code can be found here https://github.com/hackanons/button-python-click/tree/master/Image%20Edit%20Html%20Button%20Run%20Python%20Script/buttonpython Thanks a lot for help image is birdie1.png file raw url birdie1.png file full url /home/felix/ucmr/button-python-click/Image_Edit_Html_Button_Run_Python_Script/buttonpython/media/birdie1.png template url /media/birdie1.png CompletedProcess(args=['/home/felix/anaconda3/envs/ucmr/bin/python', '//home//felix//ucmr//button-python-click//Image_Edit_Html_Button_Run_Python_Script//test.py', 'upload'], returncode=0, stdout=b'Hi upload welcome to Hackanons & time is 2021-06-01 20:35:53.229957\n') b'/media/temp.png\n' [01/Jun/2021 20:35:53] "POST /external/ HTTP/1.1" 200 1074 [01/Jun/2021 20:35:53] "GET /media/birdie1.png HTTP/1.1" 200 103100 Internal Server Error: /external/b'/media/temp.png/n' Traceback (most recent call last): File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in __getitem__ list_ = super().__getitem__(key) KeyError: 'image' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/felix/ucmr/button-python-click/Image_Edit_Html_Button_Run_Python_Script/buttonpython/buttonpython/views.py", line 19, … -
Is there a good django chat package to begin with and modify it?
I am looking for a good chat application to start with and continue developing it. I tried peivate-django-chat1 & 2 by Bearle. But the new one requires redis. I don't want a huge list of dependencies that would become a problem. Any help with just basic chat app and then that could be tweaked and modified. Please be patient and don't create any closing votes as I want a definite answer with this question. Thanks in advance. -
How do I optimize this Django query that uses an annotated Subquery?
I have an approval queue Django app that has two models: Flow and Recipient. The Flow keeps track of each "request" in the approval queue system, and the Recipient tracks who can approve each step in the queue, and can be related to a Django User or Group. Here's a simplified snippet of what these models look like: class Flow(models.Model): current_step = models.IntegerField(default=0) class Recipient(models.Model): step = models.IntegerField() user = models.ForeignKey( User, on_delete=models.PROTECT, null=True, blank=True) name = models.CharField(max_length=255) flow = models.ForeignKey( Flow, on_delete=models.PROTECT, related_name='recipients' If an approval queue has 3 people (recipients) in it, each Recipient's step will represent its position in the queue. The first person's Recipient will have step == 0, the next person will have a step == 1, and so on. The Flow.current_step is updated when the approval queue progresses from one person to another. My goal is to query for Recipients, and include an annotated field named assigned_to which will contain either User.first_name or the name of the Recipient of the "current" Recipient. The current Recipient is the one whose Recipient.step == Flow.current_step. All Recipients will either have user or name set. Here's my first attempt at implementing this query: current_rec = Recipient.objects.filter(flow=OuterRef('flow'), step=OuterRef('flow__current_step')).select_related('user') qs … -
Update many in mondodb in python?
I want to update records in mongodb using python: I am using this code it does the job. However the length of data is around one million and it takes a lot of time. new_data = [] for x in data: if collection.find({'ptr_id':x["ptr_id"]}).count() < 0 : new_data += [x] else: bulkop.find({'ptr_id':x["ptr_id"]}).update({ "$set": x }) try: result = bulkop.execute() except: ... How can I run this faster. FYI collection.find({'ptr_id':x["ptr_id"]}).count() will always be 0 or 1 -
Should I be using Celery/Redis in my Django application?
I have a Django application that is designed to be used as a companion tool for sportsbooks or DFS sites. I am largely self-taught, so I have been adopting a more "go with what works" approach and then going back to revise my methods as I learn better ways to create the app. I have several tables from scraped data in CSV format that I import into my DB with shell scripts. For example, one table is for starting lineups, and another is for player stats. I then have methods set up in my models.py to take that imported data and turn it into data that I want to use. I found out quickly that trying to call a large group of objects and the values from their method functions was not at all efficient. I get the data I need via the methods because a lot of it is based on data from multiple tables (for example, I might want the start time of a game from the starting lineups table for a player object.) The current solution that I have is to use Threading to run a function every few minutes to calculate the results of every method … -
Is there a way to hot build react to use with Django?
I am trying to build a Django and react app, but I want Django to serve the html. At the moment I have to keep building the scripts (with webpack) after I make changes, which is costing development time. Is there a way to build the main.js file everytime I make changes? Same thing that react-scripts does but without the {host}:3000 server running -
The problem of getting an object created thanks to TabularInline
My model A uses TabularInline, which creates objects of model A1. I want to output information about object A1 to the console when I save object A. I use the clean/save method. When I save an existing A object, it's fine, but if I create one, it outputs an error. How can I track the creation of object A1 in object A? Thank you. class A(models.Model): name = models.CharField(max_length=120) def save(self, *args, **kwargs): super().save(*args, **kwargs) print(self.a_name.all()) class A1(models.Model): description = models.CharField(max_length=120) name = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_name") error: 'A' object has no attribute 'a_name' It's like the A object is saved first, and only then the A1 objects are created and substituted into A. I think that's how it works, that's why I can't access -
Get all parameters and their values in a request in Django
I have a get request being sent to my Django project with a list of parameters. GET /site/login? _name=bill&_last_name=Smith&_favorite_food=wings I need to get each parameter and it's value. What would be the best way to do this? I know that in Django you can do print(request.data) but I need the parameters.