Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add meta properties each page in django?
Need help How to add meta properties each pages in django ? I have base.html but i need each pages meta tags -
How much money do I need to deploy my project using Django?
This is my first time that I will deploy my project. I have no idea how much money do I need. Also can you guys give me a tip on where I can deploy a website for free with having own domain name? -
How to display data in a drop down corresponding to the data from another dropdown in html page?
I am trying to create a web page using Python DJANGO, in which I have two dropdowns out of which one is for category and another for subcategory, for which data is getting fetched from database. In DB, there are two columns for category and another for subcategory respectively. For example, there are 2 Categories, i.e boys and girls. and for boys there are 3 names under SubCategory column, similarly for girls. So my want is that, in drop down 1, it should show 'boys' and 'girls'. When user chooses any of them, the corresponding names should appear in the second drop down(i.e only boys names should appear in dropdown 2 when "boys" is selected in dropdown1). But the way I have written, its showing all the data irrespective of the selection in dropdown1. Please suggest, how do I make the subcategory data appear categorically? Please find the below sample code, that i have written. View.py: def createTicketView(request): if request.method == 'POST': taskName=request.POST.get('title') taskDescription=request.POST.get('description') Category=request.POST.get('category') SubCategory=request.POST.get('type') user_id=request.user.id task=UserTaskDetails.objects.create(user_id=user_id, taskName=taskName,taskDescription=taskDescription, Category=Category,SubCategory=SubCategory) task.save() return redirect('home') category =ServiceCategoryDetails.objects.values('category').distinct() subcategory=ServiceCategoryDetails.objects.values('SubCategory').distinct() return render(request,'custws/ticket.html',{'title':'create ticket', 'category':category, 'subcategory':subcategory, '}) Html code: <div class="form-group col-md-6"> <label for="category" class="font-weight-bold">Category</label> <select name="category" id="category" class="form-control"> {% for type in category %} … -
django-rest-auth urls not found
I'm trying to implement django-rest-auth, but the url is not recognized and throw 404 error. The 'rest_auth' is added in the INSTALLED_APPS and path also included in the urls.py file. Request URL: http://127.0.0.1:8000/api/v1/rest-auth/login/ Using the URLconf defined in blog_project.urls, Django tried these URL patterns, in this order: admin/ api/v1/ <int:pk>/ api/v1/ api-auth/ api/v1/rest-auth ^password/reset/$ [name='rest_password_reset'] api/v1/rest-auth ^password/reset/confirm/$ [name='rest_password_reset_confirm'] api/v1/rest-auth ^login/$ [name='rest_login'] api/v1/rest-auth ^logout/$ [name='rest_logout'] api/v1/rest-auth ^user/$ [name='rest_user_details'] api/v1/rest-auth ^password/change/$ [name='rest_password_change'] The current path, api/v1/rest-auth/login/, didn't match any of these. settings.py content INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'rest_auth', # Apps 'posts.apps.PostsConfig', ] Below is the content of my urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('posts.urls')), path('api-auth/', include('rest_framework.urls')), path('api/v1/rest-auth', include('rest_auth.urls')), ] I'm not able to figure out, what is wrong with the code. -
Is it possible to pass variables to CSS file in Django
I was wondering is it possible to pass a variable from a Django view to CSS file? Is there any way? I was following some tutorials in a front end design and wondered if it can be built dynamically in Django? .card:nth-child(1) svg circle:nth-child(2){ stroke-dashoffset: calc(440 - (440 * 90) / 100); stroke: #00ff43; } .card:nth-child(2) svg circle:nth-child(2){ stroke-dashoffset: calc(440 - (440 * 80) / 100); stroke: #00a1ff; } .card:nth-child(3) svg circle:nth-child(2){ stroke-dashoffset: calc(440 - (440 * 60) / 100); stroke: #ff04f7; } stroke-dashoffset: calc(440 - (440 * {{ var }}) / 100); can i pass those variables from a view to this var in CSS? this portion of code gives 90, 80 and 60% respectively. -
How to retrieve all the comments for a post using related names?
I am trying to create a comment page for a blog-style site that will list all of the previous comments for a single related post. I am having trouble figuring out how to structure the view to get what I'm looking for. I have been trying to use related names to get the data but am not sure if that is the right method. Here are my models: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=128) content = models.TextField() image = models.ImageField(upload_to='post_pics', blank=True) date_posted = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('home') class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() date_created = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('home') And here is my view: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'home/comment-form.html' fields = ['comment',] def get_context_data(self, **kwargs): context = super(CommentCreateView, self).get_context_data(**kwargs) context['post'] = Post.objects.get(pk=self.kwargs['pk']) comments = Post.comments.all() context['comments'] = comments return context def form_valid(self, form): form.instance.user = self.request.user form.instance.post = Post.objects.get(pk=self.kwargs['pk']) return super().form_valid(form) I have been trying a bunch of different things. The above is just my latest attempt. When I try to run this one I get a 'ReverseManyToOneDescriptor' object has no attribute 'all' error. I don't know if I need to run … -
Getting Base model instance from proxy model
Using proxy model like below. How can I get base model_name from proxy model instance. class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class MyPerson(Person): class Meta: proxy = True -
Passing Foreign Key Through Django Session
I am really stuck on a scenario where I am looking to pass some data through the session in django from one view to another. I am looking to pass data from a dynamic formset (i.e. it may have one form, two forms, or more - no way of knowing). In that one field - ProductCode - is a foreign key so is not json serializable. I will post my code below: models.py class QuoteManifest(models.Model): quote = models.ForeignKey(Quote, null=True, on_delete=models.CASCADE) ProductCode = models.ForeignKey(Product, null=True) DescriptionOfGoods = models.CharField(max_length=500, blank=True) UnitQty = models.CharField(max_length=10, blank=True) Type = models.CharField(max_length=50, blank=True) Amount = models.CharField(max_length=100, blank=True) Price = models.CharField(max_length=100, blank=True) class Product(models.Model): ProductCode = models.CharField(max_length=100) HSCode = models.CharField(max_length=50, null=True) DescriptionOfGoods = models.CharField(max_length=100) Price = models.CharField(max_length=100) UnitType = models.CharField(max_length=100) def __str__(self): return str(self.ProductCode) views.py def QuoteView(request): QuoteManifestForm= modelformset_factory(QuoteManifest, QManifestForm, can_delete = True) if request.method == "POST": form2 = QuoteManifestForm(request.POST) if form.is_valid(): manifestData = form2.cleaned_data product = manifestData.pop('ProductCode') #this is where I get error request.session['manifestData'] = manifestData return redirect('QuotePreview') class QuotePreview(View): def get(self, request, *args, **kwargs): manifestData = request.session.pop('manifestData', {}) context = { 'manifestData': manifestData, } pdf = render_to_pdf('quote_preview.html', context) return HttpResponse(pdf, content_type='application/pdf') forms.py class QManifestForm(forms.ModelForm): class Meta: model = QuoteManifest fields =('ProductCode', 'DescriptionOfGoods', 'UnitQty', 'Type','Amount', 'Price') When … -
Elastic Beanstalk - AWS
I've researched and couldn't find the solution. click here for see ERRO -
Django Uploaded images not displayed in production
I am aware of this question: Django Uploaded images not displayed in development , I have done everything that it is described, but still can't find a solution. I also have used for reference this: GeeksForGeeks and Django official documentation, however, none of them solved my problem. I have deployed a Django App on a Ubuntu server for the first time using Nginx and gunicorn. Before deployment, I used port 8000 to test if everything runs as it is supposed to and all was fine. Since I allowed 'Nginx Full' my database images are not showing up. This is my django project structure: My virtual environment folder and my main project folder are both in the same directory. I have separated them. # Create your models here. class Project(models.Model): project_name = models.CharField(max_length=120) project_description = models.CharField(max_length=400) project_link = models.CharField(max_length=500) project_image = models.ImageField(upload_to='') def __str__(self): return self.project_name I have set up my settings.py to : # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media' MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', 'media').replace('\\','/') My view gets all the project object from a database and passes those to the template. In my template … -
Is there a way to call a post from another view in Django?
I want to process the POST in Processing view when I type next/ URL directly on the browser bar, any clue? I'm including the repository just in case: https://github.com/ivanperezdesigner/Hypercar thank's for your help views.py file class Processing(View): def get(self, request, *args, **kwargs): context = {'service_line': service_line} return render(request, 'tickets/processing.html', context) def post(self, request, *args, **kwargs): if len(service_line['change_oil']) > 0: service_line['change_oil'].pop(0) elif len(service_line['inflate_tires']) > 0: service_line['inflate_tires'].pop(0) elif len(service_line['diagnostic']) > 0: service_line['diagnostic'].pop(0) return redirect('/next') class Next(View): def get(self, request, *args, **kwargs): x = 0 if len(service_line['change_oil']) > 0: x = service_line['change_oil'][0] elif len(service_line['inflate_tires']) > 0: x = service_line['inflate_tires'][0] elif len(service_line['diagnostic']) > 0: x = service_line['diagnostic'][0] context = {'next': x} return render(request, 'tickets/next.html', context) urls.py file from django.urls import path from tickets.views import WelcomeView, MenuView, Service, Processing, Next from django.views.generic import RedirectView urlpatterns = [ path('welcome/', WelcomeView.as_view()), path('menu/', MenuView.as_view()), path('get_ticket/<str:service>', Service.as_view()), path('processing/', Processing.as_view()), path('next/', Next.as_view()), ] -
why django crispy_forms is failing on ubuntu on my aws ec2 instance
I have created a AWS ec2 instance using python 3.6 django2.2 gunicorn nginx supervisor but now that i have pulled the latest changes from github where i added two dependencies: Pillow crispy_form to install them on ubuntu i did: sudo apt-get install python-pil sudo apt-get install python-django-crispy-forms but now after restarting supervisor and nginx I get a 502 Bad Gateway nginx/1.14.0 (Ubuntu) on the web app page. by checking the log of /var/log/gunicorn/gunicorn.err.log with nano: this is what i found. ModuleNotFoundError: No module named 'crispy_forms' [2020-06-21 00:48:19 +0000] [10606] [INFO] Worker exiting (pid: 10606) Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 209, in run self.sleep() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 357, in sleep ready = select.select([self.PIPE[0]], [], [], 1.0) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/env/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 229, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt self.stop() … -
Model data not displayed on template - django
Short Story: I have made two apps. Properties and Tenants within a django project. First I started rendering data from Property model to property_detail.html template and it works fine, but after I created & migrated the Tenants model, and I try to render data from there to property_detail.html it doesn't work. Yet it doesn't give me any errors. It just doesn't show up. Models.py import arrow import uuid from django.db import models from django_countries.fields import CountryField from django.urls import reverse from django.conf import settings from properties.models import Property class Tenant(models.Model): id = models.UUIDField( # new primary_key=True, default=uuid.uuid4, editable=False) full_name = models.CharField("Full Name", max_length=255, null=True) email = models.EmailField(unique=True, null=True) phone = models.CharField(max_length=20, unique=True, null=True) description = models.TextField("Description", blank=True) country_of_origin = CountryField("Country of Origin", blank=True) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) created_on = models.DateTimeField( "Created on", auto_now_add=True, null=True) is_active = models.BooleanField(default=False) apartment = models.ForeignKey( Property, on_delete=models.CASCADE, related_name='reviews', ) rent_tenant = models.CharField( "Rent he/she pays", max_length=10, blank=True) def __str__(self): return self.full_name def get_absolute_url(self): """"Return absolute URL to the Contact Detail page.""" return reverse('tenant_detail', kwargs={'pk': str(self.pk)}) urls.py from django.urls import path from .views import TenantListView, TenantDetailView urlpatterns = [ path('', TenantListView.as_view(), name='tenant_list'), path('<uuid:pk>', TenantDetailView.as_view(), name='tenant_detail'), # new ] views.py from django.views.generic import ListView, DetailView … -
what payment gateway should i use in django
hi i am new to django maybe few months ago,but successfully created a website but it needed a payment Gateway now i want to ask is their any *third party used for payment in django built in django-payment gateway or how do i go about the payment method* i have tried using Stripe but its does not work for my country because its not in the list of countries its working with Note= if their is any tutorial i can follow with any recommended payment gateway, kindly provide -
Django notify when model changes
I have a big legacy Django1.11 project and I want to make some changes on a table. I needed to be notified (notification is not a big deal here and suppose i just want to print "hello world" in case of happening) when every change on this table happens (every insert or or update in rows) and I can not be sure I can find all of this changes in code because it is so big. I searched and I figured out if I override save method in Model I will be notified in some cases and still i will be missing some changes in rows. For example when Model.objects.filter().update() I will be missing changes. I wanted to know Is there a way that I can be sure that I will catch every happens in rows of Model table? -
How to send a variable from Django template to view
I am trying to send a number from the template page (.html) to views.py. For this, I did the following things: urls.py path('video/<int:value>', views.process_number, name='video_lab'), .html <div class="frame"> <span id="currentFrame">0</span> </div> <div class="btn-group" > <button id="stop_bttn_id" class="btn btn-primary btn-lg" name="stop_bttn">Take Number</button> </div> <script type="text/javascript"> function btn_click() { var x = document.getElementById('currentFrame').textContent fetch("{% url 'video_lab' value=x %}", { method: "POST", headers: { "X-CSRFToken": '{{csrf_token}}'}, body: 'true' }).then(response => { return response.json() }) } document.getElementById('stop_bttn_id').addEventListener('click', btn_click); </script> views.py @login_required def process_number(request, value: int): json_response = {....} return JsonResponse(json_response) Here is the problem. If I directly send a number instead of variable, then the number can be sent to the views.py. fetch("{% url 'video_lab' 5 %}" However, if I try to send a variable, I get an error: NoReverseMatch at /video/ Reverse for 'video_lab' with keyword arguments '{'value': ''}' not found. 1 pattern(s) tried: ['video/(?P[^/]+)$'] I also tried: fetch("{% url 'video_lab' x %}" Although I did lots of research, I could not find any solution. Could anyone help me about it? Best. -
Saving lists to models in Django
I'm building a tracker where users save their response to the same question every day. Is there a way to track individual responses as a list through models.py? I don't see a model field for lists, so I'm saving the list of responses through views.py at the moment. mylist = [] global length @login_required def add(request): respond = Response.objects.all() if request.method == 'POST': selected_option = (request.POST['rating']) length = len(mylist) if selected_option == 'option1': mylist.append(1) print(respond.score) elif selected_option == 'option2': mylist.append(2) print(respond.score) elif selected_option == 'option3': mylist.append(3) print(respond.score) elif selected_option == 'option4': mylist.append(4) print(respond.score) elif selected_option == 'option5': mylist.append(5) print(respond.score) else: return HttpResponse(400, 'Invalid form') for votes in respond: votes.save() return redirect(add) context = { 'respond' : respond, 'mylist' : mylist } return render(request, 'rating/add.html', context) def graph(request): x_data = list(range(0,len(mylist))) y_data = list(mylist) return render(request, "rating/home.html", context={'plot_div': plot_div, 'mylist' : mylist}) This accomplishes my need to save responses to a list so that I can send them over to a plot. The issue is that it doesn't save as part of the model and as such is not linked directly to any specific user (all user results are grouped together). I'm using this for my models file right now but … -
Create Pre-Populated Database Models
I have an online learning website with modules students can enroll in. Each module contains a set of 5 classes. To do this I intend to: On enrollment, an empty one-to-many 'learning module' instance is created and attached to the student (a student can have many modules, but a module instance can only have one student). Superusers can assign modules to students (preferably in Django's Admin and by going to Student). On doing this, the module's classes are copied into the students 'learning module' db instance at the click of a button? Students can view their modules. If the student has multiple modules, modules will be separated with a space My question is how can I create these modules class lists and store them, ready to be copied into a students 'learning module' database instance? Basically I need to store pre-filled database fields which can be copied to a database instance at the click of a button. I know of data fixtures, but this seems more for initially populating a database and is done with shell. My next problem will be finding out how to allow superusers to assign these modules to Students within Django Admin. Thank you. -
Linking a HTML button to run a python script in django
I want to run my python file when a html button is pressed. I have my python file working when i press run in PyCharm (it just creates a graph). My python file is stored as main.py. I am having trouble linking the html button to run the main.py file when the button is pressed. At the moment I think i have the button pointing to a function in my views.py which in turn runs my main.py file. (or so i think. it is not working) INDEX.HTML <input type="button" value="Run graph" onclick="run_graph()"> URLS.PY from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('run_graph', views.run_graph), ] VIEWS.PY def run_graph(main): return main MAIN.PY import matplotlib.pyplot as plt import numpy as np col_count = 3 bar_width = .1 korea_scores = (554, 536, 538) canada_scores = (518, 523, 525) china_scores = (613, 570, 580) france_scores = (495, 505, 499) index = np.arange(col_count) k1 = plt.bar(index, korea_scores, bar_width, alpha=.4, label="Korea") c1 = plt.bar(index + bar_width, canada_scores, bar_width, alpha=.4, label="Canada") ch1 = plt.bar(index + 0.2, china_scores, bar_width, alpha=.4, label="China") f1 = plt.bar(index + 0.3, france_scores, bar_width, alpha=.4, label="france") plt.ylabel("mean score in PISA 2012") plt.xlabel("Subjects") plt.title("France") plt.xticks(index + .3 / 2, ('Maths', … -
Django RF - login/logut API views problem
I have a problem with logging in / logging out using the API. I created two views: class SignIn(APIView): def post(self, request): user = authenticate( request, username=request.data['username'], password=request.data['password'] ) if user is not None: login(request, user) return Response( {'username': request.user.username, 'logged': True}, status=status.HTTP_202_ACCEPTED ) else: if User.objects.filter(username=request.data['username']).exists(): return Response( {'init_data_problem': 'wrong_password', 'logged': False}, status=status.HTTP_409_CONFLICT ) else: return Response( {'init_data_problem': 'user_not_exists', 'logged': False}, status=status.HTTP_404_NOT_FOUND ) class SignOut(APIView): def get(self, request): if request.user.is_authenticated: logout(request) return Response( {'logged_out': True}, status=status.HTTP_200_OK ) else: return Response( {'logged_out': False}, status=status.HTTP_400_BAD_REQUEST ) Login seems to be working correctly: http POST http://127.0.0.1:8000/signin username="MyUser" password="mypassword" Response: { "logged": true, "username": "MyUser" } But using logout immediately afterwards gives the response: http http://127.0.0.1:8000/signout Response: { "logged_out": false } Why do I get a positive response about logging in, but the user is not "permanently" logged in? What am I doing wrong? -
Problem in calling items from the database django
I am trying to create a music streaming website.I have created a base template and extended it to two other templates.One is song_list.html and musicplayer.html. I have coded the views and urls to get absolute url. my song_list.html: {% extends "home.html" %} {% block content %} <div class="container"> {% for post in posts %} <a href="{{ post.get_absolute_url }}">{{post.song_title}} by {{post.artist}} from {{post.album}}</a><br> {% endfor %} </div> <div class="container"> {% include "pagination.html" with page=page_obj %} </div> {% endblock %} I want to render songs from the database in the musicplayer page after clicking the anchor tag. my msicplayer.html: {% extends "home.html" %} {% load i18n %} {% block content %} <div class="container"> <form class="" action="mediaplayer.html" method="get"> <div class="data-content"> <div class="container"> <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-sm"> <div class="card" style="width: 18rem;"> <div class="img"> <img class="img-thumbnail" src="{{ post.img.url }}" alt=""> </div> <div class="card-body"> <div class="title"> <p>{% trans 'Artist:' %} {{post.artist}} </p><br> <p>{% trans 'Title:' %} {{post.song_title}}</p><br> <p>{% trans 'Album:' %} {{post.album}}</p><br> <p>{% trans 'Duration' %} {{post.song_duration}}</p><br> </div> <audio controls> <source src='{{ post.song.url }}' type="audio/mpeg"> Your browser does not support the audio element. </audio> </div> </div> </div> </div> </div> </div> </div> </div> {% endblock %} My app views: from django.shortcuts import … -
how do i manually authenticate and log in a user in django?
if request.method=='POST': try: email=request.POST['email'] password = request.POST['password'] if StudentUser.objects.filter(email=email).exists(): user = StudentUser.objects.get(email=email) if user.check_password(password): user = auth.authenticate(email=email) if user is not None: auth.login(request,user) messages.success(request,'Successfully Loggedin') return redirect('/') else: messages.warning(request,'Password does not match') return redirect('login') else: messages.error(request,'No Account registered with this mail') return redirect('login') except Exception as problem: messages.error(request,problem) return redirect('login') return render(request,'login.html') This above code i am trying to authenticate the user manually, but it is not working. i want to authenticate a user by manually checking the password. How can i do it? ** when I am passing the password in auth.authenticate function it is showing password does not match error -
Django dynamic show images from folders
I'm new in Django and I want to build a site that dynamically shows images from a folder that is not located in the project directory, these images are create each 10 minutes. I don't know if this is possible to do with Django or if there is another way of doing this. the structure of the folder is like this: Folder_img/month/day/images.tif -
How to perform some tasks with an incoming request before saving it or responding with django rest framework?
I'm quite new to django, i'm trying to migrate and old API built in express to Django Rest Framework, brief story: The API is meant to receive different kind of payplods from different device, in example { "device": "device001", "deviceType": "temperature_device", "deviceTs": timestamp, "payload": { "airTemp": X, "airHum": Y, } } the payload wouldn't be always the same, so other devices (different type) will bring different key - value pairs in the "payload" field. I'm using Django Rest Framework, alongside model serializers and and GenericViewSet, but the problem is that before storing the data to the DB and returning the HTTP Response, I need to perform a data validation (minimum, and maximum values) and in some cases, the device sends some "corrupted" data (In example: Negatives number comes with the following syntax: 1.-5 instead of -1.5), I need to fix these values and so on, finally, I need to perform two HTTP request to an external API with the fixed payload and and API Key (that should be stored in the device details model in my database) so, in short how can I perform any kind of -previous work- to a request BEFORE storing the data into the DB and … -
How get request in bootstrap-modal-forms in django?
I have problem with bootstrap-modal-forms for django. I installed packed with instructions from https://github.com/trco/django-bootstrap-modal-forms. It's work but I don't know how to get to options form in views.py. I must set client_id for form like initial in normal functions (form_add = IncomeForm(client_id=client_id, data=request.POST). How to use request in class BookCreateView? Any idea? models.py class BankAccount(models.Model): name = models.CharField(max_length=128) client_id = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True) start_value = models.DecimalField(decimal_places=2, max_digits=10, default=0) forms.py from bootstrap_modal_forms.forms import BSModalForm class BankAccountForm3(BSModalForm): class Meta: model = BankAccount fields = ['name', 'start_value', 'client_id'] views.py from bootstrap_modal_forms.generic import (BSModalCreateView) class BookCreateView(BSModalCreateView): template_name = '1.html' form_class = BankAccountForm3 success_message = 'Success: Book was created.' success_url = reverse_lazy('website:ustawienia') Here is modal form: https://finaen.pl/test