Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send lockout response of django-axes in the login api response
The django (django-rest-framework) app is using Simple JWT for the authentication and now I am trying to integrate the django-axes in the framework. I am able to lockout the user in 5 failed login attempt and its working as expected. Everything is working fine but When the user got locked out I am not able to send the response to the user notifying him that he is locked out. Problem Statement : When user login, he recieves No active account found with the given credentials in failed attempt. But once he reaches the lockout limit he receives Account locked for 1 hours: too many login attempts. Simple-JWT Configuration: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): print("Yes.........") data = super().validate(attrs) data['username'] = self.user.username data['id'] = self.user.id data['first_name'] = self.user.first_name data['last_name'] = self.user.last_name data['phone'] = self.user.phone data['email'] = self.user.email test = update_last_login(None, self.user) return data MyTokenObtainPairView class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer def send_response(self): return Response(self.serializer_class.data, status=status.HTTP_200_OK) I guess we need to override this validate function. But failed to do so. I was also trying to use: from axes.signals import user_locked_out class TokenObtainSerializer(serializers.Serializer): username_field = User.USERNAME_FIELD default_error_messages = { 'no_active_account': _('No active account found with the given credentials') } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) … -
How to install requirements.txt in django
I want to install all the dependencies in Django using requirements.txt.but I am getting an error ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' -
Django template: resolve nested variable [duplicate]
In the context I pass to the template, there are variables var_1, var_2, var_3, etc. I want to show the value of all those variables using a for loop. To do that, I write this code: {% with "1 2 3" as lst %} {% for x in lst.split %} <p>{{"var_{{ forloop.counter }}" }}</p> {% endfor %} {% endwith %} With this, I hope for each iteration, it first resolves the value of forloop.counter (e.g. 1), then resolves the value of the variable var_{{ forloop.counter }} (e.g. var_1) and shows this value. However, I got the error below: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '"var_{{ forloop.counter' from '"var_{{ forloop.counter' Is there any way I can get my desired result? -
Not able to run Django project on local machine
I am new to Django and I want to run a project in my local machine but it gives errors. Let me describe it: manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from django.http import Http404, HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.template import loader from django.urls import reverse import traceback def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lmui.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc try: execute_from_command_line(sys.argv) except Exception as e: print(str(e)) except: print("Oops!", sys.exc_info()[0], "occurred.") message = traceback.format_exc() print(message) if __name__ == "__main__": main() I run the the project as below on git bash: >> python manage.py migrate Segmentation fault >> python manage.py runserver 127.0.0.1:8000 Watching for file changes with StatReloader Performing system checks... Oops! <class 'SystemExit'> occurred. and traceback error is: File "C:\Users\rakesh.client\OneDrive - client\Documents\Rakesh\client\projects\codes\myproject\lmui-django\manage.py", line 25, in main execute_from_command_line(sys.argv) File "C:\Users\rakesh.client\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\rakesh.client\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rakesh.client\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rakesh.client\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, … -
How to pass form data to external API using POST request in django view function?
How to pass form data to external API using POST request in Django view function? My API does not get my form data. @csrf_protect def home_page(request): context = {} if request.method =='POST': form = UserForm(request.POST) if form.is_valid(): # form.save() resp = requests.post('http://127.0.0.1:8000/user_api/save_user/',params=request.POST).json() print(resp,' - type = ',type(resp)) context = {'success_message':'User registered successfully..!'} else: context = {'error_message':'Invalid Form Inputs'} form = UserForm() context.update({'form':form}) return render(request,'home/index.html',context) -
Django SAML Auth giving error as Sorry, you are not allowed to access this app
I am trying to Integrate SSO authentication using grafana-django-saml2-auth My SAML_AUTH files looks like below SAML2_AUTH = { 'METADATA_LOCAL_FILE_PATH': os.path.join(BASE_DIR,'ssometadata.xml'), 'DEBUG': False, # Send debug information to a log file # Optional settings below 'DEFAULT_NEXT_URL': 'XXX/SearchScreen/', # Custom target redirect URL after the user get logged in. Default to /admin if not set. This setting will be overwritten if you have parameter ?next= specificed in the login URL. 'CREATE_USER': True, # Create a new Django user when a new user logs in. Defaults to True. 'NEW_USER_PROFILE': { 'USER_GROUPS': ["user"], # The default group name when a new user logs in 'ACTIVE_STATUS': True, # The default active status for new users 'STAFF_STATUS': False, # The staff status for new users 'SUPERUSER_STATUS': False, # The superuser status for new users }, 'ASSERTION_URL': 'http://127.0.0.1:8000/', # Custom URL to validate incoming SAML requests against 'ENTITY_ID': 'http://127.0.0.1:8000/saml2_auth/acs/', # Populates the Issuer element in authn request 'USE_JWT': False, # Set this to True if you are running a Single Page Application (SPA) with Django Rest Framework (DRF), and are using JWT authentication to authorize client users } when I access the application getting below error . Sorry, you are not allowed to access this app To … -
Not able to insert or update data with Django ORM into Sql Server database when when trigger is active on database table,
enter code hereHello everyone I am new to Django and SQL Server and I am stuck on one Issue that can any one please help me Not able to insert or update data with Django ORM into SQL Server database when a trigger is active on a database table, but I can be insert or update data with a custom query like from django.db import connection def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("Insert Into table(col1,col2) values ('abc','xyz')") I want to achieve the same thing with Django Orm but when I try I get this error enter image description here how can I overcome this -
Use two ManyToMany fields to same models in migratiion
My model have two ManyToMany fields to one model. class Item(models.Model): additional_subcategories = models.ManyToManyField(SubCategory, related_name="additional_subcategories", blank=True) subcategories = models.ManyToManyField(SubCategory, related_name="subcategories", blank=True) But when I call this fields in migration, they return same queries. def forwards_func(apps, schema_editor): Item = apps.get_model("api", "Item") db_alias = schema_editor.connection.alias for item in Item.objects.using(db_alias).all(): print(item.additional_subcategories.all().query) print(item.subcategories.all().query) class Migration(migrations.Migration): dependencies = [ ('api', '0141_create_item_subcategories'), ] operations = [ migrations.RunPython(forwards_func) ] Printed: SELECT * FROM `api_subcategory` INNER JOIN `api_item_subcategories` ON (`api_subcategory`.`id` = `api_item_subcategories`.`subcategory_id`) WHERE `api_item_subcategories`.`item_id` = 1 SELECT * FROM `api_subcategory` INNER JOIN `api_item_subcategories` ON (`api_subcategory`.`id` = `api_item_subcategories`.`subcategory_id`) WHERE `api_item_subcategories`.`item_id` = 1 What I make wrong ? -
AttributeError: module 'rest_framework.serializers' has no attribute 'SmallIntegerField'
I'm getting an attribute error while using 'SmallIntegerField'. Doesn't Serializer support 'SmallIntegerField'? serializers.py from rest_framework import serializers class StudentSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField(max_length=150) email = serializers.EmailField(max_length=150) batch = serializers.SmallIntegerField() -
Webhook get blocked somehow and not trigger Django view function
I have a website set up using Django and digital ocean. I am trying to add a 3rd party webhook to my site url to trigger some code, however, the view function connected to my site url never gets called (I put debug code at first, and it never got called). I try to relink the webhook to the webhook.site, and it works. I have checked the webhook endpoint URL, no problem at all. If I type the webhook endpoint URL on the browser, my debug code will get triggered. It seems like, for some reason, when the webhook tries to call my code, this request gets blocked somehow and never reaches my code. I tried to put a @csrf_exempt to my view function, but it still does not seem to be called. Any idea? -
Cant get Information out of request data (Django/Postman)
Im trying to build an api with Django. I think i build it correctly but from, for example Post-request data, i get as the field values "none" Maybe you can help me to solve this problem :) Heres the api: def apiRequests(request): if request.method == "POST": print(request.POST.get("name")) print(request.POST.get("publisher")) print(request.POST.get("price")) #Game.objects.create(name= request.POST.get('name'),publisher = request.POST.get("publisher"),price = request.POST.get("price")) elif request.method == "GET": response = Game.objects.filter(name = request.GET.get("name")) return render(request,"apirequests.html") As you may see i'm printing out the data i receive. This looks like this: [26/Aug/2022 07:11:41] "GET /api/ HTTP/1.1" 200 263 None None None Here's the model class: class Game(models.Model): name = models.CharField(max_length=200) publisher = models.CharField(max_length=200) price = models.BigIntegerField() def __str__(self): return str(self.id) + " " + self.name And here is the data I'm sending as a Post-request from Postman to the api: { "name": "FarCry", "publisher": "EA", "price": "35.66" } I think i should say that i got Problems with the CsrfViewMiddleware-Token so i commented it out in the settings.py, maybe there is the problem. Thanks for helping -
Django Models - Django admin is throwing a DataError for "setting" a string to an integer within a Foreign Key
I've setup some models for Stripe payments, one for Product and the other for Price. You can see I've set the API value from Stripe as the Primary Key. These are their fields: class Product(models.Model): stripe_product_id = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Price(models.Model): stripe_price_id = models.CharField(max_length=100, primary_key=True) product = models.ForeignKey( Product, on_delete=models.CASCADE, to_field="stripe_product_id") price = models.IntegerField(default=0) Django admin let me create Product fine using the string api key, then when I went to create a Price object using the Price API value from Stripe, and having the foreign key set to my Product. I was given the following error (my api values are redacted): DataError: invalid input syntax for integer: "prod_xyz" LINE 1: UPDATE "payments_price" SET "product_id" = 'prod_xyz... I tried using the to_field parameter in Foreign Key but that didn't seem to fix it. Does anyone know the method to fix it? Or should I just go back to using the default primary key with the product/price id as Unique? Below is what I'm attempting to do in Admin. -
Which frontend(React.js/React Native) and backend(Flask/Django) frameworks should I choose?
I'd like to develop a portfolio manager web app. In this app users will be able to manipulate portfolios by adding/editing/removing transactions and see their portfolios statistics in real time(change of the stock prices, total return). I have a list of requirements and examples of screens for the project below. It's worth to mention that I don't have experience in web-development and only know the basics of python and js. Frontend: Support both Desktop and Mobile web app versions Interactivity (Adding/Editing/Removing portfolios/transactions) Content expansion (More transactions/holdings/portfolios are added) Frequent data updates (Prices of holdings/total returns) Technologies: React.js/View.js/React native Backend: Localization (For now only English) Authorization (Users should be able to sign up/login in the system) Real time data streaming (Get financial data from yahoo or other financial sources) Technologies: Django/Flask Portfolio screen Portfolios screen AddTrade view Settings screen -
Django pass variable from button to view
This is my template file which contains a menu that generates dynamically: {% block idfs %} {% for each in list %} <li> <a href="{{each}}">{{ each }}</a> <button type="submit" value={{each}} onclick="location.href='{{each}}'" name='{{each}}'>Go</button> </li> {% endfor %} {% endblock %} I have the button there, and I need the name for each button in my view. So when user clicks on any button, I can process the output in my view. I have tried this in my view: def example(request): item = request.POST.get('name') print(item) But it doesn't work. It always returns None. Shouldn't it work? Since I am using 'name' to pass the data from template? How can I pass the generated names in my buttons to my view? -
Django new project Run Add Grop page not save selected permissions
Just create a new project, Run Add Grop page, add a new group, and select some permissions. Press the save button. A result is a new group added with no permissions. Why? I modify a little code as below: class GroupAdmin(admin.ModelAdmin): search_fields = ("name",) ordering = ("name",) # filter_horizontal = ("permissions",) def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == "permissions": qs = kwargs.get("queryset", db_field.remote_field.model.objects) # Avoid a major performance hit resolving permission names which # triggers a content_type load: kwargs["queryset"] = qs.select_related("content_type") return super().formfield_for_manytomany(db_field, request=request, **kwargs) mark out this line : filter_horizontal = ("permissions",) , for not showing the selected items listbox. run the same page: Press the save button, then got the desired result. Although the answer is right, without filter_horizontal = ("permissions",) Listbox is not suitable for users. I think the add group page is the basic function page, and should not have bugs. Why did no one fund or reply to this problem? -
Django Rest framework API - Token Authorization
http http://127.0.0.1:8000/studentapi/ "Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYxNDgzOTczLCJpYXQiOjE2NjE0NDczNzIsImp0aSI6IjU5ZjQ3MzcxODdiODRkYWI5Mjg4NzM2YzZhZjBkN2YwIiwidXNlcl9pZCI6NX0.x0naaeapuTTFUIThownVDyuDs53kkZjkljpb6sieLuE" HTTP/1.1 403 Forbidden Allow: GET, POST, HEAD, OPTIONS Content-Length: 58 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Fri, 26 Aug 2022 03:18:01 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.10.5 Vary: Accept X-Content-Type-Options: nosniff X-Frame-Options: DENY { "detail": "Authentication credentials were not provided." } -
Methodology to fix 'QuerySet' object has no attribute 'Breakdown' for a Django Project
I have a workout progress project that I am working on and I am trying to find the breakdown of each exercise which is reps and order. Here is the model for clarification: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) date = models.DateField(blank=True, null=True) slug = models.SlugField(unique=True,blank=True, null=True) def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("my_gym:workout", kwargs={'workout_id': self.id}) class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) def __str__(self): return self.name class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='breakdown',blank=True, null=True) weight = models.FloatField(validators=[MinValueValidator(0)],blank=True, null=True) repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) def __str__(self): return self.exercise.name + ' set #' + str(self.order) I am trying to show a table after going to one of the excercises list to review the reps and order Here is the url: urlpatterns = [ path('', views.home, name='home'), path('workout/<int:workout_id>/', views.workout_details, name='workout'), ] Here is the views: def workout_details(request,workout_id): template_name = 'my_gym/start_workout.html' # workouts = Workout.objects.filter(workout_id=workout_id) # excercises = Exercise.objects.get(pk=workout_id) excercises = Exercise.objects.filter(workout_id=workout_id) breakdowns=excercises.Breakdown.repetitions.all() context = { 'excercises': excercises, 'breakdowns':breakdowns } return render(request, template_name, context) In the template: {% for breakdowns in breakdown %} {{excercises.breakdown.order}} {{set.repetitions}} {% endfor %} My question: I am getting 'QuerySet' object has no attribute 'Breakdown' … -
Please is there a way I can solve this error I think everything is well with this
I have suffered from this error, please help me. this is my views.py and models.py file please I need to create add to cart function, and this error one happens when I click the add to cart button using get_or_create function. here is the code: def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("core:product", slug=slug) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) -
Postgre query with JSONField on array
I am new to Postgres, and try to build a SQL query that can retrieve a Key/Value dictionary pair in an array [] from table table_b and use it in the WHERE clause on finding matching tag_name and tag_value returning the object_uuid The original tags on table_b were stored as JSONField() in Django -> Postgres and not sure how that would work in array on extracting each one out. Question: How do we build a SQL query can traverse each name and value in table_b.tags and then use it to match it on table_a? table_a tag_name tag_value object_uuid foobar coffee aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee hello world 3dd98cb6-978c-44b0-92fd-403032a7cb1f key_one 81bba637-4156-42b2-a2c0-ae5dd23ed695 table_b id object_uuid tags 3 00000000-1111-2222-3333-444444444444 4 99999999-8888-7777-6666-555555555555 271 [{"name": "foobar", "value": "coffee"}, {"name": "hello", "value": "world"}] I think I come with this SELECT id, object_uuid, name, value FROM table_b b, jsonb_to_recordset(b.tags) AS (name TEXT, value TEXT) id object_uuid name value 271 foobar coffee 271 hello world -
Django unit testing FileField and ImageField using ContentFile
I am using Django 3.2 I have a model like this: Foo class class Foo(models.Model): name = models.CharField(max_length=124) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() bio = models.TextField() attachment = models.FileField() photo = models.ImageField() recorded_date = models.DateField() time_of_day = models.TimeField() timestamp = models.DateTimeField() duration = models.DurationField() website = models.URLField() pseudo_array = models.CharField(max_length=256) pseudo_tags = models.CharField(max_length=128) Snippet of Unit test import glob import os import json from datetime import datetime, timedelta from django.utils.timezone import make_aware from model_bakery import baker from django.test import TestCase from django.core.exceptions import ValidationError from django.core.files.base import ContentFile image_mock =ContentFile(b"R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", name='photo.png') file_mock = ContentFile("Some random text", name='archive.txt') class TestModels(TestCase): def setUp(self): current_timestamp = datetime.now(timezone.utc) self.foo = Foo.objects.create( name='Accepted Object',bio='For accepted testing', owner=self.pattysmith, description='Object for accepted testing', attachment = file_mock, photo = image_mock, recorded_date = datetime.strptime('20200101','%Y%m%d'), time_of_day = datetime.strptime('10:00','%H:%M'), timestamp = make_aware(timezone.now().strptime('20200101 10:00','%Y%m%d %H:%M')), duration = timedelta(days=20, hours=10), website = 'https://www.accepted.com', moderation_status=1, pseudo_tags='approved,nice, accepted' ) def tearDown(self): Foo.objects.all().delete() User.objects.all().delete() for f in glob.glob("*.png"): os.remove(f) for f in glob.glob("*.txt"): os.remove(f) def test_change_moderated_char_field(self): self.foo.name='My new name' self.foo.save(update_fields=['name']) # test for number of changed fields ... When I run the test test_change_moderated_char_field I see that the file and image field names have changed - looks like Django is auto-generating the file names. … -
'CustomUser' object is not iterable
I am trying to establish a user type base register/login system for my e-commerce app. I have used the following codes in my views file. here's the code snippet from my models.py. Just given the customer class as i am focusing on that first. class CustomUser(AbstractUser): user_type_choices=((1,"Merchant"),(2,"Customer")) user_type=models.CharField(max_length=255,choices=user_type_choices,default=1) class Meta(AbstractUser.Meta): swappable = "AUTH_USER_MODEL" class CustomerUser(models.Model): auth_user_id=models.OneToOneField(CustomUser,on_delete=models.CASCADE) user=models.OneToOneField(CustomUser,on_delete=models.CASCADE, related_name='customer', null= True,blank=True) name= models.CharField(max_length = 255, null= True) firstname = models.CharField(max_length = 255, null=True) lastname = models.CharField(max_length = 255, null=True) email = models.CharField(max_length = 255, null=True) profile_pic=models.FileField(default="") created_at=models.DateTimeField(auto_now_add=True) So, as far I can say that I am logged in but can't access my home page as I got the following error. TypeError at / 'CustomUser' object is not iterable ....... Local vars F:\rewards\projectreward\rewardapp\userviews.py, line 152, in store data = cartData(request) … Local vars F:\rewards\projectreward\rewardapp\utils.py, line 43, in cartData order, created = Order.objects.get_or_create(request.user, complete=False) … I'm not sure why my cartData function in utlis.py is affected by this. It worked perfect when I didn't used user type base login. However, here's the cartData from utils.py. def cartData(request): if request.user.is_authenticated: order, created = Order.objects.get_or_create(request.user, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] … -
How to serve staticfiles from docker django app to hosted nginx
My goal is to serve the staticfiles to nginx on ubuntu from a docker django app container without using docker nginx I setup the reverse proxy to django all works fine in dev mode but when i turn Debug to False nginx doesn't recognize the staticfiles path here's a screenshot Here's my dockerfile for django app FROM python:3.9 RUN mkdir /app WORKDIR /app COPY . /app RUN pip install pipenv RUN pipenv install --system --deploy --ignore-pipfile EXPOSE 8000 ENTRYPOINT ["python", "manage.py"] CMD ["runserver", "0.0.0.0:8000"] And here's my nginx config upstream django { server 127.0.0.1:8001; } server { server_name django.com; listen 80; listen 8000; client_max_body_size 100M; location / { proxy_pass http://django; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header X-Forward-Proto http; proxy_set_header X-Nginx-Proxy true; proxy_redirect off; proxy_read_timeout 1000; proxy_connect_timeout 1000; proxy_send_timeout 1000; } } -
How to get value of django form within that same form before submission?
I'm creating a django form with 3 choice fields. I want the 3rd choice field (object field) to populate based on the first 2 choice fields. Boiling it down, I guess my question would be how do I get the values of the first 2 choice fields so I can use those values within the same form.py before submitting? Here is what my forms.py looks like, which is currently giving me the error "maximum recursion depth exceeded": class MyForm(forms.Form): season = forms.ChoiceField( widget=forms.Select(attrs={"class": "form-control test"}), label="season", choices=SEASON_CHOICES, ) episode = forms.ChoiceField( widget=forms.Select(attrs={"class": "form-control"}), label="episode" ) object = forms.ChoiceField( widget=forms.Select(attrs={"class": "form-control"}), label="object", ) def __init__(self, *args, **kwargs): super(forms.Form, self).__init__(*args, **kwargs) form = MyForm() season = form.cleaned_data.get["season"] episode = form.cleaned_data.get["episode"] try: snow = Snowflake() snow_data = snow.query( f"""select * from modern_family""" ) object_data = snow.query( f"""select * from {season}.{episode}""" ) snow.close() self.fields["episode"].choices = [(sd[0], sd[0]) for sd in snow_data] self.fields["object"].choices = [(sd[0], sd[0]) for sd in object_data] except Exception as e: print(e) -
How to resend the same request again in Django api
I have a BuyproducTviewset using createModelMixin that create an instance when post request is made however I want to repeat the same create request again after 5 seconds from the api depending on a condition if the price is greater than a specific range. class BuyProductViewset(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer_class = UserproductSerializer queryset = Userproducts.objects.all() def data_serialize(self, user_id, product_ID): data = {"user": user_id, "product": product_ID} serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return serializer, headers def create(self, request, *args, **kwargs): user_id = request.data["user_id"] product_id = request.data["product_id"] total = request.data["total"] upper_bound = request.data["upper_bound"] lower_bound = request.data["lower_bound"] product = ( product.objects.filter(product_id=product_id) .order_by("timestamp") .reverse()[:1] .values("id", "name", "price", "availability") .get() ) product_ID = product["id"] product_price = product["price"] product_availability = product["availability"] product_name = product["name"] if product_price >= int(lower_bound) and product_price <= int(upper_bound): serializer, headers = self.data_serialize(user_id, product_ID) product.objects.create( product_id=product_ID, name=product_name, price=product_price, availability=product_availability - int(total), ) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) else: time.sleep(5) # RESEND THE SAME REQUEST WITH THE SAME DATA return a response -
How to create a Domain Name for a Django App in a LAN
I recently built a Django app that I am running on a Linux machine with Gunicorn and NGINX. The app is being run inside my company's network which is predominantly a windows environment. Currently, I am able to access the web app via the server's IP address. I know if it was a windows machine I could use the DNS to have it called by a DN. How accomplish this given that it's a Linux machine? For example, I would like to have the company users call the web app from a browser using http://analytics instead of its IP address. Would make the app much more user-friendly instead of always typing in the IP and just for best practice it's probably not secure to be showing the end user the IP anyways.