Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's contrib auth + allauth's MFA - 2FA Setup
I added a feature called 2FA to my django project using django-allauth[mfa]. I also setuped the social account login process using google. login form is from django.contrib.auth 2FA form is from allauth.mfa authentication/views.py - my custom django contrib auth view class CustomLoginView(LoginView): form_class = UserLoginForm template_name='authentication/login.html' redirect_authenticated_user=True mfa_enabled = False def dispatch(self, request, *args, **kwargs): if self.redirect_authenticated_user and self.request.user.is_authenticated: if self.mfa_enabled: return HttpResponseRedirect(resolve_url('account_login')) else: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): user = form.get_user() if self.has_mfa(user): self.mfa_enabled = True print("2FA enabled") else: auth_login(self.request, user) return super().form_valid(form) def has_mfa(self, user): return is_mfa_enabled(user) and this code is not working at all. After login successed, it redirected to homepage. I want to redirect to 2FA form if user account is 2fa activated. path('accounts/2fa/authenticate/', views.Custom2FAAuthenticateView.as_view(), name='account_login'), this is my customized 2FA auth form. It worked with social account like google, it redirect to 2FA form if account is 2FA activated. this is my 2FA auth customized view file # 2FA authentication view for social login class Custom2FAAuthenticateView(Base2FAAuthenticateView): template_name = "authentication/mfa/authenticate.html" I tried many ways. when … -
How to make Django Manager and Model's interactions follow the Open/Closed Principle?
I am designing models for my Django App and am concerned with decoupling the caller's logic from the model's implementation, so that future changes to the model itself do not require changes downstream in the codebase. In short adhering to the Open/Closed Principle (OCP). I am wondering what is a best practice to implement this while leveraging Django's framework best. Conceptually, I believe it would make sense to do the following: from django.db import models class FooManager(models.Manager): def is_active(self): return self.filter(is_active=True) class Foo(models.Model): _bar = models.CharField(max_length=100, db_column="bar") is_active = models.BooleanField(default=True) objects = FooManager() @property def bar(self): return self._bar @bar.setter def bar(self, value): if not self._bar: self._bar = value else: #some setter logic pass Custom Manager for Query Logic For each model, a custom Manager is defined and is responsible for handling all sorts of filtering logic on the model. E.g. instead of calling Foo.objects.filter(is_active=True), caller would call Foo.objects.is_active(). In the future, if the implementation logic of is_active changes, the caller won't need to change it's logic, keeping things OCP. Encapsulation of model fields For each field in a model, @property are defined for getters and setters allowing to change the underlying model fields. Minimal coupling Coupling is only kept on … -
Freeradius server won't allow multiple aaa users with same auth ip
So I have been assigned to the freeradius problem, I can see the tenants in proxy.conf. Problem is arising when I am trying to register multple users from frontend with same Auth IP. It will accept same accounting IP but not same Auth IP. How can i configure so that it can allow multiple user types from same Auth IP? I tried exploring queries.conf, proxy.conf, clients.conf and django backend logic thats creating the AAA users. Nowhere I found a specific logic restricting the duplicate IP for same users. I was told its some limitation of the server. Was looking for ways to reconfigure or bypass to solve the problem. -
Django - HTML table issue (probably with for loop)
I want to use dataTables in my HTML template in Django. .html file: <!DOCTYPE html> <html lang="en"> <head> <title>FPL projections - Team list</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.css"> <script type="text/javascript" src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script> <style> section{ width: 70%; margin: 30px auto; } #teamTable th, #teamTable td{ border: 1px solid #ccc; text-align: left; } #teamTable thead { background: #f2f2f2; } </style> </head> <body> <section> {% extends "fantasy_menu.html" %} {% block content %} <h1>Team List</h1> <table id="teamTable" width="100%"> <thead> <tr> <th><strong>Name</strong></th> <th>Home for</th> <th>Home ag</th> <th>Away for</th> <th>Away ag</th> <th>opp1</th> <th>opp2</th> <th>opp3</th> <th>opp4</th> <th>opp5</th> </tr> </thead> <tbody> {% for team in team_list %} <tr> <td><a href="{% url 'fantasy:team' team.ref_id %}"><strong>{{team.name}}</strong></a> ({{team.ref_id}}) </td> <td>{{team.avg_goal_for_home}}</td> <td>{{team.avg_goal_ag_home}}</td> <td>{{team.avg_goal_for_away}}</td> <td>{{team.avg_goal_ag_away}}</td> <td>{{team.opp1}}</td> <td>{{team.opp2}}</td> <td>{{team.opp3}}</td> <td>{{team.opp4}}</td> <td>{{team.opp5}}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready( function () { $('#teamTable').DataTable(); } ); </script> <br /> <br /> <p><a href="{% url 'fantasy:player_list' %}">Player projections</a></p> <p><a href="{% url 'fantasy:index' %}">Back to main page</a></p> {% endblock %} {% block footer %} {% endblock %} </section> </body> </html> The JavaScript (that would affect the headers of the table) doesn't seem to run because the headers are not clickable (for sorting for instance). Current weblink of what's being displayed (before it gets fixed...): http://texouze.pythonanywhere.com/fantasy/teams/ When … -
What is a GenericForeignKey?
I have read Django's documentation on GenericForeignKeys and found it to be extremely confusing. I don't understand what the variables I am giving it is, and therfore I have no idea how it works, and therefore I have no idea what it is - and everything I see only makes me more confused, because I still can't find anything clearly explaining, at its root, what is it and how does it works. Can someone please start from the beginning and explain what a GenericForeignKey is, and how it works? -
How to dynamically generate and execute unit tests for multiple programming languages as strings?
I am working on a system where solutions to problems are validated using predefined unit test cases. The system supports multiple programming languages, and the generated test cases need to be converted into strings for execution by an API. The Problem: To test submitted solutions, I need to dynamically generate unit test cases for each programming language. The generated tests should: Include predefined base test cases for each problem (e.g., validating a palindrome function). Allow dynamic addition of custom test cases (e.g., user-defined edge cases). The generated tests must then be converted to a string and sent to Judge0 for execution. Current Approach: For Python: I use unittest to define base test cases in a file (e.g., test_palindrome.py). Custom test cases are dynamically added as new test methods. Both base and custom test cases are combined into a single string. The following code will already be existing with the is_palindrome.py file but new custom test cases will need to be added on. import unittest class TestPalindrome(unittest.TestCase): def test_base_cases(self): self.assertTrue(is_palindrome("radar")) self.assertFalse(is_palindrome("hello")) for example, for the given the user input: [ { "input": "'level'", "expected_output": "True" }, { "input": "'world'", "expected_output": "False" } ] I would need to generate a string of … -
Django migrations failing in Docker container after adding new model
I am running a Django project inside a Docker container, and I am facing an issue with migrations after adding a new model to models.py. When I try to apply the migrations, the system looks for the old migrations, but since I rebuild the app via Docker, those migrations are missing. When I try to force Django to ignore the old migrations, it attempts to create tables that already exist, and the process fails because of that. If I allow it to run the migrations normally, it tries to re-apply the migrations that have already been executed, which leads to errors. I need a way to: • Skip old migrations during the rebuild. • Ensure the new tables are created without conflicting with existing ones. • Prevent Django from reapplying migrations that are already done. How can I resolve this migration issue in Docker? Any help would be appreciated! Here’s what I have in my Dockerfile (now there is that problem with creating existing tables): FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . # Vyčistíme migrace a vytvoříme nové při buildu image RUN rm -rf api/migrations/* && \ touch api/migrations/__init__.py # Instalace netcat … -
Django: NameError with instance of model with Generic Foreign Field in, created by post_save signal
I have 3 models that I am dealing with here: SurveyQuestion, Update, and Notification. I use a post_save signal to create an instance of the Notification model whenever an instance of SurveyQuestion or Update was created. The Notification model has a GenericForeignKey which goes to whichever model created it. Inside the Notification model I try to use the ForeignKey to set __str__ as the title field of the instance of the model that created it. Like so: class Notification(models.Model): source_object = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() source = GenericForeignKey("source_object", "object_id") #more stuff def __str__(self): return f'{self.source.title} notification' I am able to create instances of SurveyQuestion and Update from the admin panel, which is then (supposed to be) creating an instance of Notification. However, when I query instances of Notification in the shell: from hotline.models import Notification notifications = Notification.objects.all() for notification in notifications: print (f"Notification object: {notification}") NoneType --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 for notification in notifications: ----> 2 print (notification) File ~/ygzsey/hotline/models.py:27, in Notification.__str__(self) 26 def __str__(self): ---> 27 return f'{self.source.title} notification' AttributeError: 'NoneType' object has no attribute 'title' When I query instances of SurveyQuestion: from hotline.models import SurveyQuestion surveys = SurveyQuestion.objects.all() for survey in surveys: … -
How to allow the admin to change the uses's password in the Django admin panel?
I want to allow the admin to change any user's pasword, but th admin panel doesn't have that option anymore. I had to extend the abstract user class to add some fields to my users when they are created. I wanted to know what I can do to allow my admin users to change the user's passowrds. This is my User class: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): numero_de_empleado= models.CharField(max_length=100, unique=True, default="0", verbose_name="Puente") class Meta: permissions = [ ("view_retiro", "Ver retiro"), ("make_changes","Crear dotaciones y arqueos"), ("create_user","Crear un usuario"), ("view_all","Ver toda la información") ] And this is my admin.py from my user app: from django.contrib import admin from .models import User # Register your models here. admin.site.register(User) I am not an expert in django and i don't lnow why it's doing this, Thanks in advance. -
How to Disable Re-authentication in Django's allauth MFA's TOTP
I am trying to customize the reauthentication form of the mfa. I aslo customized the TOTP activate and deactivate form and it works, but now i am struggling to customize the reauthentication form with my defined route name in django. and is there any way to disable this reauth of the allauth mfa - 2fa settings/urls.py path('mfa/reauthenticate/', views.CustomReauthenticateView.as_view(), name='mfa_reauthenticate'), settings/views.py class CustomReauthenticateView(BaseReauthenticateView): template_name = "settings/mfa/reauthenticate.html" # Ensure the correct template is used def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['custom_message'] = 'This is a custom message for reauthentication.' return context def form_valid(self, form): response = super().form_valid(form) return response but it always rendering to localhost:8000/accounts/reauthenticate/?next=... and not my defined url. I also tried another way by customizing the allauth.account.decoders - reauthentication_required but not work Please someone help, that i want to redirect to my customize reauth form -
How to add dict to QuerySet
I have a result from the DB which I want to enriche with a row. A queryset is a dict right? So I created a new dict and wanted to merge those two. But it told me you cant merge a dict and QuerySet. How can this be done? -
Localhost route can't load static file
I am currently creating a dockerized web application. It is composed of the following elements : React for the frontend (with the routes managed by react-router-dom) Django for the backend PostgreSQL for the database managment Nginx for the reverse proxy I have created the reverse proxy for the back-end and front-end. I have created a route named /element/:id (id is an URL parameter) which would allowed me to see the informations of an object stored in a database. Unfortunately, when I try to load the page localhost/element/1, the page displayed nothing. In the web console, I have an error, telling me Uncaught SyntaxError: Unexpected token '<' for the file http://localhost/element/static/js/file.js. After inspection, he loads the index.html file. The home page works without a problem. Here is my nginx configuration file : server{ include /etc/nginx/mime.types; listen 80 default_server; error_log /var/log/nginx/app-error.log info; access_log /var/log/nginx/app.log main; location /admin/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://admin-backend/admin/; } location /api/v1/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://admin-backend/api/v1/; } location /static/ { alias /staticfiles/$1; } error_page 500 502 503 504 /50x.html; location = /50x.html { root … -
Django request.GET adds and extra quote to the data
When I pass my parameters via Django request.GET I get an extra comma in the dictionary that I do not need. Encoded data that I redirect to the endpoint: /turnalerts/api/v2/statuses?statuses=%5B%7B%27conversation%27%3A+%7B%27expiration_timestamp%27%3A+%271735510680%27%2C+%27id%27%3A+%2757f7d7d4d255f4c7987ac3557bf536e3%27%2C+%27origin%27%3A+%7B%27type%27%3A+%27service%27%7D%7D%2C+%27id%27%3A+%27wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA%3D%27%2C+%27pricing%27%3A+%7B%27billable%27%3A+True%2C+%27category%27%3A+%27service%27%2C+%27pricing_model%27%3A+%27CBP%27%7D%2C+%27recipient_id%27%3A+%272349039756628%27%2C+%27status%27%3A+%27sent%27%2C+%27timestamp%27%3A+%271735424268%27%7D%5D The request: <rest_framework.request.Request: GET '/turnalerts/api/v2/statuses?statuses=%5B%7B%27conversation%27%3A+%7B%27expiration_timestamp%27%3A+%271735510680%27%2C+%27id%27%3A+%2757f7d7d4d255f4c7987ac3557bf536e3%27%2C+%27origin%27%3A+%7B%27type%27%3A+%27service%27%7D%7D%2C+%27id%27%3A+%27wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA%3D%27%2C+%27pricing%27%3A+%7B%27billable%27%3A+True%2C+%27category%27%3A+%27service%27%2C+%27pricing_model%27%3A+%27CBP%27%7D%2C+%27recipient_id%27%3A+%272349039756628%27%2C+%27status%27%3A+%27sent%27%2C+%27timestamp%27%3A+%271735424268%27%7D%5D'> Data after request.GET: {'statuses': "[{'conversation': {'expiration_timestamp': '1735510680', 'id': '57f7d7d4d255f4c7987ac3557bf536e3', 'origin': {'type': 'service'}}, 'id': 'wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA=', 'pricing': {'billable': True, 'category': 'service', 'pricing_model': 'CBP'}, 'recipient_id': '2349039756628', 'status': 'sent', 'timestamp': '1735424268'}]"} The issue here is the double quote in the list as in "[{'conversation'... Expected result is: {'statuses': [{'conversation': {'expiration_timestamp': '1735510680', 'id': '57f7d7d4d255f4c7987ac3557bf536e3', 'origin': {'type': 'service'}}, 'id': 'wamid.HBgNMjM0OTAzOTc1NjYyOBUCABEYEjdCMTJFNUZDNzNFQjkxQ0IyRQA=', 'pricing': {'billable': True, 'category': 'service', 'pricing_model': 'CBP'}, 'recipient_id': '2349039756628', 'status': 'sent', 'timestamp': '1735424268'}]} Here's my view: class StatusesPayloadLayerView(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): payload = request.GET data = payload.dict() From the url encoding reference here, the encoded data looks fine as it doesn't appear to have a double quote before the list which would be "%22" notation so I can't quite understand where the double quote is coming from. -
How to store Django media folder in different EC2 instance
I have to host Django project on multiple server for load balancing. I have 4 EC2 server. I have used first for Nginx setup, 2nd and 3rd for Django application host and host 4th server to store all media folder. Now my problem is how can i save all media from server 2 & 3 to server 4? i tried some tutorial from google and couldn't get success. NOTE: i cant use s3 bucket to store media. -
handle situation where Django UpdateView does not have any data to update
I have created a forms wizard where a user will be able to create and update data for the models after which I will calculate the result by gathering all the data from all the forms and present them with an output. My user has the freedom to pick up where they left off and continue filling in data when they revisit. Each CreateView is linked to the next CreateView using the success_urls. So each UpdateView goes to the next UpdateView in the series of Views using the success_urls. So when a user updates data for a form and click next, they might arrive at a form which does not have any data to update because they have not filled in that data in thier previous visit. So get_object() returns an error as there is no data in the database for that form of that project. How to handle this situation ? class UserUseUpdateView(UpdateView): model = UserUse form_class = UserUseForm template_name = 'user_use.html' success_url = reverse_lazy('controller', kwargs={'step': 10, 'action': 'update'}) def get_object(self, queryset=None): try: project_instance = get_project(self.request) return UserUse.objects.get(project=project_instance) except Project.DoesNotExist: return redirect('step-9-create') # raise Http404(f'Project not found.') except UserUse.DoesNotExist: raise Http404(f'UserUse for project not found.') def form_valid(self, form): try: … -
Error when passing argument to custom tag in Django
Getting following error when using a custom tag that needs an argument. I am on Django version 4.2, does this still need a separate assignment to variable instead of using in if ? TemplateSyntaxError at /view/users/ "Unused 'PERM_CREATE_USER' at end of if expression" Inside view {% load my_tags %} {% if has_permission 'PERM_CREATE_USER' %} <a>Create User</a> {% endif %} #my_tags.py file @register.simple_tag(takes_context=True) def has_permission(context, perm): return True -
deploying django in vercel function timeout
i have a function called FetchAjaxs, which works fine in my local machine but not when i deploy view.py FetchAjaxs: #makes a api call to a different url which then returns a json to display in webpage i am calling that function from a ajaxs in my html index.html $.ajax({ url: "{% url 'FetchAjaxs' %}", // Django URL for the view type: "POST", data: $(this).serialize(), // Serialize form data headers: { "X-CSRFToken": "{{ csrf_token }}" // Add CSRF token for security }, dataType: 'json', my url.py looks like this path('fetch-ajax/', FetchAjaxs, name='FetchAjaxs'), and my vercel.json looks like this { "builds": [{ "src": "AppName/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9", "maxDuration": 300} } ], "routes": [ { "src": "/(.*)", "dest": "AppName/wsgi.py" } ] } when i run this in my local machine it works but when i run it in vercel it doesnt i figured it has to do with time out this is the error i get in my xhr {"error": {"code": "504", "message": "An error occurred with your deployment"}} i have increased the timeout in the settings in vercel however i still get the same error, any help would be appreciated , also please note i am … -
How "unpythonic" is it for an exception to be the expected outcome?
In Django I am validating a request which submits something that a user is only supposed to submit once, and in the "correct behavour sequence" an Exception is raised: try: my_row = models.MyModel.objects.get(id=instance_id, user=request.logged_in_user) return HttpResponseBadRequest("Already submitted") except models.MyModel.DoesNotExist: pass // continue Scale of 1-10, how much of a crime is this? -
Unclear error in Django rest framework swagger - guid instead of uuid
I have a Django rest framework project that is documented using drf-spectacular. In one of the endpoints I use rest_framework.serializer.UUIDField inside a serializer which inherit from rest_framework.serializer.serializer. But once I assign a wrong value in the swagger page the error is "Value must be a Guid". Why Guid and not UUID? Can I change it somehow? I don't understand from where it is coming from, did someone can assist with it? Search the "drf-spectacular" repo and didn't find it. -
Django Testing: Use main database as only one database available?
I am a university student, and I decided to use Django for my final year project. This means I am limited to using the University's MySQL database server. On the server, I am only allowed to have one database under my name and do not have permission to create any more of my own. I cannot use Django's test database functionality, as I only have one available and cannot create another. So, when I run ./manage.py test, I get the error... Found 3 test(s). Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'comp24394'@'%' to database 'test_comp24394'") How can I get around this? Is it possible for "test" tables to be created in the main database? Or, can I have the test database on another server from the main - if so, what would be the steps to implement this? Thank you for any help! -
Which method is best for designing custom error pages in Django?
For example, I've seen methods which design custom views with changes to URLconf, I've seen other methods that use handler404 = "mysite.views.my_custom_page_not_found_view" in URLconf with no changes to views. I've seen both of these methods explained in the docs. The easiest method I've seen is to simply create a templates/404.html without any other changes to the app. So which method is best for a production app? -
Select TruncYear start with specific year
I have Transactions stored in a Table, to select the last 3 years I wrote a simple Query in Django. I did this mid last year and it seemed to be fine. Now it would be nice if it would return me the year 2025 with 0, how could I achive that? Current Query: Transactions.objects .annotate(year=TruncYear('timestamp')) .values('year') .order_by('-year') .annotate(total=Sum('amount')) .values('year', 'total')[:3] This returns me the data for the years 2024,2023,2022 which is okay, but it would look more nice if it would return the data for 2025,2024,2023 Something like a change to get the current year and browse the table from there on. regardless of the table transactions having data for this year or not. -
How to Remove or Skip Object Serialization in Django Rest Framework Based on Conditions?
class CreateAttributeSerializer(BaseAttributeSerializer): class Meta(BaseAttributeSerializer.Meta): fields=['id', 'required'] + BaseAttributeSerializer.Meta.fields def to_representation(self, instance): attribute = super().to_representation(instance) current_display_order = int(instance.create_display_order) old_instance = self.context.get('old_instance', None) if old_instance: attributes = [] old_attribute = self.context['old_attribute'] if int(old_instance.create_display_order) == current_display_order: attributes = [old_attribute] attributes.append(attribute) else: attributes.append(attribute) return attributes self.context['old_instance'] = instance self.context['old_attribute'] = attribute I need to conditionally skip an object during serialization in Django Rest Framework. If certain conditions are met, the object should not be included in the response at all, neither as None nor an empty list. How can I get rid of null, [ null, [ { "id": 1, "required": false, "name": "price", "slug": "price" }, { "id": 6, "required": true, "name": "currency", "slug": "currency", "choices": [ "sum", "y.e" ] } ], [ { "id": 2, "required": false, "name": "Chevrolet model", "slug": "chevrolet_model", "choices": [ "Nexia", "Damas" ] } ], ] -
Adding custom actions button to wagtail snippets
I have been trying to look through the documentation on how to add custom action buttons for wagtail snippets. No luck so far. My wagtail version is 6.1.3 This is my snippet class. class CurrentDayForecastViewSet(SnippetViewSet): model = CurrentDayForecast menu_label = 'Current Day Forecast' list_display = ('forecast_title', 'forecast_date', 'town') search_fields = ('forecast_title', 'forecast_date', 'town') panels = [ FieldPanel('forecast_title'), MultiFieldPanel([ FieldPanel('forecast_date', classname='col6'), FieldPanel('town', classname='col6'), FieldPanel('min_temperature', classname='col6'), FieldPanel('max_temperature', classname='col6'), ], heading="Forecast Details", classname='col12'), MultiFieldPanel( [ FieldPanel('weather_condition_5AM', classname='col4'), FieldPanel('wind_direction_5AM', classname='col4'), FieldPanel('wind_speed_5AM', classname='col4'), ], heading='5AM', classname='collapsible col12' ), MultiFieldPanel( [ FieldPanel('weather_condition_12PM', classname='col4'), FieldPanel('wind_direction_12PM', classname='col4'), FieldPanel('wind_speed_12PM', classname='col4'), ], heading='12PM', classname='collapsible col12' ), MultiFieldPanel( [ FieldPanel('weather_condition_5PM', classname='col4'), FieldPanel('wind_direction_5PM', classname='col4'), FieldPanel('wind_speed_5PM', classname='col4'), ], heading='5PM', classname='collapsible col12' ), MultiFieldPanel( [ FieldPanel('weather_condition_9PM', classname='col4'), FieldPanel('wind_direction_9PM', classname='col4'), FieldPanel('wind_speed_9PM', classname='col4'), ], heading='9PM', classname='collapsible col12' ), ] By default the actions dropdown has "edit, copy, delete". I need to add a custom action button just for this snippet to run some custom logic. Appreciate if anyone can point me to right direction. -
When referencing imported Django model, I get 'local variable referenced before assignment' error
I am trying to import a model into my Django view and then query all objects, sort them, and iterate over them. I am not getting any error when importing the model, however, when trying to query the model with songs = song.objects.all()#.order_by('-release_date'), I am getting an error: UnboundLocalError at /hotline/dbm local variable 'song' referenced before assignment /home/path/to/site/views.py, line 82, in dbm songs = song.objects.all()#.order_by('-release_date') I do not understand what the problem is, as the variable song is clearly imported from my models.py file, and I am not getting any errors importing it - so why is Python not recognizing song as what I imported from my models.py file? My models.py file: class song(models.Model): name = models.TextField() file = models.FileField() release_date = models.DateTimeField(default=timezone.now) class Meta: verbose_name = 'Song' verbose_name_plural = f'{verbose_name}s' my views.py file: #list of modules removed to keep code clean from .models import * @csrf_exempt def dbm(request: HttpRequest) -> HttpResponse: songs = song.objects.all()#.order_by('-release_date') response = request.POST.get('Digits') if response == None: vr = VoiceResponse() vr.say("Please choose a song, and then press pound") vr.pause(length=1) with vr.gather(finish_on_key='#', timeout=6, numDigits="1") as gather: for song, num in songs: gather.pause(length=1) gather.say(f"For {song.name}, please press {num}") vr.redirect(reverse('dbm')) return HttpResponse(str(vr), content_type='text/xml') elif response != None: vr …