Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Turning on a webapp's functionality using a button in another webapp
I have two different web apps (designed using Django) which are deployed on different servers and running independently. I am searching for the following pointers: Imagine there is a functionality X in webapp1 and a button1 in webapp2. When button1 is pressed (webapp2), the X1 functionality(webapp1) must be activated. -
How to use django rest api to do inference?
I was trying to build a website with Django rest API as the backend. when given a string Its gives the score from 1 to 10 for negativity. The frontend part of the website was built using next.js. Previously I have made the same app without Django rest API by doing all inference in the views.py file. Now I am using Rest API I am confused about where should I need to include the machine learning inference code. I have seen tutorials on the internet showing that inference code is attached in the models.py file. Previously when I included inference code in views.py the page used to get reload whenever I do the inference. I want to avoid it. What is the best practice to include inference code while using Django rest API. -
¿How to add multiple forms inherited from another form with Django?
I have a question, what happens is that when I click the plus sign (+), the fields are repeated to put more data. I did some research and saw that I can use a formset, I only have a problem placing the code for the views. Since I'm inheriting from Parte/forms.py to Presupuestos/forms.py and I don't know if in Parte/views.py or Presupuestos/views.py to do the modification for the formset or how to adjust it to what I already have in my views Parte/model.py class Parte(models.Model): codigo=models.IntegerField() quantity=models.IntegerField() unit_price=models.IntegerField() total_price=models.IntegerField() tax_free=models.BooleanField() descripcion=models.TextField(max_length=255,blank=True, null=True) descuento=models.IntegerField(default=0) total=models.IntegerField() def __str__(self): return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_price} {self.tax_free}{self.descuento}{self.total}' Parte/forms.py from django import forms from django.forms import formset_factory from .models import Parte class ParteForm(forms.ModelForm): class Meta: model=Parte fields=['codigo','descripcion','quantity','unit_price','total_price','tax_free'] ParteFormset = formset_factory(ParteForm, extra=0) Presupuestos/forms.py class PresupuestosParteForm(forms.ModelForm): class Meta: model = Parte fields = '__all__' widgets = { 'codigo': forms.TextInput( attrs={ 'class': 'form-control' } ), 'quantity': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'unit_price': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'multiplicar()', } ), 'total_price': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'tax_free': forms.CheckboxInput( attrs={ 'class': 'form-check-input', 'onclick': 'taxes_free(multiplicar())', } ), 'descripcion': forms.TextInput( attrs={ 'class': 'form-control' } ), 'descuento': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'totales()', } ), 'total': forms.NumberInput( attrs={ 'class': 'form-control', … -
discount amount after posting a sale - Django
I am making an app that consists of a sales system. I want that when registering a sale, the quantity sold is discounted to the product. I leave the sales and product models, also the createview: class Product(LlegadaModel): """Product model.""" nombre = models.CharField(max_length=100) precio = models.FloatField() cantidad = models.FloatField() ... class Venta(LlegadaModel): """Venta model.""" fecha = models.DateTimeField(default=timezone.now, help_text='Ejemplo: 09/11/2021 17:20:00') cliente = models.ForeignKey(Cliente, on_delete=models.SET_NULL, null=True) producto = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) cantidad = models.FloatField() forma_pago = models.CharField(help_text='Contado - QR - Tarjeta', max_length=8) create view class CreateVentasView(CreateView): """Create sales.""" template_name = 'ventas/create.html' form_class = VentasForm success_url = reverse_lazy('ventas:list') context_object_name = 'venta' -
Conver python to html using Django
Hi I have a python program for customers to query price. Each time a customer can input some necessary information, the program will calculate and return the price to customer. Note: during hte calculation process, the program also need to query a third party map service web API to get some information (such as google map API or other similiar service) I have a website developed using web development tools such Wix, Strikingly. It offers a capability to customize a web page by simply input a block of HTML codes. So, I want to study the possibility of using Django to convent my python program into HTML (incl. add some user interface such as text box and button), which can then be pasted into the website to form a unique webpage. I am not sure if it is doable? Especailly, the part of connecting third party map service API. Would Django be able to convert this part automatically to HTML as well? (how does it deal with API key and connection). -
How to load csv file into django postgres database?
I'm using django to load a csv file into data base,here is the code to read the file: import csv with open(r'/Users/williaml/Downloads/events.csv') as csvfile: spamreader = csv.reader(csvfile, delimiter=',' ,quotechar=' ') count=0 for row in spamreader: print(row) Output: ['"PATIENT ID', 'PATIENT NAME', 'EVENT TYPE', 'EVENT VALUE', 'EVENT UNIT', 'EVENT TIME"'] ['"1', 'Jane', 'HR', '82', 'beats/minute', '2021-07-07T02:27:00Z"'] ['"1', 'Jane', 'RR', '5', 'breaths/minute', '2021-07-07T02:27:00Z"'] ['"2', 'John', 'HR', '83', 'beats/minute', '2021-07-07T02:27:00Z"'] ['"2', 'John', 'RR', '14', 'breaths/minute', '2021-07-07T02:27:00Z"'] ['"1', 'Jane', 'HR', '88', 'beats/minute', '2021-07-07T02:28:00Z"'] ['"1', 'Jane', 'RR', '20', 'breaths/minute', '2021-07-07T02:28:00Z"'] ['"2', 'John', 'HR', '115', 'beats/minute', '2021-07-07T02:28:00Z"'] ['"2', 'John', 'RR', '5', 'breaths/minute', '2021-07-07T02:28:00Z"'] ['"1', 'Jane', 'HR', '66', 'beats/minute', '2021-07-07T02:29:00Z"'] ['"1', 'Jane', 'RR', '15', 'breaths/minute', '2021-07-07T02:29:00Z"'] ['"2', 'John', 'HR', '107', 'beats/minute', '2021-07-07T02:29:00Z"'] ['"2', 'John', 'RR', '17', 'breaths/minute', '2021-07-07T02:29:00Z"'] My first question is,how to convert the patient id into integer and how to convert the event value into integer,they are string now,but in data base they should be integer. The second question is how to use sql to insert the row into database: try: conn = connect( dbname = "python_test", user = "WRONG_USER", host = "localhost", password = "mypass" ) except OperationalError as err: # pass exception to function print_psycopg2_exception(err) # set the connection to 'None' in case … -
I want to bring data from models to views and filter out the data i need for html output
[enter image description here][1] error information [enter image description here][2] views.py this is the class that caused the error [enter image description here][3] search_list.html I want to bring data from models.py to views.py and filter out the specific data I want to bring to the search_list.html file. please help asap. [1]: https://i.stack.imgur.com/j08hl.png [2]: https://i.stack.imgur.com/Qcgze.png [3]: https://i.stack.imgur.com/kGVMU.png -
Why is my bootstrap not working in Django
I really don't know why my bootstrap isn't working in Django and its really frustrating me. Bootstrap5 is downloaded in my virtual environment Bootstrap5 is also installed apps file in settings.py This is my index.html that only displays the html not the bootstrap or static files {% load socialaccount %} <html> <head> <title>Google Registration</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <!-- Bootstrap --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <div style="width: 100%" class="shadow p-2 mb-3 bg-body rounded text-white"> <h1 class="font-monospace text-center">Housing for UVA Students by B-07!</h1> </div> {% if user.is_authenticated %} <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand">Explore!</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'housing:studentHousingList' %}">Browse Listings</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'housing:logout' %}">Logout</a> </li> </ul> </div> </nav> <div class="mx-auto" style="width: 400px;"> <p class="text-success">Welcome, {{ user.username }}! Your email is {{ user.email }}</p> </div> {% else %} <div class="mx-auto" style="width: 200px;"> <h2>Please Login!</h2> <a href="{% provider_login_url 'google' %}">Login with Google</a> </div> {% endif %} </body> </html>iv> {% endif %} </body> </html> This is my urls.py under one of my … -
Django template won't render photos
I am trying to render photos from my static file, but it does not work. The path is found, but the photos will not render. Here is part of my code: models.py class Book(models.Model): title = models.CharField(max_length=200) adultcontent = models.BooleanField(default=False) book_photo = models.ImageField(null=True, blank=True) def __str__(self): return self.title views.py def bookIndex(request): books = Book.objects.all() form = BookForm() if request.method =='POST': form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/books') context = {'books': books, 'form':form} return render(request, '../templates/list.html', context) template: (if i make it {{book.book_photo.url}} it crashes {% load static %} {% for book in books %} {% if book.adultcontent == True and user.is_child %} <div class="hidden"> {% if user.is_admin%} <a class="btn btn-sm btn-info" href="{% url 'edit_book' book.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'delete_book' book.id %}">Delete</a> {% endif %} {% else %} <div class="book-row"> {% if user.is_admin%} <a class="btn btn-sm btn-info" href="{% url 'edit_book' book.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'delete_book' book.id %}">Delete</a> {% endif %} <span></span> <span>{{book}}</span> <img class="photo" src="{{book.book_photo}}" > {% endif %} </div> {%endfor%} I have additionaly configured settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') and have added urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the console shows that … -
User Login Authentication using forms and Django
I am trying to set up the user authentication for the login page using forms and comparing it to database values and my code works but then I realized I was getting login successful if I put any password if it was available in the database. What I want to do is to search for the mail and get the password for that user only not the whole database. My database will contain no duplicate emails so I don't have to worry about that. I have spend too much time trying to figure out how to get the password for same user the email is. my login.views look like this def login(request): if request.method == "POST": form = Studentlogin(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = User.objects.create_user(email, password) try: studentemail = students.objects.get(email=email) studentpass = students.objects.get(password=password) return render (request, 'subscrap/main.html', {'student': studentemail }) except: messages.success(request, 'Error, either Email or Password is not correct') pass else: form = Studentlogin() return render(request, 'subscrap/login.html', {'form': form}) My student model looks like this: class students(models.Model): fname = models.CharField(max_length=50) lname = models.CharField(max_length=50) password = models.CharField(max_length = 50 , null = True) passwordrepeat = models.CharField(max_length = 50, null = True) email = models.EmailField(max_length=150) class … -
Dash datatable not rendering in django_plotly_dash web app
I am creating a web application using django_plotly_dash, a module combining Django, Plotly, and Dash into one package. I am having an issue where I can't render the datatables from my original dash app onto the django webpage. From researching, these github issues (link_1 and link_2) would suggest that I have to add some components to my settings.py or run python manage.py collectstatic. I've tried both of these solutions and none have worked for me. If there is anybody who has a clue or has tried something like this with this package before, your help would be appreciated. Here is the html page that is supposed to render the tables: welcome.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <h1>Home Page</h1> <div class="{% plotly_class name='DashBoard' %} card" style='height: 100%; width: 100%'> {% plotly_app name='DashBoard' ratio=0.65 %} </div> <br> {{ plot1 | safe }} {% endblock %} Here is a segment of the dash datatables to be rendered: dashboard.py from dash import dcc from dash import html from dash import dash_table from dash.dash_table import FormatTemplate from dash.dash_table.Format import Sign from dash.dependencies import Input, Output from django_plotly_dash import DjangoDash import pandas as pd from … -
Needs time slot to display when user select date and also want the time slot deactivated when selected or clicked on
enter image description here This is the time slot image I want to be able to disable slot when clicked on. -
Django Python manage.py runserver showing error although my codeis correct
Error Error Image views.py code view.py code url.py code url.py code -
Get the integer value of IntegerChoices given a string in Django?
Suppose I have class AType(models.IntegerChoices): ZERO = 0, 'Zero' ONE = 1, 'One' TWO = 2, 'Two' in Django 3.2. Then AType.choices can be used as a dict, e.g. AType.choices[0] or AType.choices[AType.ZERO] is 'Zero'. What's the easiest way to map from the string to the int (0, 1, 2), e.g., map 'Zero' to 0? I could make another dict by iterating over each key, value pair, and use the other dict. However, I wonder if there's a more convenient way. This is somewhat related to this question (other way), or this question (doesn't have the answer), or this question (also doesn't have the answer). -
Django - XAMPP - Apache - Cookiecutter
I have a Django project configured using cookiecutter and I need to deploy the proyect using XAMPP and apache with mod_wsgi on windows 10. I already try some solutions but does not work for me. This is my configuration: Apache/2.4.48 (Win64) OpenSSL/1.1.1k PHP/8.0.8 mod_wsgi/4.9.0 Python/3.7 Django Version 3.2 wsgi.py import os import sys from pathlib import Path from django.core.wsgi import get_wsgi_application ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent sys.path.append(str(ROOT_DIR / "cinema")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() httpd.conf in apache xampp LoadFile "D:/Tools/Anaconda3/python37.dll" LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome "D:/Trabajo/ByT/CINEMA/venv" WSGIPythonPath "D:/Trabajo/ByT/CINEMA/cinema/config/" <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "logs/cinema.error.log" CustomLog "logs/cinema.access.log" combined WSGIScriptAlias /cinema/ "D:/Trabajo/ByT/CINEMA/cinema/config/wsgi.py" <Directory "D:/Trabajo/ByT/CINEMA/cinema/config"> <Files "wsgi.py"> Order allow,deny Allow from all Require all granted </Files> </Directory> Alias /static "D:/Trabajo/ByT/CINEMA/cinema/staticfiles/" <Directory "D:/Trabajo/ByT/CINEMA/cinema/staticfiles/"> Require all granted </Directory> Alias /media "D:/Trabajo/ByT/CINEMA/cinema/media/" <Directory "D:/Trabajo/ByT/CINEMA/cinema/media/"> Require all granted </Directory> </VirtualHost> When I run the apache server, I'm getting server error 500 and this is a fragment from the logs: [Tue Nov 09 17:54:49.688418 2021] [wsgi:error] [pid 7892:tid 1980] [client ::1:19759] ModuleNotFoundError: No module named 'config'\r -
getting model property value in other model form and display it
I have two models, and the user need to fill the first model form and he will be redirected to the next form where I want to get a value from property of the first model to the seconde model form. ***Models*** class Delivery(models.Model): user = models.ForeignKey( Client, on_delete=models.CASCADE, verbose_name=_("Client"), related_name=_("delivery_user") ) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("destination_address")) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) @property def distance(self): distance = Distance( m=self.pickup_address.address_point.transform(32148, clone=True).distance( self.destination_address.address_point.transform(32148, clone=True) ) ) context = {} context["distance"] = f"{round(distance.m / 1000, 2)}" print(context) return context def __str__(self): return str(self.delivery_key) class DeliveryDetails(models.Model): delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE, related_name=_("delivery")) distance = models.DecimalField(_("Distance Approximative "), max_digits=7, decimal_places=2) delivery_price = models.DecimalField(max_digits=7, decimal_places=2) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) def __str__(self): return str(self.created_at) ***Views*** class DeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, FormView): model = Delivery form_class = UserDeliveryForm template_name = "deliveries/customer/edit_deliveries.html" def get_success_url(self): return reverse( "delivery:delivery-details", kwargs={"pk": self.object.pk, "distance": self.object.distance}, ) def test_func(self): return self.request.user.is_active class DetailsDeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, FormView): model = DeliveryDetails form_class = DeliveryDetailsForm template_name = "deliveries/responsable/edit_deliveries_details.html" … -
Is there any reason why a user would not be able to load scripts if they are not inside a scripts file?
The problem I am facing a rather weird issue where a windows 10 user is not able to load scripts if they are in script tags inside of a template file (.html). However scripts are loading fine if they are added into a script file (.js). The problem is that I am unable to hard code everything into the script files because some values are dynamically generated. Here's a very simple example: Ex: $.ajax({ url: "{% url 'some-namespace' %}", type: "POST", data: data, ... If I were to change a url pattern, then I can just do so directly in the Django urls.py file, and not have to update all of the scripts. How do I know this? When the user told me he got Uncaught ReferenceError: discardDraft is not defined, then I realized that his computer was not loading scripts inside of templates. I tested this by first adding a basic alert in the template file, and nothing appeared. I then tried adding another alert inside of the scripts file, and voila it works. So I am extremely puzzled and honestly have no clue how to figure out a solution to this. Other issues this user faced: make-corrections.js:96 Uncaught … -
How can i make good models for categories in django?
im trying to make a online menu qr. i want to make a category, sub category an items that go in one of those. I mean, an item can be on a category like "sushi", or be in a sub category like sushi -> avocado rolls -> nameofsushi. i have something like this in my models.py but is there a better way to do it? class Category(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=500, verbose_name='Descripción', blank=True, null=True) parent = models.ForeignKey('self', related_name='children', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return 'Category: {}'.format(self.name) class MenuItem(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='menu_images/', null=True, blank=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=0) other_Price = models.DecimalField(max_digits=6, decimal_places=0, null=True, blank=True) categories = models.ManyToManyField('Category', related_name='item', null=True, blank=True) def __str__(self): return 'MenuItem: {}'.format(self.name) -
How to query many-to-many field in Django
I'm trying to update a view I have that returns all my items from my pets table given the current logged in user. I have in Pet a many-to-many field petowners. The PetOwner model is as follows... class PetOwner(models.Model): """Model representing a pet owner.""" user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, help_text="Enter owner's first name") last_name = models.CharField(max_length=50, help_text="Enter owner's last name") email = models.EmailField( max_length=50, blank=True, null=True, unique=True, help_text="Enter owner's email" ) phone_number = models.CharField( max_length=15, blank=True, null=True, unique=True, help_text="Enter owner's phone number" ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, null=True, blank=True ) The Pet model is as follows... class Pet(models.Model): """Model representing a pet.""" first_name = models.CharField(max_length=50, help_text="Enter pet's first name") last_name = models.CharField(max_length=50, help_text="Enter pet's last name") breeds = models.ManyToManyField("Breed", help_text="Select a breed for this pet") weight = models.DecimalField( max_digits=5, decimal_places=2, help_text="Enter pet's weight" ) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField("Died", null=True, blank=True) owners = models.ManyToManyField(PetOwner, help_text="Select an owner for this pet") address = models.ForeignKey( "Address", on_delete=models.SET_NULL, null=True, blank=True ) I am using the User that is already given to us by Django for authentication (registering and login). A PetOwner is created when a user creates their account, alongside with their first and last name. The PetOwner … -
Should I include django tables in my database structure?
I'm writing a report regarding my django project. I have to describe my database structure and I have three tables with data - products, shopping list, recipes. When I added JWT authorization, django created few tables in the database - customuser, blacklist_token etc. My question is - should I include them in diagrams showing my structure or not? Thanks for your help -
Django - Trying to order get_object_or_404 by latest
I have a collection of blog post with a category defined for each. The single category page displays all post under the specified category, but I would like these to be sorted by the date written. Here is what I have: def single_category(request, slug): category = get_object_or_404(Category, slug=slug) categories = Category.objects.all() context = { 'category': category, 'categories': categories } return render(request, 'Blog/single-category.html', context) This doesn't work, but here is what I want: def single_category(request, slug): category = get_object_or_404(Category.objects.order_by('-written_on'), slug=slug) categories = Category.objects.all() context = { 'category': category, 'categories': categories } return render(request, 'Blog/single-category.html', context) -
Django's pagination in React
I'm trying to set a django's pagination in react. views.py def post_list(request): posts = Post.published.all() serializer = PostSerializer(posts, many=True) paginator = Paginator(posts, 2) page = request.GET.get('page') venues = paginator.get_page(page) context = {'posts': json.dumps(serializer.data), 'venues': venues, 'has_next': venues.has_next, 'has_previous': venues.has_previous, 'num_pages': venues.paginator.num_pages, 'previous_page_number': venues.previous_page_number, 'num_current': venues.number} return render(request, 'frontend/index.html', context) I'm done with most of the work but I can't think of a solution of one problem. When I try to loop over a venues from views.py I get an error. What I mean: Inside my React component: {JSON.parse(posts).map((post, index) => <div> <p key={index}>{post.title}</p> <p key={index}>{post.body}</p> </div> )} But I have 6 of posts, and I want to display just 2 per page. So I did {JSON.parse(venues).map((post, index) => as in classic django. When JSON.parse is removed, the error is map() isn't a function. -
get_or_create creates an object even though it already exists in Django
views.py customer, created = Customer.objects.get_or_create( personal_number=request.POST.get("personal_number"), defaults={ "first_name" : request.POST['first_name'], "last_name" : request.POST['last_name'], } ) models.py class Customer(models.Model): first_name = models.CharField( db_column='FirstName', verbose_name=first_name_label, max_length=150, blank=False ) last_name = models.CharField( db_column='LastName', verbose_name=last_name_label, max_length=150, blank=False ) personal_number = models.PositiveIntegerField( db_column='PersonalNumber', verbose_name=personal_number_label, unique=True ) debug Customer.objects.get(request.POST['personal_number']) -> returns an object that exist Why even it finds an exist customer it still trying to create a new customer with it's defaults that I set? -
Trying to get Twilio app to work correctly with "if" statement
What am I doing wrong? Please help. Problem: twilio_view2 ignores the "if" statement and outputs the TwiML response below even when (i think) a match occurs. Desired result: If test matches digits then proceed to twilio_view3, otherwise redirect to twilio_view1. example.py import re def test(digits): if re.match(r'^99\d{10}$', digits): return True else: return False views.py from example import test def twilio_view2(request: HttpRequest) -> HttpResponse: digits = request.POST.get('Digits') response = VoiceResponse() if test(digits): gather = Gather(input='dtmf', action='/twilio_view3', method='POST') gather.say('Blah blah blah.') response.append(gather) else: response.say('Something other than Blah blah blah.') response.redirect("/twilio_view1") return HttpResponse(str(response), content_type='text/xml') TwiML response: <Response> <Say>Something other than Blah blah blah.</Say> <Redirect>/twilio_view1</Redirect> </Response> -
In Django why the error "TypeError at / Field 'fees' expected a number but got [[0, 0.26], [50000, 0.24], [100000, 0.22], ..."?
I am trying to figure out how to get in Django a sequence of strings, an integer, and an array of integers or numbers from a Kraken API. I went through other examples here and created the code below. The strings of my code return properly the values, however the arrays of integers return an error. How can i solve this error and gain control over every part of this API content? views.py i marked the variables that "return OK" and the ones that do not return properly are "NOT OK" from django.shortcuts import render from meal_app.models import Kraken import requests def get_krakens(request): all_krakens = {} url ='https://api.kraken.com/0/public/AssetPairs' response = requests.get(url) data = response.json() for i in data['result'].values(): kraken_data = Kraken( altname = i['altname'], # string return OK wsname = i['wsname'], # string return OK aclass_base = i['aclass_base'], # string return OK base = i['base'], # string return OK aclass_quote = i['aclass_quote'], # string return OK quote = i['quote'], # string return OK lot = i['lot'], # string return OK pair_decimals = i['pair_decimals'], # integer return OK lot_decimals = i['lot_decimals'], # integer return OK lot_multiplier = i['lot_multiplier'], # integer return OK # leverage_buy = i['leverage_buy'], # Array of integers NOT …