Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cant add Products to admin
Im having some errors updating products in my Django adminthe error that shows up whenever I try to add a new product it keeps telling me to return to my django root file and make some changes{Error that comes up} I was expecting a successful operation that says product added successfully OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Python\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\Admin\Desktop\Afresh', 'C:\Python\Python37\python37.zip', 'C:\Python\Python37\DLLs', 'C:\Python\Python37\lib', 'C:\Python\Python37', 'C:\Python\Python37\lib\site-packages'] Server time: Thu, 25 Jan 2024 11:31:08 +0000 -
Django-Python easy way to convert PPTX to PDF?
I have tried several libraries for convert a PPTX file to PDF and all of them gives me error. For example I am trying to use an API of SDK python of GroupDocs, this is my method: def generate_and_save_pptx(self): pptx_template_path = ‘panel/templates/originals/Prueba.pptx pdf_filename = f’{self.client.name} - {self.type_submission.name}_tutorial.pdf’ pdf_path = submission_directory_path(self,pdf_filename) api_instance = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key) convert_request = groupdocs_conversion_cloud.ConvertDocumentDirectRequest( "pdf", pptx_template_path, # Reemplaza con la ruta correcta a tu archivo None, None, None ) try: response = api_instance.convert_document_direct(convert_request) with open(pdf_path, "wb") as pdf_file: pdf_file.write(response) Debugging it looks like I cant even enter into response. On the other hand it says folder doesnt exist but it exists, I save other files there without problem. Any other libraries I have tried always have similar problemas, not enter into the response, save data corrupted, etc. I just would like to find and easy and free way to convert pptx files to pdf -
logout in drf api browsable it shows HTTP ERROR 405
I perform logout and login operations in Djnago Rest Framework. I logout using drf api browsable it shows HTTP ERROR 405 my version is Django==5.0.1 when i decrease version Django==3.2.10 it works perfect Is there any solution in Django==5.0.1 to resolve this issue ? -
Fire & Forget Asyncio
I've been scouring the web to an answer to this question but I can't seem to find an actual answer or maybe i'm just missing it. I'm trying to fire off a post request to start another microservice and I don't care what response comes back as that goes to a different part of my architecture Once the request is sent I want to essentially continue the code a return this random json to where the function is called. For some reason whenever I use asyncio.run() it starts the send_requests() function but waits for it to respond before continuing. Which is how async works i this case I think. But i'm unsure how to continue and exit the function before waiting for a response Here's the pseudo code Class DummyClass: def do_something(): "doing something...." asyncio.run(send_requests) return "random string" async def send_request(): try: requests.post("send to url") except: raise Issue I can use a decorator def fire_and_forget(f): @wraps(f) def wrapped(*args, **kwargs): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if callable(f): return loop.run_in_executor(None, f, *args, **kwargs) else: raise TypeError("Task must be a callable") return wrapped which works fine but just wondering if we can do it without the decorator! I think I might be slightly misunderstanding … -
Django use F() to the jsonField and there is json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
this is the code class Helo(models.Model): id = models.IntegerField(primary_key=True) aa = models.JSONField(null=True) bb = models.JSONField(null=True) one example data is this: id aa bb 1 {"p1":11 "p2": 22} {"p1": 33, "p2": 44} and i run this code test=Helo.filter(aa__p1__gte = F('bb__p1')) test.count() get these error message json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) i also tried the test=Helo.filter(aa__p1__gte = F('bb')) test.count() and there is no error, i wonder why i cant use the F('bb__p1') -
Django DATE and DATETIME settings have no effect since USE_L10N was deprecated
Since 5.0 USE_L10N settings was DEPRECATED and is always True. Now settings like DATE_FORMAT, DATETIME_FORMAT, DATE_FORMAT_INPUTS etc.. don't work because as per documentation: Note that the locale-dictated format has higher precedence and will be applied instead. But now locale-dictated formats are always enabled. A fix I've found is to copy the formats.py file you want to in your app's directory. The path should look like <your_project>/<your_app>/formats/ro/formats.py then in settings.py you can set: LANGUAGE_CODE = 'ro-RO' FORMAT_MODULE_PATH = ['yourapp.formats',] But why have those settings anymore? Is there any way in which you can still use those settings? -
How to add an accordion in djnago admin in the change_list.html template?
I want to change the default table in the django admin, which is displayed in the template change_list.html. While retaining all the functionality that django provides. The idea is to make the table in the form of an accordion, where there will be a button "Collapse" and "Expand". In the case of clicking the button "Expand" will expand the column with the associated record and all its data Can you tell me how to implement such functionality, I will be glad to receive any suggestions? In simpler words, how to add the action "view_data" and when you click "Open" button the accordion will open and show all the data related to the record table -
how to solve CORS error in react and django
i am trying to creat log in app using Django and react . my js : const client = axios.create({ baseURL: "http://127.0.0.1:8000"}); //my submitRegistration function function submitRegistration(e) { e.preventDefault(); client.post( //every time I got cors error here// "/api/register", { email: email, username: username, password: password } ).then(function(res) { client.post( "/api/login", { email: email, password: password } ).then(function(res) { setCurrentUser(true); }); });} django cors setup: CORS_ALLOWED_ORIGINS = [ 'http://localhost', 'http://127.0.0.1', 'http://0.0.0.0', ] CORS_ALLOW_CREDENTIALS = True I dont know why I got cors error here.any suggestion please! -
What is this little note below DateField that is displayed in Django Admin?
Hi I have defined a CD Model in my models.py file in my app and linked it to the admin page. However, I noticed this little note below the Date field. 'You are 8 hours ahead of server time'. What does it mean? I tried finding information about it but still couldn't get a good understanding of it. -
python dict weird assign of a key value (multiple keys are created)
I run the following code (django framework, but it doesn't seem relevant) def asignador(self) -> dict: try: a_asignar = deepcopy(list(self.materias)) dict_mezclado = deepcopy(Biotcher.mezclador(self.dict_de_asignaciones)) divisiones_mezcladas = deepcopy(Biotcher.mezclador(self.divisiones_habilitadas_por_materia)) shuffle(a_asignar) nueva_grilla = deepcopy(self.grillas) for materia_a_asignar in a_asignar: materia_a_asignar = a_asignar[0] division_asignada = divisiones_mezcladas[materia_a_asignar.materia.pk][-1] ##### horas_div = materia_a_asignar.materia.horas_por_semana for _ in range(horas_div): dia, hora = dict_mezclado[division_asignada][-1] print(nueva_grilla[division_asignada]) nueva_grilla[division_asignada][dia][hora]['mat'] = materia_a_asignar.materia.nombre print(nueva_grilla[division_asignada]) dict_mezclado[division_asignada].pop(-1) divisiones_mezcladas[materia_a_asignar.materia.pk].pop(-1) return nueva_grilla except Exception: print('EXCEPCION') print(nueva_grilla) The first print I obtain {1: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 2: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 3: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 4: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 5: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}} and in the second one {1: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 2: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 3: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}, 4: {1: {'mat': 'Pol y Ciud.'}, 2: {}, 3: {}, 4: {}, … -
I am tying to create .exe for my django I used python freeze_script.py build but I'm getting error
# freeze_script.py import os import sys from cx_Freeze import setup, Executable from django.core.management import call_command from django.core.wsgi import get_wsgi_application # Manually configure Django settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DVE.settings') # Replace 'your_project_name.settings' with your actual settings module application = get_wsgi_application() # Your Django project name (replace 'your_project_name' with your actual project name) project_name = 'DVE' base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable("manage.py", base=base) ] # Call the 'migrate' command before freezing call_command("migrate") # Freeze the application build_options = { 'packages': ['DVE','TOOL', 'django', 'gunicorn'], 'includes': ['django.template.backends', 'django.templatetags.i18n'], } setup( name="TOOL", version="1.0", description="TOOL", options={"build_exe": build_options}, executables=executables ) Traceback (most recent call last): "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\cx_Freeze\initscripts_start up_.py", line 124, in run File module_init.run(name + "main_") File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\cx_Freeze\initscripts\consol e.py", line 16, in run exec(code, module_main.dict_) File "manage.py", line 22, in <module> File "manage.py", line 18, in main File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\django\core\management\ init_.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\AAMOLGHA\AppData\Local\Packages\PythonSoftwa reFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-p ackages\Python310\site-packages\django\core\management\ init_.py", line 424, in execute sys.stdout.write(self.main_help_text() + "\n") AttributeError: "NoneType' object has no attribute 'write' this is the error your text -
How to save information in two different tables in Django?
I have a django application where I can open a form with fields (client and services) rendered (form) and save it in a single table. I decided to separate the customer data in another table, so as not to have the same customer saved more than once in the services table. It turns out that I don't know how to apply this reasoning in practice. Below is the view responsible for the n ew registration. @login_required def NovaOS(request): if request.method == 'POST': form = OrdemServicoForm(request.POST) if form.is_valid(): OS = form.save(commit=False) OS.user = request.user OS.save() return redirect('/os/list/') else: form = OrdemServicoForm() return render(request, 'serviceorders/addos.html', {'form': form}) I have already created the necessary information in forms.py and models.py. forms.py class ClienteForm(forms.ModelForm): class Meta: model = Clientes fields = '__all__' widgets = { #Dados do cliente 'STATUSCliente': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Status'}), 'cliente_razaosocial': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Razão Social', 'autofocus': True}), 'cliente_cpfcnpj': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CPF/CNPJ'}), 'cliente_rgie': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'RG/I.E.'}), 'cliente_email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'E-mail'}), 'cliente_telefone_fixo': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tel. fixo', 'data-mask':"(00)0000-0000"}), 'cliente_telefone_celular': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tel. celular', 'data-mask':"(00)00000-0000"}), 'cliente_endereco': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Endereço'}), 'cliente_endereco_num': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Número'}), 'cliente_endereco_CEP': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CEP'}), 'cliente_endereco_Bairro': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Bairro'}), 'cliente_endereco_Cidade': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Cidade'}), … -
What do I need to do to fix a 404 error in django
I'm new to studying Django and I'm doing a task and I have to display a message with the url "http://127.0.0.1:8000/blog/". But when I search with this url, the error "Page not found (404) is displayed Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order: admin/ The current path, blog/, didn’t match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.", Could anyone offer me help? A message chosen by the teacher would have to appear, but I only have the error as a response. -
django rest framework serializer.data throws error about attribute in manytomany relationship
I have the following models: class MenuItem(models.Model): class Category(models.TextChoices): PIZZA = "pizza" SIDE = "side" OTHER = "other" name = models.CharField(max_length=40) description = models.TextField(max_length=150) price = models.FloatField(default=0.0) category = models.CharField(max_length=50, choices=Category.choices, default=Category.OTHER) class Order(models.Model): class OrderStatus(models.TextChoices): NEW = "new" READY = "ready" DELIVERED = "delivered" customer = models.CharField(max_length=50) order_time = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(MenuItem, through='OrderItem') status = models.CharField(max_length=50, choices=OrderStatus.choices, default=OrderStatus.NEW) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() And the following serializers: class MenuItemSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=40) description = serializers.CharField(max_length=150) price = serializers.FloatField(default=0.0) category = serializers.CharField(max_length=50) def create(self, validated_data): return MenuItem.objects.create(**validated_data) class OrderItemSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) menu_item_id = serializers.PrimaryKeyRelatedField(queryset=MenuItem.objects.all(), source='menu_item', read_only=False) quantity = serializers.IntegerField(min_value=0) class OrderSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) customer = serializers.CharField(max_length=50) order_time = serializers.DateTimeField(read_only=True) items = OrderItemSerializer(many=True) def create(self, validated_data): order_items_data = validated_data.pop('items') order = Order.objects.create(**validated_data) for order_item_data in order_items_data: quantity = order_item_data.pop('quantity') menu_item = order_item_data.pop('menu_item') OrderItem.objects.create(order=order, quantity=quantity, menu_item=menu_item) return order And then in views: @csrf_exempt def order(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = OrderSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) print(serializer.errors) return JsonResponse(serializer.errors, status=400) An example request looks like: echo -n '{"customer": "John Doe", "items": [{"menu_item_id": 1, "quantity": 2}, {"menu_item_id": 2, "quantity": 1}]}' | http POST http://127.0.0.1:8000/order … -
How to quickly revert a Django migration?
I wrote a trivial new app in Django and after I ran ./manage.py migrate myapp, I realized I wanted to add some new fields. Since it's a new app, I want to update my original migration and not create a second migration, so I ran .manage.py migrate myapp zero to completely revert all migrations for the app. However, even though it took Django about 5 seconds to initial apply my single migration, after 30 minutes of processing, it still hasn't been able to revert the migration. I've killed all other connections to my local database, so I don't think it's waiting for anything. Yet top says Django's manage.py is hogging about 75% of my CPU. My app only has three simple models, with a FK relation between them in a Parent<-Child<-Grandchild relationship, and there are no records in any of the tables. I'm using a PostgreSQL backend. Why is Django so inefficient at removing a migration for tables with no records? -
UserAdmin save_model not triggering on password change
I want to end the users session when ever the password is changed through the admin site (see screenshot). I did a research and it suggests to override the save_model and write the custom logic to end the session @admin.register(User) class UserAdmin(UserAdmin): def save_model(self, request, obj, form, change): print("HERE") ... The problem is that for some reason save_model never triggers (tried debugging as well). Both User and UserAdmin are properly registered, otherwise I wouldn't even be able to access the Change Password page. Version: Django 4 -
TypeError: update() got an unexpected keyword argument 'slug' in flask
i have this flask code views.py @bp.route('/\<slug\>/update', methods=('GET', 'POST')) @login_required def update(\*args): slug = request.view_args\['slug'\] print(f"this is the slug: {slug}") if not g.user\['is_admin'\]: abort(404) db = get_db() post = db.execute("""--sql SELECT \* FROM posts WHERE slug = ?""", (slug,)).fetchone() tags = get_tags(post['id']) if request.method == 'POST': title = request.form['title'] new_slug = slugify(title) image = request.files['image'] body = request.form['body'] publish = request.form['publish'] tags = request.form['tags'] user_id = g.user['id'] # handle errors error_fields = form_errors('title', 'body', 'tags') errors = validate(error_fields, title, body, tags,) if title and body and tags: if image: filename = save_image(image) db.execute("""--sql UPDATE posts SET image = ? WHERE slug=?""", (filename, slug)) # Editd post query = """--sql UPDATE posts SET title = '%s', slug = '%s', body = '%s', publish = '%s' WHERE slug = '%s' """ % (title, new_slug, body, publish, slug) db.execute(query) db.commit() update_tags(tags.split(','), post['id']) flash('Post was Successfuly Updated', category='success') return redirect(url_for('blog.detail', slug=new_slug)) return render_template('blog/form.html', errors=errors, post=post, tags=tags, title='Edit Post') return render_template('blog/form.html', errors=None, post=post, tags=tags, title='Edit Post') what i am trying to archive is that i have this blog website and i want to be able to edit a blog post each time i call this function and this is my layout.html <!DOCTYPE html> <html lang="en"> … -
Django Rest Framework - unable to add 'url' to HyperlinkedModelSerializer fields
I have what feels likes a stupid simple question, but the docs don't seem to address my issue at all. I'm using django-rest-framework as a backend for a react app, so I want the model list view to also include the url to the details view, so my view set looks like this: from ..models import BoardModel from ..serializers import BoardSerializer from rest_framework import viewsets class BoardViewSet(viewsets.ModelViewSet): queryset = BoardModel.objects.all().order_by('file_name') serializer_class = BoardSerializer and the serializer looks like this: from .models import BoardModel from rest_framework import serializers class BoardSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BoardModel fields = ['url', 'slug', 'file', 'processed_file', 'file_name', 'keypoints'] extra_kwargs = { 'url': {'lookup_field': 'slug'}, } and for good measure, the model: from django.db import models from .validators import validate_img_ext, validate_keypoints_schema def validate_file(v): validate_img_ext(v, [ '.png', '.jpg', '.jpeg' ]) # Create your models here. class BoardModel(models.Model): file = models.FileField(validators=[validate_file]) file_name: 'models.CharField' = models.CharField(blank=True, max_length=75) processed_file = models.FileField(blank=True, validators=[validate_file]) keypoints: 'models.JSONField' = models.JSONField(null=True, blank=True, validators=[validate_keypoints_schema]) slug: 'models.SlugField' = models.SlugField(blank=True, unique=True) and URLs with router: from rest_framework import routers from .views import board app_name = 'boardcanvas' router = routers.DefaultRouter() router.register(r'boards', board.BoardViewSet) urlpatterns = router.urls I know the routes are loading correctly, because I can see the boardmodel-detail route listed … -
Django filter not using correct template
I am working on a Django web application. The app includes a filter that is calling the wrong template--even though 'template_name' is set in both the view and the filter. I don't understand why the template_name attribute is being ignored. Here's the code: in urls.py: path('curation/', views.SubjectsCurationView.as_view(), name='subjects_curation'), in views.py: class SubjectsCurationView(LoginRequiredMixin, FilterView): template_name = 'subjects_curation.html' filterset_class = filters.CurationFilter in filters.py: class CurationFilter(django_filters.FilterSet): template_name = 'subjects_curation.html' projects = django_filters.ModelMultipleChoiceFilter( queryset=Project.objects.all(), field_name='projects', widget=forms.CheckboxSelectMultiple() ) class Meta: model = models.Subject fields = [ 'projects', ] @property def qs(self): queryset = super().qs return queryset The template that does get called, subjects_filter.html, is different from the subjects_curation.html template that is specified here. I tried changing the order of the url entries in case lazy matching was part of the problem, but that made no difference. Joe White Dana-Farber CI -
What is the best way to implement Django-Oscar Shipping Methods as model instances?
I am struggling to understand some concepts that django-oscar implements, regarding shipping, and hope that someone on here can give me some clarity. I'm trying to understand why the shipping methods are hard-coded classes versus dynamic models, and if I create models for the shipping methods, will it break the get_available_shipping_methods() method? I have looked through the docs and there are examples explaining how to create new shipping methods by subclasses, but this is not what I am looking for. I am using django-oscar as the foundation for a marketplace, therefore there will be multiple sellers/shops. I want them to be able to define their own shipping methods, as well as use the "built-in" Shipping methods used to calculate multiple shipping carrier rates. -
Equivalent of laravel chunk and pluck code in Python django
Can somone help me to convert this ( PHP - Laravel ) code to ( Django - Python ) which migrate records from an existing table in chunks, also would appreciate the use of wherein to reduce the number of queries and to reduce RAM usage. $limit = 100; $query = (new Log) ->select(['id', 'created_at']) ->latest(); $query->chunk($limit, function ($chunk) { $ids = $chunk->pluck('id')->toArray(); $existing_ids = DB::table('logs_new_table') ->whereIn('log_id', $ids)->pluck('log_id'); // Remove the existing IDs from the array $non_existing_ids = collect($ids)->diff($existing_ids)->toArray(); // Gets the non-existing ids $logs = (new Log_event) ->findMany($non_existing_ids); foreach ($logs as $log) { try { Log::debug(__METHOD__ . " processing log id: {$log->log_id}"); } catch (\Exception $e) { Log::warning(__METHOD__ . " failed to migrate log: {$e->getMessage()}"); } } }); -
Django user object can't retrieved from database
views.py def profile(request,link): user = User.objects.get(username=link) print(user.email) return render(request,'profile.html',{'user':user}) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('login',views.loginUser,name='login'), path('signup',views.signup,name='signup'), path('profile@<str:link>',views.profile,name='profile'), path('courses',views.courses,name='courses'), ] When I trying to retrive user object it raising an error 'Dosen't exist' or 'user have no atribute username', and lot sof error. I also used filter as well but that gave a quaryset and I couldn't sent in html template as a object. -
i want to put the form boxes in-line instead of stacked
code and result. I would like to know how to display the date form in-line instead of stacked. thank you in advance! :) im using bootstrap and django so i tried solving the problem with bootstrap or even the django templating but couldnt get nowhere. -
How does CSRF Token work for a sign up request
I am just getting to learn Django, and CSRF Token seems to be an important aspect in terms of preventing cross-site request forgery. However, I am a little bit confused about its role in a sign up function. From my understanding, the CSRF Token is sent from the backend server to the frontend server after the user sends an initial request from the frontend server. Then in proceeding request to the backend server, the backend server checks if there is a valid CSRF token from the frontend and send a response accordingly. However, if a user is signing up or logging in for the first time, without any cookies on the browser whatsoever, is it possible (or necessary) to check for CSRF token in a Django signup/signin view function? If it is necessary, what is the mechanism, assuming separate backend and frontend server, behind validating CSRF token in such scenario? -
django htmx cannot get element name for the second time
In my views.py, I have 2 functions using "customer = request.GET.get('drf_customers')" In list_drf_customer_branch() it works, but in list_customer_products() it returns null Is there something wrong with my approach? views.py: def list_drf_customer_branch(request): template_name = "poc/partials/drf_customer_branch.html" customer = request.GET.get('drf_customers') # this works, returns id if customer == "": drf_customer_branch = None else: drf_customer_branch = models.CustomerBranch.objects.filter( customer=customer).order_by("description") context = {} context["drf_customer_branch"] = drf_customer_branch context["is_htmx_branch"] = True return render(request, template_name, context=context) @login_required def list_customer_products(request): template_name = "poc/partials/drf_customer_products.html" context = {} context["form"] = forms.DrfDetailForm customer = request.GET.get('drf_customers') # this doesnt work, returns None if customer == "": customer_products = None else: customer_products = models.CustomerProduct.objects.select_related("product__brand", "product__brand_category", "customer").filter( customer=customer).order_by("product__brand", "product__description") context["drf_customer_products"] = customer_products return render(request, template_name, context=context) forms.html <div id="id_drf_customers" class="mb-3"> {% include 'poc/partials/drf_customers.html' %} </div> <div id="id_drf_customers" class="mb-3"> {% include 'poc/partials/drf_customer_branch.html' %} </div> <div id="id_drf_customer_products" class="mb-3"> {% include "poc/partials/drf_customer_products.html" %} </div> partials/drf_customers.html <select name="drf_customers" class="select form-select" id="id_drf_customers" hx-get="{% url 'poc:drf_customer_branch' %}" hx-trigger="change" hx-target="#id_drf_customer_branch" required > <option value="" selected disabled>Select Customer/Outlet</option> {% for i in drf_customers %} <option value="{{i.customer_id}}">{{i.customer_name}}</option> {% endfor %} </select>