Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why using anchor tags directly doesn't work and what is the solution
How to work with anchor tags in django?I mean what things should i include in url to make it working .Say I have home,about and contact page.When I go to about and contact error pops up but home seems to work just fine. I tried including all of home,contact and about in the same render method but I guess it's incorrect -
Django doesn't import UserCreationForm
I try to import UserCreationForm from django.contrib.auth.forms. However I got en error like this: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What does this mean? I follow this question. However in my wsgi.py file this kind of settings were set up. What should I do? UPDATE: The same error raises when I try to run this code: from django.contrib.auth.models import User. -
Getting ChromeDriver from Selenium
I'm dockerizing my Python-Selenium application, and have this three lines in my Dockerfile: RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' RUN apt-get update -qqy --no-install-recommends && apt-get install -qqy --no-install-recommends google-chrome-stable While outside Docker it works okay, when running selenium inside Dockerized app I get this error: (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) I'm initializing my selenium function with this code, but I guess when Dockerizing it the service part may need to change? Anyone can guide? def function_scrap(data1): # op = webdriver.ChromeOptions() # op.add_argument('headless') chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_prefs = {} chrome_options.experimental_options["prefs"] = chrome_prefs chrome_prefs["profile.default_content_settings"] = {"images": 2} driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=chrome_options) -
Django update database each second
I'm trying to update Django's project database each second. For now, I can deal with Javascript's function setInterval in my template html but each time I refresh the page or reload my server the values restarts at my database values. I think it could be better to deal that directly in the views.py and then call the variables in my html but got no idea how I can do an incrementation each sec in that way. here is my code using Javascript's function setInterval : #models.py class materiaux(models.Model): nom = models.CharField(max_length=100) nombre = models.IntegerField() production = models.IntegerField() class Meta: ordering = ['id'] def __str__(self): return str(self.nom) #views.py def objetUpdate(request): items = materiaux.objects.all() for item in items: if item.nom == "objet1": nombre_objet1 = item.nombre production_objet1 = item.production if item.nom == "objet2": nombre_objet2 = item.nombre production_objet2 = item.production if item.nom == "objet3": nombre_objet3 = item.nombre production_objet3 = item.production return render(request, 'materiaux.html', {'nombre_objet1': nombre_objet1, 'production_objet1':production_objet1, nombre_objet2': nombre_objet2, 'production_objet2':production_objet2, 'nombre_objet3': nombre_objet3, 'production_objet3':production_objet3}) #materiaux.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}Matériaux{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> <script> var nombreObjets1= {{ nombre_objet1 }}; var nombreObjets2= {{ nombre_objet2 }}; var nombreObjets3= {{ nombre_objet3 }}; var productionObjets1 … -
How To Make Auto Blogger using Python for django bloging website
I want to create an auto blogger for my website. I use react and Django REST to build my website. The auto blogger will copy the article with an image from another blog website and post it on my website. Example: WordPress auto blogger plugin. Click here --> wordpress auto blogger package -
Fernet cryptography.fernet djnago
I am using cryptography.fernet in my views.py and I get this error: File "C:\Users\DIDAM\Desktop\venv\Lib\site-packages\rest_framework\relations.py", line 190, in get_attribute return super().get_attribute(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIDAM\Desktop\venv\Lib\site-packages\rest_framework\fields.py", line 479, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `course` on serializer `SectionSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'course'. [18/Jan/2023 09:01:55] "GET /api/chapter-section-list/1/ HTTP/1.1" 500 140636 -
how to pass Two params value in one url
event_category = self.request.query_params.get('event_category').split(',') event_subcategory = self.request.query_params.get('event_subcategory') AttributeError: 'NoneType' object has no attribute 'split' i passing event_subcategory params..i get AttributeError: 'NoneType' object has no attribute 'split' -
python django landscape page generating pdf report
I am working on a django project and I have already created PDF report but I want landscape page because some data is hiding after generating PDF report: views.py: def export-pdf(request): response = HttpResponse(content_type = 'application/pdf') response['Content-Disposition'] = 'inline; attachment; fileName=ABC Reports' +\ str(datetime.datetime.now())+'.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string = render_to_string('enroll/pdf-output.html', context) html = HTML(string=html_string) result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response I have shared the image of pdf report where you can see that status column and its related data is hiding, therefore I need landscape page or an arrangement of page by hard code where I can adjust the pdf report page according to my need. -
Django+AlpineJS : fetching ForeignKey object data with x-init and x-data and iterating over it
(edit, the post formatting got messed up, ugh) I have 2 models, Band (has parameters name, genre, country) and Album (has a band ForeignKey, and other parameters - name and year), and I'm trying to serialize it with AlpineJS so that I have a page displaying a list of bands with a list of corresponding albums beside them. I can do it normally without Alpine, but for this case I need to build a filtering search (like by genre or year, but that's not the current issue) with Alpine so I just have to use it. I also know how to fetch data of objects from one model, but when it's two of them within the same x-data div I'm at loss. Perhaps is there a way of making one single function that has both all Band AND Album data? But then how would I list them beside each other if there's no id requested, I don't know. Damn I get lost at this though I understand all these object relations for the most part. The code below is what I have right now. Tried this, the inner x-for loop doesn't work, but it works fine without it, i.e. if … -
How to implement navigation DB data in Django?
got this code from a friend, we use django and bootstrap to make a rather simple site that displays job offers, until now we displayed the job offers in a row and each offer had a button "apply" that sent the resume etc.. But we would like to change that and only display one job at a time, each job would have 2 buttons "apply" and "next". We tried in a barbaric way to do all this but we have a problem, the next button works well thanks to a little javascript incorporated by my friend but the "apply" button we would like to move to the next offer after clicking on it, for now it only applies we can't get it to display the next offer, how to do? Thank you very much for simplifying your answers I am a beginner in web development, here is the code of my Django template: {% extends 'base2.html' %} {% load static %} {% block title %} Dashboard {% endblock %} {% block content %} <body class="hold-transition light-mode layout-fixed layout-navbar-fixed layout-footer-fixed"> <div class="wrapper" > <div class="content-wrapper" > <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> … -
Inline Images are also being attached
I am using templated_email package to send emails and embedding images using the below code block. Inline images are also being added as attachments in some devices. I don't want them to added as attachments. Is there any solution? with open(path_to_img, 'rb') as image: image = image.read() inline_image = InlineImage(filename=image_name, content=image) This is the documentation of the templated_email package https://pypi.org/project/django-templated-email/#:~:text=with%20open(%27pikachu.png%27%2C%20%27rb%27)%20as%20pikachu%3A I found a solution where if we use MIMEMultipart('related') it will solve the issue if we are using MIME to embed images directly. I want to implement the same while using Django's templated_email package. -
ferrocarrilFormulario() missing 1 required positional argument: 'request'
I need help with my code, I'm making a form in django and I can't solve this error. views.py: def ferrocarrilFormulario(request): if request.method =="POST": miFormulario = ferrocarrilFormulario(request.POST) print(miFormulario) if miFormulario.is_valid: informacion = miFormulario.cleaned_data ferrocarril = ferrocarril(request.POST["tipo"], request.POST["precio"]) ferrocarril.save() return render (request, "AppCoder/inicio.html") Forms.py: from django import forms class ferrocarrilFormulario(forms.Form): tipo= forms.CharField() precio = forms.IntegerField() Form HTML: <!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>Agrega un ferrocarril</title> </head> <body> {% if.miFormulario.errors %} <p style="color: red;"> Datos mal ingresados</p> {% endif %} <form action="" method="POST"{% csrf_token %} <table> {{ miFormulario.as_tabble }} </table> <input type="submit" value="Enviar"> ></form> </body> </html> urls.py: from django.urls import path from AppCoder import views urlpatterns = [ path('',views.inicio, name="Inicio"), path("ferrocarril/", views.ferrocarril, name="ferrocarril"), path("vias/", views.vias, name="vias"), path("manodeobra/", views.manodeobra, name="manodeobra"), path("tables.html/", views.tables, name="tables"), path("ferrocarrilFormulario/", views.ferrocarrilFormulario, name="ferrocarrilFormulario") thank you <3 I wanted the form to work after that, but that is not the case. PS: if I put the request, it generates another error, and in the tutorial it appears without the request. Thanks again. -
How can I sort by calculated fields in Django Admin?
I have a calculated method in my model, and in admin page want to add sort functionality for that calculated field. For now, I am using aggregation for model calculated fields and displaying that in admin. How can I add sort function for this field in admin page? class CoinWallet(Account): student = models.OneToOneField( 'students.Student', on_delete=models.PROTECT, related_name="coinWallet", null=True) @admin.display(description='Total Coins') def total_coins(self): positive_movements_aggregate = self.movement_set.filter( side=self.positive_side, ).aggregate(models.Sum('amount')) positive_movements_balance = positive_movements_aggregate[ 'amount__sum'] if positive_movements_aggregate['amount__sum'] else 0 return f'{positive_movements_balance}' @admin.register(CoinWallet) class CoinWalletAdmin(admin.ModelAdmin): list_display = ('id', 'student', 'balance', 'total_coins', 'answer_coins', 'bonus_coins', ) search_fields = ('id', 'student') def get_queryset(self, request): queryset = super(CoinWalletAdmin, self).get_queryset(request) queryset = queryset.annotate(_total_coins=ExpressionWrapper(F('balance'), output_field=DecimalField())).order_by('_total_coins') return queryset def total_coins(self, obj): return obj._total_coins total_coins.admin_order_field = '_total_coins' I tried this, but, instead of balance, i want to add sortable for total_coins. What should I do in this admin class? -
What is the best way to send field values for model creation in URL in DRF?
I have and app with books, where I want to have POST request with field's value in URL like POST URL:BOOKS/NINETEEN_EIGHTY_FOUR HTTP/1.1 content-type: application/json { "description": "my favorite book" } RESPONSE { "description": "my favorite book", "book_name": "NINETEEN_EIGHTY_FOUR" } What is the best way to do it in DRF? I have my book model with 2 field: description and book_name And in my views.py I have viewset (connected to router book) which is working with books: for example GET books/ will return full list of books and through @action decorator I get GET/POST books/{book_name} requests class BookViewSet(ListViewSet): queryset = Book.objects.all() serializer_class = BookSerializer @action(methods=['get', 'post', ], detail=False, url_path=r'(?P<book_name>\w+)',) def get_or_create_book(self, request, book_name): if request.method == 'GET': book = get_object_or_404(Book, book_name=book_name) etc book, create = Book.objects.get_or_create(book_name=book_name) Are there something better ways? -
Request.urlopen does not work after moving the server to the cloud. use docker-compose django, nginx
Yesterday, I moved to the cloud while running the server locally. Based on ubuntu 20, the server is operated using docker, django, nginx, mariadb, certbot in docker-compose. is configured and operational. It has opened both 80:port and 443post to the cloud, and outbound is allowed in the cloud itself. In docker-compose, if you receive a request from 80 or 433 from nginx.conf to upstream django_nginx server container name: 8000 after mapping from docker-compose to 80 or 433 for the application --bind 0.0.0.0:8000 Jango. Proxy_pass http://django_nginx; is passing. The problem is that when an external api is called from a running django inside the docker container (e.g. request.urlopen(url) header included or not included), there is no response. So I gave the option request.url, timeout=3 and checked, and the https request causes We failed to reach a server /Reason: _ssl.c: 980: The handshake operation timed out http request causes We failed to reach a server /Reason: timed out. I used to run a server locally as a virtual machine, but it was a logic that was going on without a problem before, so I'm very embarrassed because it didn't work after the cloud transfer. I'm inquiring because I haven't made any progress … -
Stripe Subscription Update with Django and React
I have developed backend implementation for Stripe API calls to handle the following requests : urlpatterns = [ path('subscription', SubscriptionCreate.as_view(), name="create_subscription"), path('add_payment_method', PaymentIntentCreate.as_view(), name="add_payment_method"), path('delete_payment_method', PaymentIntentDelete.as_view(), name="add_payment_method"), path('customer', CustomerView.as_view(), name="customerview"), path('webhook', stripe_webhook, name="stripe_webhook") ] Here below are my models in Django backend to handle information regarding products and the customer : class Product(models.Model): class Plan(models.IntegerChoices): FREE = 0, _('Free') BASIC = 1, _('Basic') PREMIUM = 2, _('Premium') ENTENPRISE = 3, _('Enterprise') plan = models.PositiveSmallIntegerField(choices=Plan.choices, null=False, blank=False, default=Plan.FREE) stripe_plan_id = models.CharField(max_length=40) class Customer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40, default="") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) stripe_subscription_id = models.CharField(max_length=40, default="") clientsecret = models.CharField(max_length=80, default="") active = models.BooleanField(default=True) Also I have a post_save function that is triggered by "User Creation in Django" which also creates a Stripe Customer associated with each user and a subscription with a FREE plan that does not require payment / card information : post_save.connect(post_save_customer_create, sender=settings.AUTH_USER_MODEL) stripe_subscription = stripe.Subscription.create( customer=customer.stripe_customer_id, items=[{"price": customer.product.stripe_plan_id},], payment_behavior='default_incomplete', payment_settings={'save_default_payment_method': 'on_subscription'}, expand=['latest_invoice.payment_intent'], ) However, when the user wants to upgrade their subscription from Free to Paid models (Basic, Premium, Enterprise) then payment method / card information is required. In this case I want the subscription get into a "Incomplete" state until the payment is … -
how to insert images from database to html jinja
I'm trying to pull the link from the database in the src part, but I couldn't. im using django. images are in s3 storage. i append link to sqlite database in django. normally, {{project.ac}} is working. but <img src=> is not working. JİNJA TEMPLATE CODE <figure class="glitch-filter-example"> <figcaption class="glitch-filter-example__heading">{{ project.ac }}</figcaption><br/><br/> <img src={{ project.image }}> <img src={{ project.image2 }}> <p class="glitch-filter-example__filtered-text">HTML text</p> </figure> <script src="{% static 'icerik/js/script.js' %}"></script> PAGE SOURCE <figcaption class="glitch-filter-example__heading">MY TEXT</figcaption><br/><br/> <img src=> <img src=> -
How to generate Django / Python Test for view with LoginRequiredMixin and UserPassesTestMixin
I am trying for some time to test a view of mine that I have protected from access via LoginRequiredMixin and UserPassesTestMixin. Unfortunately I do not manage to write the appropriate test. here is the view. The special thing is, that the user must not only be logged in, but he must also belong to the group "Administrator" or "Supervisor". With this combination I have not yet managed to write a test. Please who can help me. Here is my View: class FeatureListView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = FeatureFilm template_name = "project/feature-list.html" def test_func(self): if self.request.user.groups.filter(name="Administrator").exists(): return True elif self.request.user.groups.filter(name="Supervisor").exists(): return True elif self.request.user.groups.filter(name="Operator").exists(): return True else: return False def handle_no_permission(self): return redirect("access-denied") and here is a snippet of the url.py: urlpatterns = [ path("feature/list/", FeatureListView.as_view(), name="feature-list"), path( "feature/<int:pk>/date", FeatureDetailViewDate.as_view(), name="feature-detail-date", ), how would you test this FeatureListView and the template belongs to thank you very much! -
Django: How does one mock a method called in an api test?
I keep hitting a method scan_file() that should be mocked. It happens while calling self.client.post() in a django api test. The app setup is below, I've tried mocked the imported scan_file patch("myapp.views.scan_file") as well as the source location patch("myapp.utils.scan_file") neither work. # myapp.views.py from myapp.utils import scan_file class MyViewset(): def scan(): scan_file() # <- this should be mocked but its entering the code #myapp.utils.py def scan_file() -> bool: boolean_result = call_api() return boolean_result #test_api.py class MyAppTest(): def test_scan_endpoint(self): patcher = patch("myapp.views.scan_file") MockedScan = patcher.start() MockedScan.return_value = True # This post hits the scan_file code during the api # call but it should be mocked. resp = self.client.post( SCAN_ENDPOINT, data={ "file" :self.text_file, "field1" : "Progress" } ) I've also tried the following syntax for mocking, and tried including it in the test setup() as well: self.patcher = patch("myapp.views.scan_file") self.MockedScan = self.patcher.start() self.MockedScan.return_value = True -
How are Django's form assets (Media class) served?
The "Form Assets" page of Django says Django allows you to associate different files – like stylesheets and scripts – with the forms and widgets that require those assets. For example, if you want to use a calendar to render DateFields, you can define a custom Calendar widget. This widget can then be associated with the CSS and JavaScript that is required to render the calendar. When the Calendar widget is used on a form, Django is able to identify the CSS and JavaScript files that are required, and provide the list of file names in a form suitable for inclusion on your web page. Okay, but what component of Django takes those form assets and actually puts them in the page? I ask because I'm trying to use django-autocomplete-light (DAL) with django-bootstrap5 on a multi-select form with a many-to-many field. I've done all the installing, put the widget on my form field: class SomeForm(forms.ModelForm): class Meta: model = Something fields = ['things'] widgets = { 'things': autocomplete.ModelSelect2Multiple( url='myapp:things-autocomplete') } I can see the HTML for the form widget includes autocomplete-light stuff to multi-select "things" with "things" autocomplete: ... <select name="things" class="form-select" required id="id_things" data-autocomplete-light-language="en" data-autocomplete-light-url="/thing-autocomplete/" data-autocomplete-light-function="select2" multiple> </select> ... … -
Will I be able to use a wordpress site domain as a django website on a VPS?
I deleted all the files and folders associated with the Wordpress site I intend to write from scratch using standard HTML, JavaScript, CSS and with Django framework. My question is if I can use this domain with this newly created site in a VPS. At first I had erased the files and folders and recreated it with the Django app right onto the Wordpress structure, and that does not seem to be working. I am most likely doing something wrong anyways, but I am after the right way of accomplishing this. -
Django cannot migrate on Galera but MariaDB standalone works
I'm using Django together with MariaDB, I now moved my application to K8s and my Django migration don't want to run through, instead the whole migration process fails. On my local development system I'm using a standalone MariaDB instance where everything is working fine. How can it be that the same process is not working against a Galera-Cluster, here the output of my application is the following while trying to migrate all the tables: python manage.py migrate Operations to perform: Apply all migrations: App, App_Accounts, App_Storages, admin, auth, contenttypes, database, django_celery_results, sessions, sites Running migrations: Applying contenttypes.0002_remove_content_type_name... OK Applying App_Storages.0001_initial... OK Applying App_Accounts.0001_initial...Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django_prometheus/db/common.py", line 71, in execute return super().execute(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) ^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/venv/lib/python3.11/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1170, "BLOB/TEXT column 'avatar_path' used in key specification without a key length") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/strics/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line … -
I want to make a checkbox type filter on the items of an e-commerce
I have a simple e-commerce where I want to filter items. This will be done in a form checkbox, but the form's categories are user-created, ie it's a "for" of Cor.objects.all() . The filter only works for the last selected color. So I wanted it to have multiple filters. index.html: <div class="widgets-item"> <form id="widgets-checkbox-form" action="{% url 'carro_filtro' %}" method="GET"> <ul class="widgets-checkbox"> {% for cor in cores %} <li> <input class="input-checkbox" type="checkbox" id="color-selection-{{ cor.id }}" name="termo" value="{{ cor.nome_cor }}"> <label class="label-checkbox mb-0" for="color-selection-{{ cor.id }}"> {{ cor.nome_cor }} </label> </li> {% endfor %} </ul> <input type="submit" class="btn btn-custom-size lg-size btn-primary w-100 mb-5 mt-5" value="Filtrar"> </form> </div> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.CarView.as_view(), name='shop'), path('filtro/', views.CarroFiltro.as_view(), name='carro_filtro'), ] views.py class CarView(ListView): model = Car template_name = 'shop/index.html' paginate_by = 12 context_object_name = 'cars' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['personalizacoes'] = Shop.objects.filter( publicado_shop=True).order_by('-id').first() context['categorias'] = Categoria.objects.all() context['cores'] = Cor.objects.all() return context def get_queryset(self): qs = super().get_queryset() categoria = self.kwargs.get('nome_categoria', None) if not categoria: qs = qs.filter(publicado=True).order_by('-id') return qs qs = qs.filter( categoria_carro__nome_categoria__iexact=categoria, publicado=True).order_by('-id') return qs class CarroFiltro(CarView): def get_queryset(self): qs = super().get_queryset() color_selection = self.request.GET.get('termo') print("X"*100) print(color_selection) print("X"*100) if not color_selection or color_selection is … -
Django custom selection HTML page for django admin form
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page. I have done a 100 times before, but now the value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none Driving me crazy, I cannot find anything wrong in the code The Html template {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_modify %} {% block extrahead %} {{ media }} {% endblock %} {% block content %} <form class="change_superprofile_parent_form" method="POST" class="change_superprofile_parent_form">{% csrf_token %} {% for superprofile in superprofiles %} <input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br> {% endfor %} <input type="submit" value="Submit"> </form> {% endblock %} Django admin.py def change_superprofile_parent(self, request, queryset): """ Action to change the superprofile of the selected """ queryset = queryset.values_list("id", flat=True) if request.method == 'POST': selected_value = request.POST.getlist('superprofile_selected') eligible_superprofiles = SuperProfile.objects.filter(status='Active') return render( request, 'admin/auth/user/change_superprofile_parent.html', context={ 'superprofiles': eligible_superprofiles, } ) -
Django: Pass non-editable data from the client to the server
I am building a media tracker for TV shows and movies. When the user makes a query on the front-end, on the server I make a request with an API in which I get TV shows/movies with id, title, image link, media type, seasons, etc. After that, I display the result of the query on the front-end with the name and image: Then the user can select one of the results and get a simple form: The thing is that after submitting the form, I want to save the score and progress with the id, media type and other parameters that aren't shown on the front-end but are related to the media submitted. At the moment I am using to pass the values to the server: <input type="hidden" name="id" value="{{media.response.id}}"> The problem with this is that the user could change the id value with the developer tool (inspector), which would cause problems. I don't really know how to validate the form as the id could be any number. Is there a better and still simple approach? Thanks in advance