Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form and formset together in a wizard step
I have a form wizard in Django. In the first step I need to insert data about a transport request, and a message, which is in another model. In second step I add passengers using a formset, and in the last one, the addresses, also in a formset. I don't know how to insert the message field in the first step. I tried to add a formset in the context overriding the get_context_data method from the SessionWizardView (code below). It shows the field, but I couldn't figure it out how to save it. I saw this post Django form with fields from two different models, but the SessionWizardView does not allow me to add a view with two forms in a step, I can only add forms. I have also read this one django wizard, using form and formset in the same step, but it doesn't works, maybe because it is from 6 years ago. My last try was to add a custom field in the transport ModelForm (not in the code below), but I think it will not be the right way to do it (I still don't know how to save the message this way). The code is … -
Q: Django, How to force logout a user from another app?
I'm writing a django project that will act as FreeRadius backend (via it's rlm_rest) It's specificaly for captive portal login. I also use allauth with this project. Basicaly, user have to login to my site first before the captive portal send radius request. Currently, it's just work. But (yes there is a 'but') When the user logout from captive portal, captive portal just kick them out from it, and tell radius that the user logged out. When the portal tell radius, radius will call my project to book that event ... just like normal radius-acct. So ... Is there any way for me to check all session belonging to that user and flush it ? If so, kindly please give me some clue. Sincerely -
Letsencrypt certificate renewal issue on Ubuntu 18.04 machine using Apache Server
I am using Apache servers to host my Django (v2.1) app. I've installed Letsencrypt certificate for HTTPS. Now the time of renewal has come and it is giving me some unauthorized access error. When I run sudo certbot command, I got the following output. /usr/lib/python3/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.23) or chardet (3.0.4) doesn't match a supported version! RequestsDependencyWarning) Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator apache, Installer apache Which names would you like to activate HTTPS for? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: noppera.tk 2: www.noppera.tk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate numbers separated by commas and/or spaces, or leave input blank to select all options shown (Enter 'c' to cancel): 2 Cert is due for renewal, auto-renewing... Renewing an existing certificate Performing the following challenges: http-01 challenge … -
Google Cloud Django app - sever timesout at IP:8000 (0.0.0.0:8000)
I'm new to two things: Google Cloud and deploying a live Django App. I haven't found anything useful, regarding Google Docs for deploying the Django app, but I did find a reference written by DigitalOcean -> https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#create-and-configure-a-new-django-project I have followed this guide to the letter and when I get to the step of python manage.py runserver 0.0.0.0:8000, nothing works. I go to my_ip_:8000 and it just times out. However, on my ip (without the port 8000), it see the message for the Nginx server. So far my steps have been: 1. Create a VM with Ubuntu 16.04. 2. Used Putty to generate the SSH keys (I updated the key in the VM) 3. Placed the new url into the Allowed_hosts part of the settings.py file. 4. Updated my DNS settings with the new url. 5. Followed the tutorial above, step by step. I haven't used any Cloud SQL or any other google tools outside of this tutorial. I don't get any error message when I run the python server. The page my_ip_:8000 just times out. I'm at a loss. I honestly don't know what to do and any feedback or suggestions are appreciated. I don't know what code would be … -
Seed a user in django-allauth
I'm looking to seed a user using django-allauth. On launching the dev server, a verified user should be created in the base, mimicking a correctly signed up (not signed in) user. I see that the signing up a user seems to be handled in the perform_login method in allauth.account.utils, where allauth checks this: from .models import EmailAddress has_verified_email = EmailAddress.objects.filter(user=user, verified=True).exists() To circumvent the email confirmation for the account in my seeding i use the following code: User = get_user_model() print('Creating Admin user...') admin = User.objects.create_superuser(username='admin', # nosec email='admin@foo.com', password='foobar') admin.is_active = True admin.save() # To avoid email verifiaction, we add the below line to each user EmailAddress.objects.create(user=admin, email=admin.email, verified=True) This seems hacky though, for something that must be done fairly often. Am I missing an easier way? -
get username by URL for form
my system the user logged in as USER enters the profile page of Company1 and leaves a comment. I need to save the user id and Company1's username on the same form. And this username is passed by the url as in the example below. http://127.0.0.1:8000/comments/company1/ but when saved the form, it takes the id and username of the registered user. Do not take the company urls.py url(r'^comments/(?P<username>[\w.@+-]+)/$', comments_form, name='comments_form'), profile.html link for comments <a href="{% url 'comentario_form' user_details.username %}" type="button" > Comments </a> views.py def comments_form(request, username): comments = Comments.objects.all() form = CommentsForm() data = {'comments': comments, 'form': form} return render(request, 'comments.html', data) def save_comments(request, username): if request.method == 'POST': form = CommentsForm(request.POST) form.instance.user = request.user form.instance.username = User.objects.get(pk=username) if form.is_valid(): form = form.save() return redirect('system_comments') else: form = CommentsForm() return render(request, 'comments.html', {'form': form}) -
What is the best way to apply 18% tax to all products in Django Oscar?
I want to apply 18% tax to all products on Django Oscar. What is the best and simple way to achieve this? I have followed this documentation. checkout/tax.py from decimal import Decimal as D def apply_to(submission): # Assume 7% sales tax on sales to New Jersey You could instead use an # external service like Avalara to look up the appropriates taxes. STATE_TAX_RATES = { 'NJ': D('0.07') } shipping_address = submission['shipping_address'] rate = D('0.18') for line in submission['basket'].all_lines(): line_tax = calculate_tax( line.line_price_excl_tax_incl_discounts, rate) unit_tax = (line_tax / line.quantity).quantize(D('0.01')) line.purchase_info.price.tax = unit_tax # Note, we change the submission in place - we don't need to # return anything from this function shipping_charge = submission['shipping_charge'] if shipping_charge is not None: shipping_charge.tax = calculate_tax( shipping_charge.excl_tax, rate) def calculate_tax(price, rate): tax = price * rate print(tax) return tax.quantize(D('0.01')) checkout/session.py from . import tax def build_submission(self, **kwargs): """ Return a dict of data that contains everything required for an order submission. This includes payment details (if any). This can be the right place to perform tax lookups and apply them to the basket. """ # Pop the basket if there is one, because we pass it as a positional # argument to methods below basket … -
Django: Does OneToOneField direction matter in this case?
I've just found a brilliant solution for automatically created OneToOneField. I use O2O very often and most of the times, the related model is created right after base model was created. Like User and UserProfile. class User... class UserProfile... user = OneToOneField(User,... When I need to create a userprofile for a User I either override save method or use post_signal but according to this answer, there is another solution which I like very much. class User(models.Model): userprofile = models.OneToOneField(User,default=UserProfile.get_new) class UserProfile(models.Model): @classmethod def get_new(cls): return cls.objects.create().id The only caveat is that I can't define the relation in UserProfile (which is natural since it's in fact ForeignKey). I have to define userprofile in User model. I think OneToOneField works in both ways equally, including lookup and select_related but I'm not sure. Is there a reason why not to do this? -
Django translation : assess if a string is a translation in any available language
I can't find a way to identify if a given string (say "xxxxxxxxxx") is a translation of a defined string (say "hello world"), in any available language (the languages my application is translated into). I'm inputted a string, and would like to identify if it's a translation of "hello world" in any of my available languages (PO files then). Any idea ? -
Why does django does not redirect to new url using drag-and-drop file upload?
I want to incorporate a drag-and-drop to upload files using Django and HTML. I am able to upload the file and save it to the model "Document". After that, I want to be redirected to 'user:datapreparation', which will display the dataframe in a new page. However, I am not redirected and I stay on the same page ("user:userform"). Do you perhaps know why I am not redirected to datapreparation'? Hereby the code. Thank you for your help! View: class FileUploadView(View): form_class = DocumentForm template_name = 'user/model_form_upload.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): document_name = str(request.FILES['file']) if request.FILES['file'].size < 31457280: # max 30 mbs allowed form = self.form_class(request.POST, request.FILES) document_type = str(document_name.rsplit(".", 1)[1]) valid_document_types = ["txt", "csv", "xlsx"] if document_type in valid_document_types: a = Document.objects.all()[0] a.file = request.FILES['file'] a.description = document_name a.save() return redirect('user:datapreparation') Models: class Document(models.Model): description = models.CharField(max_length=255,blank=True) file = models.FileField(upload_to='documents/') URL: from django.conf.urls import url from . import views app_name = 'user' urlpatterns = [ # upload url(r'^upload/$', views.FileUploadView.as_view(), name='userform'), # data preparation - dataframe creation url(r'^datapreparation/$', views.DataPreparation.as_view(), name='datapreparation'), ] HTML: <div id="upload"></div> <form class="dropzone" action="{% url 'user:datapreparation' %}" method="post" enctype="multipart/form-data" id="dropzone">{% csrf_token %} <div> Drop files here </div> </form> … -
How to filter based on compared values of fields in a model in django?
How to filter queryset based on comparing internal values of fields in any model? For instance, have a look at the example below: class Model1(models.Model): num1 = models.IntegerField() num2 = models.IntegerField() Say I have to filter for the Model1 values for which num2 - num1 is less than 10. So, how will we write the filter condition? That is Model1.objects.filter(???)? -
How to retrieve an object from a database in django that is associated to a user in the User model with a foreignkey
I am trying to capture the user from the User model and then use that info as a foreignkey to save data to another model. A registration form saves user info to the User model and an additional UserProfile model. This data is then used to query an API which returns a account ID number. This ID number is then to be stored in another database that is linked to the User model with a foreignkey. I have tried many possibilities but nothing works. class registeraccount(TemplateView): def get(self, request): form = ExtendedUserCreationForm() profile_form = UserProfileForm() post1 = User.objects.all() post2 = UserProfile.objects.all() return render(request, 'main/register.html', context={'form': form, 'profile_form': profile_form}) def post(self, request): if request.method == "POST": form = ExtendedUserCreationForm(request.POST) profile_form = UserProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) obj = User.objects.order_by("-id")[0] a = obj print(a.username) obj2 = UserProfile.objects.order_by("-id")[0] b = obj2 print(b.street) try: login_id = 'ap133875@gmail.com' api_key = '##############################' environment = currencycloud.Config.ENV_DEMO client = currencycloud.Client(login_id, api_key, environment) account = client.accounts.create(account_name=(a.username), legal_entity_type=(b.legal_entity_type), street=(b.street), city=(b.city), postal_code=(b.postal_code), country=(b.country)) print("Your account has been created") account = client.accounts.find() c = account d = (c[-1].id) print(d) … -
How to make a search bar in django thag filters the queryset based on what choices are been taken?
I am trying to make a search bar which would filter the queryset based on choices user selects from search bar.But I am failing to make it as I don't know how to do it. Here's the search bar template <div class="sidebar-left"> <!-- Advanced search start --> <form method="get" action="{% url 'property:search' %}"> <div class="widget advanced-search"> <h3 class="sidebar-title">Advanced Search</h3> <div class="s-border"></div> <form method="GET"> <div class="form-group"> <select class="selectpicker search-fields" name="all-status" name="q" > <option>All Status</option> <option>For Sale</option> <option>For Rent</option> </select> </div> <div class="form-group"> <select class="selectpicker search-fields" name="location" name="q" > <option>location</option> <option>California</option> <option>American Samoa</option> <option>Belgium</option> <option>Canada</option> </select> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6"> <div class="form-group"> <select class="selectpicker search-fields" name="bedrooms" name="q" > <option>Bedrooms</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </div> </div> <div class="col-lg-6 col-md-6 col-sm-6"> <div class="form-group"> <select class="selectpicker search-fields" name="bathroom" name="q" > <option>Bathroom</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </div> </div> </div> <div class="range-slider"> <label>Area</label> <div data-min="0" data-max="10000" data-min-name="min_area" data-max-name="max_area" data-unit="Sq ft" class="range-slider-ui ui-slider" aria-disabled="false" name="q" ></div> <div class="clearfix"></div> </div> <div class="range-slider"> <label>Price</label> <div data-min="0" data-max="150000" data-min-name="min_price" data-max-name="max_price" data-unit="USD" class="range-slider-ui ui-slider" aria-disabled="false" name="q" ></div> <div class="clearfix"></div> </div> <div class="form-group mb-0"> <input type="submit" class="search-button">Search</input> </div> </form> </div> <!-- Recent properties start --> <h3 class="sidebar-title">Recent Properties</h3> {% for i in most_recent %} <div class="widget recent-properties"> <div … -
why isn't my objects url showing in my view
I am a bit confused by why my url isn't showing up. I am working in django and i am having a problem with my anchor link url. my model is this (called homepage_offer.py): from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from caching.managers import CachedManager from imageuploader.fields.models import ImageUploaderField BANNER_IMAGE_PARAMS = { 'upload': 'instant', 'upload_to': 'homepage', 'ops': [ 'thumbnail:width=128,height=128,fill_box=1', 'i1024x768:width=1024,height=768,fill_box=1', 'banner:width=1200,height=250,fill_box=1', ], 'thumb': 'thumbnail', 'cropping': '1024x768,,,min', 'quality': 65, 'ui': 'imageuploader.ui.fancy', 'ui_button_label': 'Select image', 'keep_original': True, } class HomepageOffer(models.Model): """ A class for a the homepage image offer """ image = ImageUploaderField( params=BANNER_IMAGE_PARAMS, verbose_name=_('Homepage Offer Image'), null=True, blank=True, help_text=_('Image should be of size at least (1024, 768)') ) url = models.URLField( null=True, blank=True, help_text=_("Link to offer") ) objects = CachedManager() class Meta: """ Metadata """ app_label = u'homepage' verbose_name = _(u'Homepage Offer') verbose_name_plural = _(u'Homepage Offer') icon = 'fa-cart-plus' def __unicode__(self): """Unicode representation""" return u"Homepage Offers" Then in my view context['homepage_offers'] = HomepageOffer.objects.all() return context and lastly my html: <section class="home-feature-content"> <div class="rb5-hompage-content"> <h2>Our Store Offers</h2> {% for offer in homepage_offers %} <div class="rb5-hompage-content-item__inner"> <a href="{{ offer.url }}"><img src="{{ offer.image.banner }}"/></a> </div> {% endfor %} </div> </section> so in my for loop, it … -
what file structure should I use for django app on google app engine
I can't get my django app to run on google app engine. It deploys successfully but throws an error when I try connect to it in my browser. main.py throws the following error: from wsgi import application as app ModuleNotFoundError: No module named 'wsgi' I've looked at the question here: ModuleNotFoundError - No module named 'main' when attempting to start service I don't know what file structure is 'expected' for my main.py to run without errors. This is the current structure --static root file--main.py, app.yaml, etc. | voting------------ | --voting-----------settings.py, wsgi.py, etc. | other stuff my main.py currently reads (voting is the name of my project) from voting.wsgi import application as app I have tried voting.voting.wsgi and wsgi also. Please help -
How do computer vision in java-script? [on hold]
I have a in-app camera written by Html and java-script, I need to do some image processing on taken photo. I tried to do the image processing by Opencv.js (Opencv in Javascript) but I need some libraries and functions which are not yet in Opencv.js. My question is: If I do image processing on python, how can I have communication between python program and main project written in React-js, Html and Laravel ? This is what I think: I have to do it in python web framework like django in the second server and then have contact with the main server. What is your opinion? Thanks for your suggestions. -
WeasyPrint ValueError locale: UTF-8 wit Python 3 on MacOS and Ubuntu event tired to add locales
I'm working on a project using Python(3.6) and Django(2.1) in which I need to convert am HTML template into pdf using WeasyPrint and send it as the attachment with an email. Note: I have tried a lot of solutions like updating .bash_profile and many other solutions but couldn't get solved this problem, so don't mark this as duplicated, please! Also, I can provide any needed information regarding my question and Code, for that just post a comment, please! Here's what I have tried: From views.py: user_infor = ast.literal_eval(ipn_obj.custom) user_info = { "name": user_infor['name'], "hours": user_infor['hours'], "taggedArticles": user_infor['taggedArticles'], "email": user_infor['email'], "date": user_infor['date'], } html = render_to_string('users/certificate_template.html', {'user': user_info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=certificate_{}'.format(user_info['name']) + '.pdf' pdf = weasyprint.HTML(string=html, base_url='http://8d8093d5.ngrok.io/users/process/').write_pdf( stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) to_emails = [str(user_infor['email'])] subject = "Certificate from Nami Montana" email = EmailMessage(subject, body=pdf, from_email=settings.EMAIL_HOST_USER, to=to_emails) email.attach("certificate_{}".format(user_infor['name']) + '.pdf', pdf, "application/pdf") email.content_subtype = "pdf" # Main content is now text/html email.encoding = 'us-ascii' email.send() But it returns this error: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 495, in _parse_localename raise ValueError('unknown locale: %s' % localename) ValueError: unknown locale: UTF-8 And it points out to the line where I have imported the weasyprint as: import weasyprint -
Is there any way to run python script in a web page or within the frame of web page?
I have built a chatbot using python and MySQL. Now i want to run/integrate it on a webpage. I have no idea how to do it. can someone help me with this. -
Django serializer output as part of JSON object
Context I have 2 models: Customer & DeviceGroup. Currently I have an API endpoint /api/v1/device-groups/?customer_uuid=<customer_uuid> which returns the DeviceGroups that are related to the given Customer like this: [ { "group_uuid": "c61361ac-0826-41bb-825a-8aa8e014ae0c", "device_group_name": "Default", "color": "0a2f45", "is_default": true }, { "group_uuid": "1a86e8e4-b41b-4f33-aefb-ce984ef96144", "device_group_name": "Testgroup", "color": "123456", "is_default": false } ] Goal I want the array of DeviceGroups be part of an object like this: "device_groups": [ { "group_uuid": "c61361ac-0826-41bb-825a-8aa8e014ae0c", "device_group_name": "Default", "color": "0a2f45", "is_default": true }, { "group_uuid": "1a86e8e4-b41b-4f33-aefb-ce984ef96144", "device_group_name": "Testgroup", "color": "123456", "is_default": false } ] Models # models.py class Customer(models.Model): customer_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_name = models.CharField(max_length=128, unique=True) class DeviceGroup(models.Model): group_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_uuid = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) device_group_name = models.CharField(max_length=20) color = models.CharField(max_length=10) is_default = models.BooleanField(default=False) Serializer # serializers.py class DeviceGroupSerializer(serializers.ModelSerializer): class Meta: model = DeviceGroup fields = ('group_uuid', 'device_group_name', 'color', 'is_default') View # views.py class DeviceGroupCustomerViewSet(viewsets.ModelViewSet): serializer_class = DeviceGroupSerializer def get_queryset(self): return DeviceGroup.objects.filter(customer_uuid=self.request.GET['customer_uuid']) I tried creating a new serializer but it did not solve my problem: class TestSerializer(serializers.ModelSerializer): device_groups = DeviceGroupSerializer(many=True, read_only=True) class Meta: model = DeviceGroup fields = ('device_groups', 'group_uuid', 'device_group_name', 'color', 'is_default') What do I need to change in order to get my desired output? -
how to filter data with ajax in django?
here i am trying to filter dishes based upon the menu category.and i want to display dishes of that selected category within this page without loading the whole page.i tried like this but this is not working at all .This is working only in 'All' option.In 'All' option all the active foods are displaying,that is fine but in in other option it is displaying nothing.HOw can i get selected category dishes within this page without loading the page.I have very very little knowledge with ajax and jquery so i get unable.can anyone help me to edit this my question.It would be a great help. models.py class MenuCategory(models.Model): title = models.CharField(max_length=250) slug = AutoSlugField(populate_from='title') date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Menu Category' class Food(models.Model): name = models.CharField(max_length=250) price = models.CharField(max_length=100) detail = models.TextField(blank=True) category = models.ForeignKey(MenuCategory,on_delete=models.DO_NOTHING) image = models.ImageField(upload_to='Foods',blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Foods' views.py def homepage(request): menu_categories = MenuCategory.objects.filter(active=True) foods = Food.objects.filter(active=True) return render(request,'cafe/base.html',{ 'menu_categories':menu_categories, 'foods':foods,} def category_dishes(request): category = MenuCategory.objects.get(id=request.GET.get('category_id')) return render(request, 'cafe/category_dishes.html', {'category':category}) urls.py path('',views.homepage), path('ajax/load-category-dishes/', views.category_dishes), category_dishes.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> … -
How to access to some data before saving my django form?
I'm building a tournament manager currently and I block on a step of my program because I don't have enough experience in Django. So, basically I have a view that manage the add team system to a tournament. I have a model "Tournament" which contains a field that indicates the number of teams that I can have in a Category ("Category" is an other field). Between Category and Tournament there is a Many-to-One relationship. I also have a model "Team" and there is a Many-to-One relationship between Team and Category. So my question is how can I check if I can add or not the team in a category depending on the field in "Tournament" ? I specify that there can be the same category in two different tournaments. views.py def team_view(request, id, *args, **kwargs): tournaments = Tournament.objects.filter(user=request.user) tournament = Tournament.objects.get(pk=id) form_team = TeamCreationForm(request.POST or None) form_team.fields['category'].queryset = Category.objects.filter(tournament=tournament) if form_team.is_valid(): form_team.save() form_team = TeamCreationForm() form_team.fields['category'].queryset = Category.objects.filter(tournament=tournament) context = { 'tournaments': tournaments, 'tournament': tournament, 'form_team': form_team, } return render(request, "tournament_manage_team.html", context) forms.py class MyModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.description class TeamCreationForm(forms.ModelForm): name = forms.CharField(label='Name', widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the name of the team'})) category = MyModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={ 'class':'form-control'})) class … -
Django Queryset for mysql replace
Is there any queryset equivalent in django for the following query. UPDATE table SET field = REPLACE(field, 'string', 'anothervalue') WHERE field LIKE '%string%'; -
django filter horizontal without ordering
In a django model containing a many-to-many field and displayed in admin with a filter horizontal, Is it possible to disable the default ordering so that picked entries in the filter are not reordered alphabetically? In that case, It would be to alter the order of the selected entries in the filter horizontal only by the order they have been picked. -
Why is not datepicker shown?
[enter image description here][1][enter image description here][2]I am developing an application with Django and I need to choose date and time. I am trying to do it with 'bootstrap_datepicker_plus', but the calendar does not appear when I show the form. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hungryFalconryApp', 'rest_framework', 'bootstrap4', 'bootstrap_datepicker_plus', ] BOOTSTRAP4 = { 'include_jquery': True, } forms.py from django import forms from bootstrap_datepicker_plus import DateTimePickerInput class DateForm(forms.ModelForm): class Meta: model = Comedero fields = ('dias', 'horas') widgets = { 'dias': DateTimePickerInput(), 'horas': DateTimePickerInput(), } views.py def programar_comederos(request, nombre): if request.method == "POST": form = DateForm(request.POST) print(nombre) if(form.is_valid()): comedero = form.save(commit=False) print(comedero.dias) print(comedero.horas) else: form = DateForm() return render(request, 'hungryFalconryApp/programar_comederos.html',{'nombre': nombre, 'form':form}) template.html {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% bootstrap_messages %} {{ form.media }} {% block content %} <form action="" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% bootstrap_button "Guardar" button_type="submit" button_class="btn-primary" %} </form> {% endblock %} -
Python Django: button assign variable from array in for loop per line per click
Is it possible in Python/Django to assign variable from array line each time I click on submit button and display result in same page? Using a counter or other idea... For example: array=[1,2,3,4,5] var = 0 for i in array: if button is clicked: var = array[i] endif endfor And each time I click on the button, the var value is incremented: First time I click var = 1 Next click I click var = 2 ... Thank you for your help !