Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/ Django_plotly_Dash (Exception Value: expected string or bytes-like object)
When I try to render a plot by Django_Plotly_Dash, I get a TypeError. Please, see below my code snippets and a taceback that I get. I've been trying to understand where the problem appears for hours but nothing comes into my mind. Could anybody, please, help me you here? simpleexample.py import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = DjangoDash('SimpleExample', external_stylesheets=external_stylesheets) app.layout = html.Div([ html.H1('Square Root Slider Graph'), dcc.Graph(id='slider-graph', animate=True, style={"backgroundColor": "#1a2d46", 'color': '#ffffff'}), dcc.Slider( id='slider-updatemode', marks={i: '{}'.format(i) for i in range(20)}, max=20, value=2, step=1, updatemode='drag', ), ]) welcome.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <block> <div> {% plotly_app name='SimpleExample' ratio=0.45 %} </div> </block> {% endblock %} views.py from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample urlpatterns = [ path('', views.home, name='home') This is the traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Python Version: 3.7.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'channels', 'channels_redis'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\milos\statisticsofcorona\templates\base.html, error at line 0 expected string or bytes-like object 1 : {% load … -
Why django class based View (DetailView) only works with a specific variable names
my English is not good, I apologize in advance. My following question is to understand why the variable template_name for example, with class by DetailView only works with exactly that variable name. For example in views.py: from django.views.generic import DetailView # /appPruebaDos/detailView/<int:pk> class DetailViewObject(DetailView): model = Articulo template_name = "plantillaDetailView.html" # varible fijado del tipo DetailView Why I can't use other variable like(this don't work): # /appPruebaDos/detailView/<int:pk> class DetailViewObject(DetailView): model = Articulo templateName = "plantillaDetailView.html" # varible fijado del tipo DetailView I think template_name field is defined in the DetailView dependencies, but how and where is defined? -
How do I get all current sessions from django?
I recently struggled to do this so i thought I would answer my own question to help. Found this out after playing with dir(Session.objects), after importing from django.contrib.sessions.models import Session. -
Hourly automatic update of Django database while avoiding duplicate entries
I know this question has been asked in the past, but it seems a lot has changed in the past few years so I'm hoping to find an up-to-date answer. I have a django app that collects third party data which is updated hourly (roughly) and saves that data to the appropriate models in my mySQL database. Right now I just run the database update view each time I manually reload my homepage. Is there a way to have this process automated so that data collection and database update is carried out every hour on its own? I've seen multiple options including celery or django managers (?) and I'm wondering what the current most popular method is. Secondary question. Sometimes the third party data provider updates their data irregularly (i.e., they miss an hour). This could potentially lead to my script collecting the same set of data more than once. Is there a way I can prevent it from saving that duplicate to my database? My initial thought is to scrape the data, then query my db to ensure that data does not already exist before saving it. Is this the preferred method or is there a faster option, as … -
How to track model changings in Django?
How to make model history in Django and do it in a safe way? For example, I have Balance and Transaction. How to link these models to reduce manually management? from django.db import models from djmoney.models.fields import MoneyField import django.contrib.auth.models as authm # Create your models here. class Balance(models.Model): user = models.ForeignKey(authm.User, primary_key=True) balance = MoneyField(max_digits=14, decimal_places=2, default_currency='RUB') class Transaction(models.Model): type = [('I', 'Income'), ('O', 'Outcome')] balance = models.ForeignKey(Balance) amount = MoneyField(max_digits=14, decimal_places=2, default_currency='RUB') type = models.CharField(max_length=1, choices=type) -
How to store the contact's phone number in memory in ChatBot using python-telegram-bot
I am working with python-telegram-bot building a menu system. I created a Django project, as shown below, using Webhook to connect to Telegram. When the first message is sent, I ask the contact for their phone number and keep this number so I don't need to ask for it in the next messages in the conversation, but it’s not working. I tried to store it in request.session, but apparently every new message is a new session and so I lose the number. How can I solve this? Every help is welcome. view.py import json from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt from core.message import proccess @csrf_exempt def event(request): json_telegram = json.loads(request.body) proccess(request, json_telegram) return HttpResponse() messages.py import telegram from bot_webhook.settings import TOKEN from telegram import InlineKeyboardMarkup, InlineKeyboardButton bot = telegram.Bot(token=TOKEN) def proccess(request, json_telegram): if 'login' in request.session: msg_options(json_telegram) else: try: request.session['login'] = json_telegram['message']['contact']['phone_number'] msg_options(json_telegram) except: msg_login(json_telegram) def msg_login(json_telegram): chat_id = json_telegram['message']['from']['id'] reply_markup = telegram.ReplyKeyboardMarkup( [[telegram.KeyboardButton('Click to Login', request_contact=True)]], resize_keyboard=True, one_time_keyboard=True ) bot.sendMessage(chat_id, 'I need to authorize your access.', reply_markup=reply_markup) def msg_options(json_telegram): chat_id = json_telegram['message']['from']['id'] first_name = json_telegram['message']['from']['first_name'] last_name = json_telegram['message']['from']['last_name'] button_list = [] button_list.append(InlineKeyboardButton('Button One', callback_data='query_one')) button_list.append(InlineKeyboardButton('Button two', callback_data='query_two')) reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2)) bot.send_message(text='Hello {0} {1}!\nI have this options:'.format(first_name, … -
Django Window annotation using combined with distinct clause
I have a Django model stored in a Postgres DB comprised of values of counts at irregular intervals: WidgetCount - Time - Count I'm trying to use a window function with Lag to give me a previous row's values as an annotation. My problem is when I try to combine it with some distinct date truncation the window function uses the source rows rather than the distinctly grouped ones. For example if I have the following rows: time count 2020-01-20 05:00 15 2020-01-20 06:00 20 2020-01-20 09:00 30 2020-01-21 06:00 35 2020-01-21 07:00 40 2020-01-22 04:00 50 2020-01-22 06:00 54 2020-01-22 09:00 58 And I want to return a queryset showing the first reading per day, I can use: from django.db.models.functions import Trunc WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day")) Which gives me: date count 01/01/20 15 01/01/21 35 01/01/22 50 I would like to add an annotation which gives me yesterday's value (so I can show the change per day). date count yesterday_count 01/01/20 15 01/01/21 35 15 01/01/22 50 35 If I do: from django.db.models.functions import Trunc, Lag from django.db.models import Window WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"), yesterday_count=Window(expression=Lag("count"))) The second row return gives me 30 for yesterday_count - ie, its showing me the previous row before … -
Django get_foo_display method on a queryset multiple result set
I am working on Django Rest Framework backend for React frontend and have a scenario where a model that I'm working with have a number of choice fields setup on Django side. Using the same key values I built fields on React side such as 'm','Male'. The problem I have is I can create a new record and send those key values (e.g. 'm'), but when I call an API to get me all records and display on the webpage, I want to see the full values coming from API directly. I know about the get_foo_display method and I used it on the Serializer and it did work for retrieving the results, but then broke the creation (post) method with below error: Got a TypeError when calling Person.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Person.objects.create(). You may need to make the field read-only, or override the PersonSerializer.create() method to handle this correctly. Is there a simple way to have both scenarios covered: 1. When creating records, send in key values associated with choice values. 2. When getting result sets using GET method, show full value of … -
Django Custom Inclussion Tags
I'm trying to use custom inclusion tag to display the latest 3 post titles on my blog sidebar, I don't seem to get any errors but my results didn't display either. Inclusion tag in[latest_posts.html file]1 templatestag.py including the template in base.html -
Django does not safe the values of the BooleanFields
I have the following form with few boolean fields: class RegistrationForm(UserCreationForm): guardianSource = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'guardianSource'}),required=False) bbcSource = forms.BooleanField(required=False) independentSource = forms.BooleanField(required=False) categoryCoronaVirus = forms.BooleanField(required=False) categoryPolitics = forms.BooleanField(required=False) categorySport = forms.BooleanField(required=False) #Telling the registration form what kind of data we are going to be modelling/ what the form needs to look like class Meta: model = Account fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport") The register template looks as following: <form class="form-signin" method="POST">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Register</h1> <label for="username" class="sr-only">Username</label> <input type="text" name="username" id="username" class="form-control" placeholder="User name" required autofocus> <label for="inputPassword1" class="sr-only">Password</label> <input type="password" name="password1" id="inputPassword1" class="form-control" placeholder="Password" required> <label for="inputPassword2" class="sr-only">Password</label> <input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Confirm Password" required> <br> <div class="form-control"> <p><b>Please choose news sources!</b></p> <label for="guardianSource" >The Guardian</label> <input type="checkbox" name="source" id="guardianSource"> <br> <label for="bbcSource" >BBC News</label> <input type="checkbox" name="source" id="bbcSource"> <br> <label for="independentSource" >The Independent</label> <input type="checkbox" name="source" id="independentSource"> </div> <br> <div class="form-control"> <p><b>Please choose news category!</b></p> <label for="categoryCoronaVirus" >Corona Virus</label> <input type="checkbox" name="category" id="categoryCoronaVirus"> <br> <label for="categoryPolitics" >Politics</label> <input type="checkbox" name="category" id="categoryPolitics"> <br> <label for="categorySport" >Sport</label> <input type="checkbox" name="category" id="categorySport"> </div> {% for field in registration_form %} <p> {% for error in field.errors %} <p class="alert alert-danger card-header text-center flashit"> {{ … -
Type <class 'authorizenet.apicontractsv1.STD_ANON_15'> cannot be created from: 4007000000027
I'm i litle lost here , i know that the form pass the credit card but we can see in the error authorizenet raise an error. someone help if possible !! thanks! def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): card_number = request.POST.get('card_number') Payment.objects.charge_credit_card(Decimal ('27.55'), card_number, request.POST) return HttpResponseRedirect('/success/') return render(request, self.template_name, {'form': form}) -
TypeError: __init__() got an unexpected keyword argument 'validators'
I want to validate phone_number in my form with RegexValidator I find this validator in here and it works all right in model.py but in forms.py I get this error can any one help me? here is my model.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional blood_type = models.CharField(max_length=2,blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) description = models.TextField(blank=True) case =models.CharField(max_length=30,blank=True) def __str__(self): return self.user.username and this is forms.py: class UserProfileForm(forms.ModelForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") class Meta(): model = UserProfile fields = ('case', 'blood_type', 'phone_number','description') labels = { 'description': '', 'case':'', 'blood_type':'', 'phone_number':'', } widgets = { 'phone_number': forms.TextInput(attrs={'placeholder':'Phone number'},validators=[phone_regex]), 'blood_type': forms.Select(choices=BLOOD_TYPES), 'case': forms.Select(choices=CASE), 'description': forms.Textarea(attrs={'class':'customtext', 'placeholder':'Please write your ilness...'}), } -
Difference between Wagtail admin Site and Django admin Site?
This may be a basic question, but it puzzles me and I couldn't find an answer on the web. In my Wagtail admin I see a menu entry 'Sites' with (in my case) one item, in which I can configure a host name, a port, a site name, a Wagtail root page and a boolean 'is default site'. When I log in to django-admin (for the same project obviously) I see a menu entry 'Sites' with one item, with only two fields: domain name, display name. Changing it in one admin doesn't seem to change anything in the other. E.g. I needed to change the domain name (default in Django 'example.com') but couldn't find that in Wagtail admin. Are the two related in some way, and if so, why don't I see the same fields on both admins? Am I missing something obvious? -
Django Bootstrap card-deck if forloop divisibleby
I'm trying to use bootstrap cards. But I have problem. When I adding new post to be display as a card, and i display more then 5 they starting to squize. I'm was try to use forloop counter to start new line every time when it display more then 5 cards. But Im doing something wrong. I read everything and everywhere is the same thing. But I'm for sure doing this wrong. <div class="card-deck"> {% for post in post_list %} {% if forloop.counter0|divisibleby:3 %} <div class="card border-primary mb-3" style="max-width: 20rem;"> <a href="{% url 'post_detail' post.slug %}"> <img style="height: 200px; width: 100%; display: block;" src="{{ post.thumb.url }}" alt="Card image"></a> <div class="card-header">Header</div> <div class="card-body"> <h4 class="card-title">{{ post.title }}</h4> <p class="card-text">{{post.content|slice:":200" }}</p> </div> </div> {% endif %} </div> </div> {% endfor %} Reference image -
In Django how to user Application A serializer in Application B and manipulate a value using SerializerMethodField
App a --> serializer.py App b --> serializer.py Now in a App I need to import b serializer.py In app a from b.serializers import aserializers class aserializers(serializers.ModelSerializer): Now I've a filed "is_prod" in a serializers whose value is either 1 or 0 if it is 1 it should prod and if it's 0 it should show non-prod. I can't use App b serializers as it's already written and used in various places. -
how to make a multiple type users in django?
I am Building an app for a Charity and I need to make a system with different forms for six different user types. the six types are : patients(with the ability to work or not), founders & managers, regular users, volunteers, Financial & work sponsors. patients form has : name, the date of injury, injury percentage, age, gender and some other stuff other users have unique fields like patients for themselves. for now I just want to make the forms and add users from the admin page. should I make six individual forms and inherit from user creation form? if so, how to separate them in the admin page? Can I use one authentication for all of them? I am so confused! could you please help me to make a multiple user sign up forms! I have no idea about the code!!! thanks for the responses -
I have a Jupyter notebook / SciKit model for NBA predictions I want to publish online
Honestly not sure how to frame this as effectively as possible. I built an NBA prediction model that outputs results of matches as well as probabilities of victory. Basically, it inputs certain stats about both teams and outputs the likelihood of each team winning. I built this on a local Jupyter Notebook, and I run one notebook to compile today's schedule and stats into a csv, and turn this csv in a panda df and run it through my model. I know the NBA season has been postponed but I wanted to build this website anyways, where basically I wanted to publish my predictions for friends and others to see. There are 2 ways I see this being done but correct me if I'm wrong: 1. Where I run the model locally and update a database with these predictions and my website will pull the data from this database. 2. Ideally, I would like the model to be hosted online and run automatically every day and execute the scripts that I would run locally to compile daily predictions without my input. Basically I am looking for help on what type of infrastructure I should actually use and what I need … -
Django queryset with partial nested lists
I have two models : class Project(models.Model): name = models.CharField(max_length=255) client = models.ForeignKey(client, on_delete=models.CASCADE) class Client(model.Model): name = models.CharFiled(max_length=255) Assume my data is : Client table - [{id:1,name:client1}, {id:2, name:client2} Project table - [{id:1, name: project1, client:1}, {id:2, name: project2, client:1}, {id:3, name: projects, client:2}] a Client.objects.all() QuerySet will return two objects, client1 and client2 which client 1 has 2 projects and client2 have only 1. I am trying to order a QuerySet by a project name, but per Client object. doing so this way : clients = Client.objects.order_by("project__name") as Expected the result will provide 3 clients object, 2 for client1 and one for client 2. However, my problem is that each client object contains all the projects and not only the specific ordered one. I am trying to filter for each client object, even if the client is the same only the requested ordered projects. I can theoretically do that manually after receiving the queryset, but I assume there is a way to do it because the request does know which project specifically cause the creation of a new row in the queryset. -
How to run the packaged application from django's polls tutorial?
https://docs.djangoproject.com/en/3.0/intro/reusable-apps/ After it's packaged, the documentation says that 'With luck, your Django project should now work correctly again. Run the server again to confirm this.'. In this tutorial, to start the server, do this: python manage.py runserver But after this is packaged and installed to the user directory, it has been moved out of the project, and 'manage.py' isn't available. How to run the server and test the newly installed package? This may be a silly question, but the doc does lack a key sentence to tell how to start the server to run the installed package. -
Override Django's ManyToManyField with Custom fields and Access It
I have created ManyToManyPatchedField by overriding class ManyToManyField. In the new class, I have added a new column called created (Datetime Field). I did this by overriding function contribute_to_class and create_many_to_many_intermediary_model to add a new column created. The patched Django function looks like this. def create_many_to_many_intermediary_patched_model(field, klass): """ Override function create_many_to_many_intermediary_model in django.db.models.fields.related to add new columns created and foreign key to Comments table """ from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = '%s_%s' % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = 'to_%s' % to from_ = 'from_%s' % from_ meta = type(str('Meta'), (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': (from_, to), 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to}, 'apps': field.model._meta.apps, }) # Construct and return the new class. return type(str(name), (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey( klass, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), # Custom created field 'created': models.DateTimeField(auto_now_add=True) }) When I try to access the row using model1.model2.through.objects.all().values(), it returns … -
django MultiValueDictKeyError and RuntimeError in saving a form's data in database
I am trying it very hard but I didn't find what I am missing. I have made a form that contains fields like the first name, last name, address, city, state, zip and one Image file from the user. But I am getting this error when I was trying to post data by views. MultiValueDictKeyError at /submit_your_task 'image' Request Method: POST Request URL: http://127.0.0.1:8000/submit_your_task Django Version: 2.2.4 Exception Type: MultiValueDictKeyError Exception Value: 'image' and this is my views.py for that form def submit_your_task(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] address = request.POST['address'] phone = request.POST['phone'] city = request.POST['city'] state = request.POST['state'] zip = request.POST['zip'] image = request.FILES['image'] fs = FileSystemStorage() file = fs.save(image.name, image) url = fs.url(file) submit_task = SubmitYourTask(first_name=first_name, last_name=last_name, address=address, phone=phone, city=city, state=state, zip=zip, image=url) submit_task.save() return render(request, 'submit_task.html') and this is urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home-page'), path('about/', views.about_us, name='about'), path('signup/', views.signup, name='signup'), path('submit_your_task/', views.submit_your_task, name='submit_your_task'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And when I put the slash after 'submit_your_task' it gives me RuntimeError RuntimeError at /submit_your_task You called this URL via POST, but the … -
Different lines does not appear in context in Django
If I have code like hello_worlds = 'hello Earth \n hello Mars' context = { 'hellos':hello_worlds } return render(request, 'home.html', context) and home.html is {{hellos}} It displays as hello Earth hello Mars not hello Earth hello Mars I'm using Django 2.1.5 and python 3.8 is there a way to have it display like the second one? -
jQuery String Matching Django Generated String
I have a script that highlights certain blocks of text on a page generated by Django. The script works fine until the block of text contains an apostrophe. It won't match in that case. I've tried various combinations of filters, escaping, etc. but can't seem to get it working. Below is my code. jQuery in template: <script> $(document).ready(function(){ // Displays highlights if any exist {% for highlight in agenda.highlights.all %} $( "div.card-body div.mb-3:contains('{{ agenda.agenda_text|hl_slice:highlight }}')" ).css( "background-color", "#FFFF00" ).attr("id", "{{ highlight.id }}"); {% endfor %} }); </script> Django "hl_slice" custom filter @register.filter @stringfilter def hl_slice(agenda_text, hl): """ Returns the highlighted portion of the agenda text. """ try: hl_text = strip_tags(agenda_text[hl.start:hl.end]) return hl_text except (ValueError, TypeError): return hl # Fail silently. Text blocks in template (generates HTML divs containing text) {{ agenda.agenda_text|safe }} Here is an example of text that breaks the match: "K. 20-378 Notification of City Manager's and Assistant City Manager's execution of Professional Consultant Agreements and Amendments to an Agreement, as well as Public Construction Contracts not subject to the Competitive Bid Act, with a Contract values of less than $25,000" If I take out the apostrophes, the text will match, so I know it has something to … -
Center bootstrap toggle navbar
**Hi, I have struggled all day to make my navbar center on the page without any luck. I have used bootstrap to create the navbar. I would be extremely happy if someone could help me out.** URL <!DOCTYPE html> <html lang="en"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- Required meta tags --> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-info d-flex justify-content-center"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse h3" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> </div> </nav> <div class="jumbotron jumbotron-fluid bg-info text-white text-center""> <div class="container"> <h1 class="display-4">c.magelssen</h1> <p class="lead">A resource on psychology, teaching, skiing and coding.</p> </div> </div> </div> -
Pass data from template to django's views.py
Right now i'm working on the pagination of the data table at my django's project. And i'm trying to let the user put how many registers are displayed per page, but i'm having troubles passing the number at the selector that i'm using to views.py (where the pagination is), my question is: How to pass the selected number to views.py so it updates the registers? this is my code: Template's Selector: <form action="" method="POST"> <select class="selector" id="estado" name="estado" onchange="post()" style="border-color: #C9C9C9; color:black; height: 25px; width:100px; position:absolute; margin-top:-32px; margin-left:230px;"> <option selected style="color:black;">5</option> <option style="color:black;">10</option> <option style="color:black;">25</option> <option style="color:black;">50</option> <option style="color:black;">100</option> </select> </form> Views.py: if request.method == 'POST': inicial = { 'paginas' : 5, } num = paginaForm(initial = inicial).fields['paginas'] else: num = 5 riesgos = Riesgos.objects.all() #Paginación paginator = Paginator(riesgos, num) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = {'riesgos':riesgos, 'page_range':page_range, 'items':items} return render(request,'restapi/listar_riesgo.html', context) Models.py class Paginas(models.Model): paginas = models.IntegerField(primary_key= True) Forms.py: class paginaForm(forms.ModelForm): class Meta: …