Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to toggle SVG from javascript or jquery , add and removed button?
This is javascript to make it do what you want to do? See //toggle line SVG to get the idea how it works i am using Jquery No more detail StACK overFLOw why do you asking me stupid $(document).ready(function() { var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); console.log("Document.ready"); $("a.tag__follow").click(function (e) { e.preventDefault(); var tag_id = $(this).data('id'); console.log(tag_id); $.post( $(this).data("url"), { csrfmiddlewaretoken: csrfToken, id: $(this).data("id"), action: $(this).data("action"), }, function (data) { if (data['status']=='ok') { var previous_action = $('a.tag__follow.'+tag_id).data('action'); // toggle data-action $('a.tag__follow.'+tag_id).data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link SVG $('a.tag__follow.'+tag_id).html(previous_action == 'follow' ? '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path d="M23 13.482L15.508 21L12 17.4l1.412-1.388l2.106 2.188l6.094-6.094L23 13.482zm-7.455 1.862L20 10.889V2H2v14c0 1.1.9 2 2 2h4.538l4.913-4.832l2.094 2.176zM8 13H4v-1h4v1zm3-2H4v-1h7v1zm0-2H4V8h7v1zm7-3H4V4h14v2z" fill="currentColor"/></svg>' : '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path d="M23 16v2h-3v3h-2v-3h-3v-2h3v-3h2v3h3zM20 2v9h-4v3h-3v4H4c-1.1 0-2-.9-2-2V2h18zM8 13v-1H4v1h4zm3-3H4v1h7v-1zm0-2H4v1h7V8zm7-4H4v2h14V4z" fill="currentColor"/></svg>'); // toggle class $('a.tag__follow.'+tag_id).toggleClass(previous_action == 'follow' || previous_action == 'unfollow' ? 'tag__following': ''); } } ) }) }) -
How to create a service from a function?
I want to create a service using Django Rest API. I have a function. The result of this function should return 2 values and I should return these values in JSON API format. The function will work like this. I will receive the features_list as a parameter and I will use it to create a result and display it as a service in json format in def prediction function. I created a sample API (I guess) it is class PredictionSet in my views but I actually want to make service the def prediction function in my views. I cannot understand how to apply it. I am so confused. Any help would be appreciated. models.py class Liquidity(models.Model): pred_y = models.CharField(max_length=600) score = models.FloatField() views.py class PredictionSet(viewsets.ModelViewSet): queryset = Liquidity.objects.all() serializer_class = LiquiditySerializer def prediction(request, features_list): filename = config.FINAL_MODEL_PATH classifier = pickle.load(open(filename, 'rb')) scale_file = config.SCALER_PATH scaler = pickle.load(open(scale_file, 'rb')) sample = np.array(features_list).reshape(1, -1) sample_scaled = scaler.transform(sample) pred_y = classifier.predict(sample_scaled) prob_y = classifier.predict_proba(sample_scaled) if prob_y[0][1] < 0.5: score = 0 elif prob_y[0][1] <= 0.69: score = 1 else: score = 2 pred_y = pred_y[0] prediction_obj = Liquidity.objects.get_or_create(pred_y=pred_y, score=score) prediction_result = prediction_obj.pred_y prediction_score = prediction_obj.score context = { 'prediction_result ': prediction_result, 'prediction_score ': … -
Can we write a single dockerfile for both front end and backend?
I've to dockerize a django react app. I wonder can we write a single dockerfile for both front end and back end instead of writing separate files and combining them at the end in docker compose? -
I want to insert a button in my table that shows expenses using javascript when the user searches someting in the searchfield
Here is my template html code :- <!---this table will show if the user has noting in the searchField---> <div class = "default-table" > <table class = "table table-stripped table-hover"> <!---table head---> <thead> <tr> <th>Amount ({{currency}})</th> <th>Category</th> <th>Description</th> <th>Date</th> <th></th> <!---this will hold the edit buttons for our expenses---> <th></th> <!---this will hold the delete buttons for our expenses---> </tr> </thead> <!---table body---> <tbody> <!---instead of looping through the expenses here we should loop through the page_obj which will give the number of expenses defined in the paginator class per page---> {% for expense in page_obj %} <tr> <td>{{expense.amount}}</td> <td>{{expense.category}}</td> <td>{{expense.description}}</td> <td>{{expense.date}}</td> <td><a href="{% url 'expense_edit' expense.id %}" class = "btn btn-primary">Edit</a></td><!---this will hold the edit buttons for our expenses---> <td><a href="{% url 'expense_delete' expense.id %}" class = "btn btn-danger">Delete</a></td><!---this will hold the edit buttons for our expenses---> </tr> {% endfor %} </tbody> </table> </div> <!---this table will show if the user tries to search expenses in the searchField---> <div class="table-output"> <table class = "table table-stripped table-hover"> <!---table head---> <thead> <tr> <th>Amount ({{currency}})</th> <th>Category</th> <th>Description</th> <th>Date</th> <th></th> <!---this will hold the edit buttons for our expenses---> <th></th> <!---this will hold the delete buttons for our expenses---> </tr> </thead> <!---table body---> … -
hosting django with angular on digitalocean with nginx
I have a Django-Angular project which I want to deploy on DigitalOcean with Nginx and I am successful in running the whole setup, but I have some doubts that I want to clear before finally proceeding with this solution. This is what I've done so far Currently, I've gunicorn.sock and gunicorn.service files to set up gunicorn and passed this file in Nginx's location block location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } The Django project is running without any issue. For the angular project, I am using supervisor, inside /etc/supervisor/conf.d/my_angular_app.conf, I've set up configurations for angular app [program:my_angular_app] command=ng serve directory=/path/to/angular/project/ user=www-data autostart=true autorestart=true stdout_logfile=/path/to/angular/project/logs/angular.log redirect_stderr=true this starts the angular project on localhost:4200 Now, I've added another location block inside my Nginx file to proxy pass the requests to angular location / { include proxy_params; # this will pass the requests to angular project proxy_pass http://localhost:4200; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } This whole setup is … -
How to save an async function fetchData() and insert it to chart.js?
My goal is to use json data as labels and data in my Chart.js piechart. I have a query which gets the data and converts it to Json in view.py: def get_data(request): filtered_transaction_query_by_user = Transaction.objects.filter(portfolio__user=request.user) total_transactions_by_user = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price') * Sum('number_of_coins'))).order_by('-total') data = list(total_transactions_by_user) return JsonResponse(data,safe=False) Resulting this at http://127.0.0.1:8000/get_data/: [{"coin__name": "Bitcoin", "total": "1220"}, {"coin__name": "Ripple", "total": "160"}] At piechart.html, I fetch it in < scripts >: async function fetchData() { const url = 'http://127.0.0.1:8000/get_data/'; const response = await fetch(url) // wait until the request has been completed const datapoints = await response.json(); console.log(datapoints); return datapoints;} Finally, I call the function, but I dont see how to insert the labels and the data into the piechart: fetchData() var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ['example','example2'], // insert here datasets: [{ data: [45,55], //insert here backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], -
Nginx can't find static files
o know that it is oftenn question. I have 2 servers with the same nginx config location /static/ { root /var/www/html; } real dicrectory for static is /var/www/html/static One server see the django static files, seconf write 404 and can't see that. I tried alias too. Any suggesions? -
Your URL pattern [<URLPattern> ] is invalid. DJANGO Urls.py file
I am getting this error ERRORS: app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/media/(?P.)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/static/(?P.)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. I don't know why I am getting this error. I have correctly added everything in my url patterns urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/jobs/", include("jobs.urls")), path("api/v1/company/", include("company.urls")), ] if settings.DEBUG: urlpatterns.extend( [ static("/static/static/", document_root="/vol/web/static"), static("/static/media/", document_root="/vol/web/media"), path("__debug__/", include(debug_toolbar.urls)), ] ) -
How do change background color of entire page in bootstrap?
I wanted to change background color of entire page . I'm using bootstrap 5 starter pack and its elements. Please give me the right answer. -
Django-channels and Firefox connection issue
I am using django-channels as a sockets endpoint in django project, I developed a real time chat using django-channels, tested, deployed to Ubuntu on top of docker, and using NGINX as a web server, it is working pretty cool, did many tested. However one of my college lives in United Arab Emirates, when he tests the socket is not working with Firefox and Safari browsers, in console JS says: cant't establish a connection to the server at wss://site.com. We did cache cleaning in his browsers, still no luck Please note that: Other with other people in even in UAE, it working very fine :( I think it might be problem with my NGINX config, so here it is: upstream site_template_wsgi { server localhost:9002; } upstream site_template_asgi { server localhost:9003; } server { root /var/www/site_template; server_name site.com www.site.com; location / { proxy_redirect off; proxy_set_header host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://site_template_wsgi; } location /socket/ { proxy_pass http://site_template_asgi; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/site.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/site.com/privkey.pem; # managed by … -
How to use Django function based view to update a model?
I used a class based view to update a user profile using this code class EditProfileViewClass(generic.UpdateView): model = UserProfile fields = ['bio', 'profile pic'] template_name = 'users/update.html' success_url = reverse_lazy('home') path('profile/<int:pk>/update', EditProfileViewClass.as_view(), name="profile"), <a href="{% url 'profile' user.id %}">Your Profile</a> the issue right now is, Instead of having the url like the one above, I want it to be like path('profile/<str:username>/update', EditProfileViewClass.as_view(), name="profile"), but unfortunately I get an attribute error saying: Generic detail view EditProfileView must be called with either an object pk or a slug in the URLconf. So I tried making a function based view so I can get the "username" from the url, doing that didn't allow me to get the form I needed to update the specific username. Any help would be great. Thanks. -
Why am I getting CORS error on some devices, while others are working fine?
I am using django-cors-headers for CORS in django. It is working fine for some devices, but some devices get CORS error. I tested it out in some of my devices, some worked, and some didn't. I also cleared entire browser data on all those devices. But it still didn't help :( My settings: from corsheaders.defaults import default_headers INSTALLED_APPS = [ ... 'corsheaders' ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', "https://www.example.com", "http://www.example.com", "https://example.com", "http://example.com", ] CORS_ALLOW_HEADERS = list(default_headers) + [ 'upload-length', 'upload-metadata', 'upload-offset', 'x-http-method-override', 'x-request-id', 'tus-resumable', 'location', 'content-type', ] CSRF_TRUSTED_ORIGINS = [ "localhost:3000", "example.com", "www.example.com" ] CORS_EXPOSE_HEADERS = [ "Location", "Upload-Offset", "Upload-Length" ] -
adding .annotate foreign key in objects does not give distinct result
When i run following query its working fine query= UserOrder.objects.filter(order_date__range=( Request['from'], Request['to'])).values('user_id__username','user_id__email').annotate( total_no_of_order=Count("pk")).annotate(total=Sum('total_cost')) But i also want to know the number of services related to order .annotate(total_no_of_services=Count("userorderservice__pk")) by adding above code in query total_no_of_order and total_cost getting changed too and by putting distinct=True in total_cost its only considering for single unique total_cost value Modles.py class UserOrder(models.Model): order_id = models.AutoField(primary_key=True) user_id = models.ForeignKey(AppUser, on_delete=models.CASCADE) total_cost = models.FloatField() ... class UserOrderService(models.Model): order_id = models.ForeignKey(UserOrder, on_delete=models.CASCADE) ... -
request.POST.get didn't get the input value
So, what I was trying to do is that user input a base64 encoded image and than convert it to text via pytesseract OCR. The problem is every time I tried to input it only reload the page and nothing happens. Here's my html snippet : <form method="POST" action="{% url 'ocr-view'%}"> {% csrf_token %} <label for="base64"> Input Base64 :</label> <input type="text" class="form-control" id="text" name="base64" /> <button type="submit" class="btn btn-primary mt-3" name="submit"> <i class="fas fa-search"></i> Submit </button> </form> <div class="card-body"> <label> Result : </label> <br> <span class="h3">{{text}}</span> </div> Here's my views.py : class IndexView(LoginRequiredMixin, CreateView): model = Ocr template_name = "ocr/ocr.html" fields = ['input'] def get_context_data (self): text = "" if self.request.method == 'POST': imgstring = self.request.POST.get('base64') imgstring = imgstring.split('base64,')[-1].strip() image_string = BytesIO(base64.b64decode(imgstring)) image = Image.open(image_string) text = pytesseract.image_to_string(image) text = text.encode("ascii", "ignore") text = text.decode() context = { 'text': text, } return context But if i put the base64 code directly to views.py the OCR function work perfectly. imgstring = 'data:image/jpeg;base64,/9j/somerandomcode' imgstring = imgstring.split('base64,')[-1].strip() image_string = BytesIO(base64.b64decode(imgstring)) image = Image.open(image_string) text = pytesseract.image_to_string(image) text = text.encode("ascii", "ignore") text = text.decode() context = { 'text': text, } return context I assume there is something wrong with my post method, please review … -
Is there a way to keep alive request longer than 60s in EC2 instance?
Hello everyone I've been trying to execute our django app on amazon aws ec2 instance. Everything works fine except for requests longer than 60s. Those requests automatically get 504 Gateway Time-out. I configured all needed ports in Security Groups for my EC2 instance. We are using nginx and my nginx.conf looks like: user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 3600s; client_max_body_size 500M; client_body_timeout 86400s; client_header_timeout 86400s; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; proxy_connect_timeout 86400s; proxy_send_timeout 86400s; proxy_read_timeout 86400s; send_timeout 86400s; #gzip on; include /etc/nginx/conf.d/*.conf; } I tried to play with keepalive_timeout as many posts suggest but it's not working. There are also a lot of posts mentioning load balancer configuration but I'm not even using load balancer so this should not be related to it. How do I manage my instance to process requests longer than 60s? -
How to convert json to form in Django?
I'm developing a Django project, and the team want to seperate the front-end and the back-ed, so I'm using Django to develop api. The format of the data transmitting is json. However, I want to use the defalt user package (django.contrib.auth), and I have to use Form. How could I convert the json received from the frontend to the form that I'm going to use in backend? thanks! I have tried the silly code as below and it does not work. @require_http_methods(["POST"]) def register(request): form = CustomUserCreationForm(data=request.POST) response = {"status": "success"} if form.is_valid(): new_user = form.save() print("valid") return JsonResponse(response) -
Reverse look-up with related name
Suppose these models: class Person (models.Model): pass and class Marriage (models.Model): person = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='person') person_2 = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='person_2') How can I filter persons through the ID of a Marriage field (e.g. the ID)? That is, my goal is to do something like Person.objects.filter(marriage__id=32). I understand that the related name has some role there, but for example Person.objects.filter(person_2__marriage__id=32) doesn't seem to work either. Thank you! -
Weird behavior when accessing request.user in django
I have a simple view which requires a user to be logged in AND belongs to a specific group as the following class IndexView(LoginRequiredMixin, UserPassesTestMixin, generics.GenericAPIView): serializer_class = IndexSerializer def test_func(self): print(self.request.user) // User object return self.request.user.groups.filter(name='Poster').exists() def get(self, request, *args, **kwargs): print(self.request.user) // AnonymousUser print(request.user) // Anonymous User return HttpResponse('Welcome') The thing is when I print the user inside the get method it returns AnonymousUser but it returns a User object inside the test_func method. I am clueless of why this is happening so any help would be appreciated. -
REST Api Django - create new model-object and add currently logged in user to it
I have an endpoint, where a currently logged in user can create an object called 'project' . I want to show the user all of his own projects, so when he creates a new one, I want the user to be automatically added to the projects user fields. How would I achieve that? Both the user and the Project objects do have an ID, so I would like to have an own model wich combines those two. My idea was to create a new view wich takes a userID and a projectID and puts them together as ManyToMany relationship. Can I somehow call the view right inside the 'create project' view without the need of a new POST ? I want to be able to use the view at an other point as well, thats why I want to split this. my current model looks like this models.py class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, default = None) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'Projects' def __str__(self): return self.name views.py class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) … -
View counter using IP address in Django app
I am working on Django app and I want to know how many people use it, so I decided to add view counter on the page. I created view counter (watched some tutorial) but it doesn't work. I don't know where is a problem. Here is the code: models.py: class User(models.Model): user=models.TextField(default=None) def __str__(self): return self-user admin.py: admin.site.register(User) There is a problem with views.py. It says that "return can be used only within a function". I know that but what can I do to make this work? def get_ip(request): address=request.META.get('HTTP_X_FORWARDED_FOR') if address: ip=address.split(',')[-1].strip() else: ip=request.META.get('REMOTE_ADDR') return ip ip=get_ip(request) u=User(user=ip) print(ip) result=User.objects.filter(Q(user__icontains=ip)) if len(result)==1: print("user exist") elif len(result)>1: print("user exist more...") else: u.save() print("user is unique") count=User.objects.all().count() print("total user is", count) return render(request, 'index.html', {'count':count}) index.html: {% load static %} <html> <head> <title>Hello World Django App</title> </head> <h1>Hello World!</h1> <div>Total visits: {{count}} </div> </html> -
How many websocket connection should to ı use in my chat application?
I am developing a django chat application for my website and I am using websockets for that.My system like a real chat ,you can enter a system and you can see different user in your dashboard to send message.And every time you click different user for chat, I connected websocket every two person for chatting.Is that true or just one websocket connection should I use for the all system and I can save message with using users Id.Or this way will slow down my website?Which one is better? -
Wagtail - pass parameters to struct block
I'm trying to pass parameters to a struct block, which also has child struct blocks to load the choices dynamically through choice block. Tried the concept with init method, but no success yet. Below is my implementation code - class DefaultThemeTemplate(blocks.StructBlock): template = blocks.ChoiceBlock(choices=[], label=_('Select a template'), required=False) def __init__(self, folder=None, **kwargs): self.template = blocks.ChoiceBlock(choices=get_designs(folder), label=_('Select a template'), required=False) super(DefaultThemeTemplate, self).__init__(**kwargs) class Meta: label = _('Default Theme') class ThemeOneTemplate(blocks.StructBlock): template = blocks.ChoiceBlock(choices=[], label=_('Select a template'), required=False) def __init__(self, folder=None, **kwargs): self.template = blocks.ChoiceBlock(choices=get_designs(folder), label=_('Select a template'), required=False) super(ThemeOneTemplate, self).__init__(**kwargs) class Meta: label = _('Theme One') class ThemeTwoTemplate(blocks.StructBlock): template = blocks.ChoiceBlock(choices=[], label=_('Select a template'), required=False) def __init__(self, folder=None, **kwargs): self.template = blocks.ChoiceBlock(choices=get_designs(folder), label=_('Select a template'), required=False) super(ThemeTwoTemplate, self).__init__(**kwargs) class Meta: label = _('Theme Two') class Templates(blocks.StructBlock): default_theme = DefaultThemeTemplate(folder='', required=False) theme_one = ThemeOneTemplate(folder='', required=False) theme_two = ThemeTwoTemplate(folder='', required=False) def __init__(self, folder=None, **kwargs): self.default_theme = DefaultThemeTemplate(folder=folder, required=False) self.theme_one = ThemeOneTemplate(folder=folder, required=False) self.theme_two = ThemeTwoTemplate(folder=folder, required=False) super(Templates, self).__init__(**kwargs) class Meta: label = _('Template') class StaticPage(Page): template = StreamField([ ('template', Templates(required=False, folder='pages')) ], null=True, blank=True, verbose_name=_('Template')) Here's the screenshot with the blank choice fields - Please help me find out what am I doing wrong here. Thanks in advance. -
How to add PDF created by ReportLab into a FileField in a model of Django
In the viws.py, I can create a PDF file. However, I can't add it into a FileField in a model. from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase import pdfmetrics buffer = io.BytesIO() cc = canvas.Canvas(buffer, pagesize=A4) # describe something font_name = "HeiseiKakuGo-W5" pdfmetrics.registerFont(UnicodeCIDFont(font_name)) pdfCanvas.setFont(font_name, 7) pdfCanvas.drawString(65*mm, 11*mm, 'test') cc.showPage() cc.save() cc.seek(0) # I can't add a PDF created above into a FileField in a model # someObject.someField.save('test.pdf', File(buffer)) # someObject.save() return FileResponse(buffer, as_attachment=True, filename='receipt_pdf.pdf') -
How to make queryset equal to list in django webapp?
Suppose that i have a model called "Test" in models.py, and the view function in views.py as follows: def app_view(request): if request.method == 'POST': form = AppForm(request.POST) if form.is_valid: ... else: form = AppForm() the_query = Test.objects.all().values_list('test_field') the_list = list(the_query) the_length = len(the_list) form.fields['test_field'].queryset = [the_list[x] for x in range(0,the_length)] return render(...) because the item in "the_query" is tuple type, but i need str type, so i convert the queryset to list, but at the second last row i neet make the queryset equal to the list, but i got an AttributeError, so i want to know is there any other way to achieve my demand? -
Twilio Voice Gather + Django Regex Validation
How do I use regular expressions to validate user input collected via dtmf? For example: I want to apply validation on multiple views within the same views.py. If user input passes validation then redirect to the next view. If user input fails validation then use the verb to give an error message and redirect to current view so that they can try again. Example: Please press 123 User presses 384 Input is checked against regex and it fails validation Say: I'm sorry, but that is incorrect. redirect to current view, so user may retry Please press 123. Example: Please press 123 User presses 123 Input is checked against regex and it passes validation User is redirected to the next view I'm using: Python 3.9.5 Django 3.2.8 twilio 7.1.0