Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I disallow a button from submitting my form in Django?
I have two buttons in my django site's form, the first one is supposed to only call a javscript function and the second one is supposed to submit the form. <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.title|as_crispy_field }} <br/> {{ form.body|as_crispy_field }} <button class="btn mt-3" onclick="insertText('HELLO')">Insert Text</button> <br/> <button class="btn btn-success mt-3" >Submit!</button> </form> My 'views.py' file contains following code for this page: class Posts(View): def get(self, request, *args, **kwargs): form = PostForm() posts = Post.objects.all().order_by('-publish_date') context = { 'form': form, 'posts': posts } return render(request, 'posts/view_posts.html', context) def post(self, request, *args, **kwargs): form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.publisher = request.user new_post.save() form = PostForm() return redirect('view-posts') My problem is the 1st button that is supposed to be only calling a javascript function is also making a POST request and submitting the form. Any solution to this problem? -
run cronjob 1 hour after the last run finished
I have a django cron and run it with linux crontab every hour. But I want to change the crontab to run the django cron 1 hour after the last execute finished. How can I do that? It is the crontab: */1 * * * * /usr/bin/python3.8 /django/vira/manage.py runcrons And this is django-cron: from django_cron import CronJobBase, Schedule from . import runner # create a class extending CronJobBase class PushCronJob(CronJobBase): RUN_EVERY_MINS = 10 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = "vira_app.runner" def do(self): runner.run_spider() -
How to get all Image using Multiple Image in Django UpdateView
When I try to update or edit my post my multiple image can't get all save images. But when I save the image without Uploading their all disappear This is my views.py UpdateView class UpdatePostView(LoginRequiredMixin,UserPassesTestMixin, UpdateView): model = Post form_class = PostForm template_name = "dash/blog/post/edit-post.html" def form_valid(self, form): form.instance.author = self.request.user post = self.get_object() # Clear existing images/This is working for post_image in Image.objects.filter(post=post): post_image.delete() images = self.request.FILES.getlist('image') print(images) for i in images: Image.objects.create(post=post, image=i) form.save() return super().form_valid(form) This is the models.py class Post(models.Model): title = models.CharField(max_length=255) content = RichTextField(blank=True,null=True) featured_image = models.ImageField(upload_to="blog_picture", default='blog_picture/post.jpg',null=True, blank=True) tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey( Category, on_delete=models.CASCADE,related_name='categories') date_created = models.DateTimeField(auto_now_add=True) date_published = models.DateField(blank=True,null=True,verbose_name="Date Published (yyyy-mm-dd)") previous_post = models.ForeignKey('self',related_name='previous',on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self',related_name='next',on_delete=models.SET_NULL, blank=True, null=True) @property def all_categories(self): categories = [] current_category = self.category while current_category is not None: categories.append(current_category) current_category = current_category.parent return categories def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('dashboard:post' ) class Image(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to="blog_picture", default='blog_picture/post.jpg',null=True, blank=True) def __str__(self): return self.post.title This is my forms.py where I put image as a multiple image in my class PostForm(forms.ModelForm): image = forms.FileField(required=False, widget=forms.FileInput(attrs={ "class":"form-control", "multiple":True })) class … -
Django If an action is added to the form, the form is not submitted
I have a form in my Django project. I want to when user fills the form and click the send button form will be posted and redirect a URL. I am using action in form for that but when I do this the form is not submitted but it opens the link, and when I delete action, the form is being submitted. I do not know why it is not working? approval_page.html <form method="POST" enctype="multipart/form-data" class="lead_form" id="lead_form" action="{% url 'approvals:approve_pending' pk=approval.pk%}" > <!-- Very Important csrf Token --> {% csrf_token %} {{ form_approval.media }} {{ form_approval|crispy }} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> <input type="submit" class="btn btn-success btn-xs" value="Approve" > <a href="{% url 'approvals:decline_pending' pk=approval.pk%}"> <button class="btn btn-danger btn-xs" id="approve-btn">Decline</button> </a> </form> views.py def approval_page(request, id): ... form_approval = LeadApprovalForm(request.POST) if request.method == 'POST': if form_approval.is_valid(): print(request.POST.get('approver_name', None)) lead_approval = form_approval.save() lead_approval.user = request.user lead_approval.approval_id = approval lead_approval.rank = request.POST.get('rank_name', None) lead_approval.save() else: form_approval = LeadApprovalForm() context = { ... 'form_approval ': form_approval , ... } return render(request, 'approval_page.html', context) def approve_pending(request, pk): pending_approval = ApprovalProcess.objects.get(pk=pk) customer = pending_approval.doc_id.owner pdf = pending_approval.doc_id priority_number = 0 ... approval_step.delta_time = abs((approval_step.finish_time - approval_step.start_time).days) approval_step.save() ... return redirect('ocr_approve', pending_approval.doc_id.id) urls.py url(r'^ocrs/(?P<id>\d+)/analysis/approve$', views.approval_page, … -
Naming of paths in Django for referencing in html templates
I am a complete newbie at Django. I've looked around for projects on the internet with the hopes of trying to incorporate other django apps into those projects. Right now, what I am trying to do is to add a forum functionality into that particular project by installing Django-Machina. With the installation already done right, I am having trouble putting its URL into the base.html Since Machina is a downloaded app using pip, it doesn't appear in the project as an app but instead in the virtual environment that I am using. In urls.py of the feed app, urlpatterns=[ . . . path('forum/', include(machina_urls, namespace='forum')), . . . ] In base.html of feed/templates/feed/base.html <a class="nav-item nav-link" href="{% url 'feed:forum' %}">Forum</a> As of now I am having an error saying that I am specifying a namespace in include() without providing an app_name is not supported, and I fully understand the error. So how do I go about naming that particular path such that I am able to reference it in base.html ? Thank you very much in advance and please let me know if you need any additional information. I will try my best to provide them. -
docker-compse build -> many "PermissionError: [Errno 13] Permission denied" error's
newbie question, so i hope you bear with me! I am trying to run an instance of a docker container (django project) on my synology nas DS220+. After: docker-compose build I get this error: traceback (most recent call last): File "urllib3/connectionpool.py", line 677, in urlopen File "urllib3/connectionpool.py", line 392, in _make_request File "http/client.py", line 1277, in request File "http/client.py", line 1323, in _send_request File "http/client.py", line 1272, in endheaders File "http/client.py", line 1032, in _send_output File "http/client.py", line 972, in send File "docker/transport/unixconn.py", line 43, in connect PermissionError: [Errno 13] Permission denied During handling of the above exception, another exception occurred: ... [6138] Failed to execute script docker-compose My directory structure is: nas |-docker | |-configurator | | |-accounts | | |-config | | |-pages | | |-static | | |-staticfiles | | |-templates | | |-docker-compose.yml | | |-Dockerfile | | |-manage.py | | |-Pipfile | | |-Pipfile.lock | | |-requirements.txt | |-some_other_project My Dockerfile: FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /configurator/ COPY Pipfile Pipfile.lock /configurator/ COPY ./requirements.txt /requirements.txt RUN pip install -r requirements.txt COPY . /configurator/ My docker-compose.yml: version: '3.8' services: web: build: . command: python manage.py runserver 0.0.0.0:8080 volumes: - .:/configurator/ ports: - 8080:8080 … -
How to get token in URL endpoint of Django rest framework token authentication of authenticated user
I want to get token of authenticated user in Django rest framework but unable to add for calling it to React -
How to fill html "option" tag with data from database in Django?
I don't understand why information from database isn't showing in html dropdown list. I have watched many videos and tutorials, but something going wrong. Help me please to figure out what I do wrong. I'm using SQLite. Here is my html template — click And also: models.py from django.db import models class Department(models.Model): class Meta: verbose_name_plural = 'Отделы' department_name = models.CharField(verbose_name='Отдел', max_length=40, editable=True, unique=True) def str(self) -> str: return self.department_name class User(models.Model): class Meta: verbose_name_plural = 'Участники' first_name = models.CharField(verbose_name='Имя', max_length=40) last_name = models.CharField(verbose_name='Фамилия', max_length=40) rfid_mark = models.CharField(verbose_name='RFID', max_length=8, editable=True, unique=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now=True, editable=False) def str(self) -> str: return self.first_name + ' ' + self.last_name views.py from django.shortcuts import render from .forms import UserForm from .models import Department def create(request): form = UserForm() if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'passage/registration.html', context) def index(request): query_results = Department.objects.all() context = {'query': query_results} return render(request,'passage/registration.html', context) -
Wagtail Django ValidationError ['“8bf95516-2a6d-494d-817d-e931ab7df570” is not a valid UUID.']
I activated wagtail's localization support. Since then this error raises randomly. The Django App is running within Apache mod_wsgi in a virtualenv. To solve it, I tried: Searching and removing the mentioned UUID from database But another UUID will throw the same exception Disable wagtail-metadata, since this app always was on top of the stackdump no effect Because of randomness I tried to find some cache mechanism I failed So, please help me :-) Environment: Request Method: GET Request URL: https://*********************** Django Version: 3.1.12 Python Version: 3.8.5 Installed Applications: ['home', 'blog', 'shop', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.postgres_search', 'wagtail.contrib.search_promotions', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail.contrib.modeladmin', 'wagtail.contrib.settings', 'wagtail.api.v2', 'wagtail_localize', 'wagtail_localize.locales', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sitemaps', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'salesman.core', 'salesman.basket', 'salesman.checkout', 'salesman.orders', 'salesman.admin', 'rest_framework', 'wagtailmenus', 'wagtailthemes', 'wagtail.contrib.routable_page', 'cookielaw', 'analytical', 'wagalytics', 'wagtailfontawesome', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ['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.security.SecurityMiddleware', 'wagtail.contrib.legacy.sitemiddleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'wagtailthemes.middleware.ThemeMiddleware', 'django.middleware.locale.LocaleMiddleware'] Traceback (most recent call last): File "/opt/cms/.virtualenvs/wagtail/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2336, in to_python return uuid.UUID(**{input_form: value}) File "/usr/lib/python3.8/uuid.py", line 166, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') During handling of the above exception ('UUID' object has no attribute 'replace'), another exception occurred: File "/opt/cms/.virtualenvs/wagtail/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File … -
'Request' object has no 'accepted_renderer', djangorestframework-datatables
In my project, I wish to use djangorestframework-datatables to automatically paginate my jquery datatables. However, I have faced this error: "'Request' object has no 'accepted_renderer'. Here are the relevant codes: (Serializer, ViewSet, javascript) class MedicationStoreSerializer(serializers.ModelSerializer): container_photo = Base64ImageField() medicine_photo = Base64ImageField() class Meta: model = MedicationStore fields = ['senior_id', ...] ---------------------------------------------- class MedicationStoreViewSet(viewsets.ModelViewSet): queryset = MedicationStore.objects.all() serializer_class = MedicationStoreSerializer ---------------------------------------------- var gSeniorTb = $('#senior_participation_tb').DataTable({ "serverSide": true, "ajax": $ajax_summary_url, "columns": [ { "data": "id"}, ..., ] }) I've tried installing pyyaml from another question, it did not work. I have these basic REST framework settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_datatables.renderers.DatatablesRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination', 'PAGE_SIZE': 25, } -
django autocomplete light search not populating values
I am using django autocomplete light search for making searchable dropdown in my application but it is not populating values views.py from dal import autocomplete from .models import States class StatesAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = States.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs models.py class States(models.Model): name = models.CharField(max_length=200) modified_by = models.DateTimeField(auto_now=True) def __str(self): return self.name forms.py class RetailerForm(forms.ModelForm): name = forms.CharField(max_length=1000, required=True, error_messages={ 'required': 'Name is mandatory', 'max_length': ' Name cannot exceed 1000 characters' }, label='Name', widget=forms.TextInput(attrs={'class': 'form-control'})) state = forms.ModelChoiceField( queryset=States.objects.all(), widget=autocomplete.ModelSelect2( url='states_autocomplete', attrs={'class': 'form-control'}), label='State' ) urls.py from retail.views import StatesAutocomplete urlpatterns = [ path('states-autocomplete/', StatesAutocomplete.as_view(), name='states_autocomplete' ] Not sure why StatesAutocomplete is not working and populating values. -
Django DetailView pk error: can't match the last one
My new to django. I am creating a simple model for my to do app in django. Here, I have used DetailView to get the details and using the int "pk". When I'm running my server the /task/1/ is working fine but when I'm running task/2/ to check the other task it is shwoing this error: error My views.py: views.py My app urls.py: urls.py template of detailview See, when I'm running task/1/ there's no error: task/1/ -
HTML tags in string are getting printed in web page
I am using Elasticsearch highlighting which returns string with highlighted text between html tags e.g. { field: "\<b> highlighted text \</b>" } Now I need to print this on web page using django , the <b></b> tags are also getting printed in the web page. Sample code snippet for html page is like this <body> {% for result in results %} <div> Result : {{ result.field }} </div> {% endfor%} </body> I want the highlighted text to be printed in bold , but the tags are getting printed instead. -
Django hosting static files in AWS S3 causing CORS error when trying to access admin font files
I setup Django to store all static files on S3 and with the "collectstatic" command, all the admin files where copied and when I visit the admin site the CSS and JS files are sourced from the S3 bucket correctly. For example: https://bucket.s3.amazonaws.com/static/admin/css/base.css https://bucket.s3.amazonaws.com/static/admin/js/vendor/jquery/jquery.js But when it tries to access the Font files .woff I get the following error: Access to font at 'https://bucket.s3.amazonaws.com/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. It's weird that it gives me access to all the files except the font files: -
How to delete selected Cart Item using Django rest framework?
I'm using Django as backend, PostgresSQL as DB and HTML, CSS and Javascript as frontend I'm calling Django API with the help of Javascript to show the cart item to authenticated user serializer.py from .models import * from rest_framework import serializers class productserializers(serializers.ModelSerializer): class Meta: model = Cart fields = '__all__' depth = 1 views.py @api_view(['GET']) def showproduct(request): if request.method == 'GET': result = Cart.objects.filter(user = request.user) serialize = productserializers(result, many = True) return Response(serialize.data) main.js $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showdata', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td style="font-style:bold">' +data[i].product.name+'</td><td style="font-style:bold">' +data[i].product.price+'</td><td><a href=' +data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><a href='#'><button type="button" class="btn btn-outline-danger">DELETE</button></a></td></tr>'); $("#tableProduct").append(row); } } }); }); Well, from above code on main.js ... <td><a href='#'><button type="button" class="btn btn-outline-danger">DELETE</button></a></td> ... In this line I want to implement delete function. Where user can delete the selected item from cart. So, How to implement delete function that can delete the item from cart and show the response in Template. -
Aplhanumeric range between 2 input values
Hi guys i need help with generating field values between alphanumeric input in javascript. i have 2 input fields UIV = with range (C0, C1, C2, C3, C4, C5, C6, C7, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, T1, T2, T3, T4, T5, S1, S2) LIV = with range (C0, C1, C2, C3, C4, C5, C6, C7, L1, L2, L3, L4, L5, L6, L7, L8, L9, L10, L11, L12, T1, T2, T3, T4, T5, S1, S2) vertebra = the range between UIV and LIV i want to be able get the values between for example vertebra= C0, C1, C2, C3 if UIV = C0 LIV= C3 or vertibra = C0, C1 if UIV = C0 and LIV=C1 I need help using javascript or python -
Passing a String from an HTML input to a python script back out to the webpage using Django
Ok! I'm a noob to Django so please forgive me. I am trying to learn django and I am attempting to pass a string from an input in my html frontend to a python file/function which contacts google api and then I would like that information spit out back onto the webpage. Right now I can't figure out how to get the function to work. Or, Idk what I'm doing wrong. Here is my views file from templates.pyfile.pyapi import Api from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Tube from templates.pyfile import pyapi # Create your views here. def tubeView(request): search = Tube.objects.all() return render(request, 'home.html') def search(request): kw_list = request.POST['content'] new_search = Tube(content=kw_list) new_search.save() print(kw_list) reApi().main(kw_list) return HttpResponseRedirect('home/') Here is my python file from googleapiclient.discovery import build from pytrends.request import TrendReq import matplotlib.pyplot as plt import pandas as pad import time pytrends = TrendReq() class Api(): def main(x): self.searchAPI(c) def searchAPI(self, kw_list): pytrends.build_payload(kw_list, cat=0, timeframe='today 1-m', geo=country_var, gprop='youtube') data = pytrends.interest_over_time() mean = data.mean() print(mean) plt.plot(data) plt.savefig('Plotzz.png') plt.legend(kw_list, loc='upper left') I'm new so please be easy but can anyone help guide me in the right direction? I've been reading all day and cant figure it out. … -
Testing with RequestFactory seems to pass for non existing route
I'm trying to verify if accessing routes of my Django application would return a 200 status code. As I was writing repetitive test code, I search for some options and found that I could use RequestFactory with a mixin. But what I'm not understanding is why the test is not failing for a non existing route. I have a class-based view called IndexView which I'm trying to test, but the idea is to use the mixin to test others as well. The tests below will consider a non existing route called i-dont-exist: Using client What I see here is that I'm not using an instance of my view inside the test yet, but only the get to i-dont-exist route. from django.test import TestCase, RequestFactory from .. import views class ExampleViewTest(TestCase): def test_if_route_exists(self): response = self.client.get('/i-dont-exist') status_code = response.status_code self.assertEqual(status_code, 200) Running python3 manage.py test: ====================================================================== FAIL: test_if_route_exists (page.tests.test_views.ExampleViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "xxxxx/page/tests/test_views.py", line 15, in test_if_route_exists self.assertEqual(status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.014s FAILED (failures=1) Using RequestContext Now I'm using my class-based view inside the test. class ViewMixinTest(TestCase): def setUp(self): # Every test needs access to the request factory. self.factory = … -
Create accounts and API tokens for live mode and test mode
I want to create a system that works similar to stripe. There'll be live API keys, as well as test API keys. I have been thinking of how to implement this architecture, and I am not sure the best way to go about it. I found a similar question on this but it didn't help much. Architecturing testmode/livemode using OAuth 2 token My current progress is basically: I have decided to use https://github.com/James1345/django-rest-knox instead of DRF's default authtoken because knox supports multiple token creation and I thougt I needed that feature. I intend to create tokens as pub_key_<token> and test_key_<token> and remove or strip the prefix before authentication I intend to create a LiveAccount Model and a TestAcoount model. However, after authenticating the request from a test api token, it's unclear how to route or perform requests to TestAcoount instead of LiveAccount. Please any ideas or a better implementation strategy is highly welcomed -
Writes id instead of name
I am new to Django, I have such a problem that Id is written instead of the category name, how can this be solved? Attached code, code not complete (only used part). I don't know how to do it anymore, most likely the problem is in views.py model.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE) PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] title = models.CharField(max_length=50) positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle) data = models.DateTimeField(auto_now_add=True) postCategory = models.ManyToManyField(Category, through='PostCategory') previewName = models.CharField(max_length=128) text = models.TextField() rating = models.SmallIntegerField(default=0) def like(self): self.rating +=1 self.save() def dislike(self): self.rating -=1 self.save() def preview(self): return self.text[0:124] + '...' def __str__(self): return self.title class Meta: verbose_name = 'Пост' verbose_name_plural = 'Посты' def get_absolute_url(self): return f'/news/{self.pk}' class PostCategory(models.Model): pcPost = models.ForeignKey(Post, on_delete=models.CASCADE) pcCategory = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: verbose_name = 'Пост категория' verbose_name_plural = 'Пост категории' def __str__(self): return f'{str(self.pcPost)}, имеет категорию {str(self.pcCategory)}' views.py I think the mistake is here class new(LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Post template_name = 'new_home.html' context_object_name = 'new' permission_required = … -
get distinct "title" in mysql in django
I have used django to develop a web app. I want to get the distinct "title" form the queryset get by filter. But I use mysql so could not pass "title" to distict. How could I filter the queryset with the distinct "title"? query_set = CourseInfo.objects.filter(discipline_id=id).distinct('title') return render(request, 'main.html', context={'query_set':query_set}) I get error for this in mysql as it may only used in postgresql ` -
When do we get https response 377?
I am using bunny CDN to redirect to my API endpoint and it worked initially for some time now it has been throwing http response 377. I have not found any explanatory answer for such https response. -
ListView can not return to other page. NameError
I have made ListView, it has "Try and Except block" When it passes try block, it shows listview with SQL data. but when it does not, I want to let the user go to another page (cancel.html). Here is my code. view.py class DbList(ListView): def get_queryset(self): try: subscription = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId) print(subscription.status) if subscription.status == "active": sql = 'select * from test_eu' msg = "abcdefg" sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " object_list = TestEu.objects.raw(sql) return object_list except: return render(request, 'cancel.html') The error message is NameError name 'request' is not defined So I tried to change the code return render(request, 'cancel.html') to return render(self.request, 'cancel.html') Then another error message occurred. TypeError object of type 'HttpResponse' has no len() How can I let the user go to another page in Listview?? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. -
Django return filtered manytomany field
class Person(models.Model): id = models.IntegerField(unique=True,null=False,primary_key=True,blank=False) name = models.CharField(max_length=10,null=False) username = models.CharField(max_length=10,unique=True) class Attend(models.Model): date = models.DateField() people = models.ManyToManyField(Person,related_name="attend",through='attendperson') i want to return Person with only filter Attend (by date ) for ex: p = Person.objects.get(id=1) #some code here to filter attend by *date* serial= PersonSerializer(p) #return Person with filtered Attend not all Attend Note: p.attend.filter(date__gte='2021-06-16') doesn't do the trick -
Django MySQL raw query does not return results
I'm trying to run a raw query in Django. I am not allowed to use ORM. I use Django MySQL backend. If I do basic queries, without parametrizing, the database returns results without problems. The query I want to run (not returning any results): from django.db import connection def get_data(variant): results = [] cursor = connection.cursor() cursor.execute("SELECT b.spec_id, b.h_loss, c.gen_type FROM `db-dummy`.spec_gen_data c JOIN `db-dummy`.gen_info a ON a.record_id = c.gen_id JOIN `db-dummy`.spec_data b ON b.record_id = c.spec_id WHERE b.h_loss = 1 AND (a.ref_gen = %s OR a.detail_ref_gen = %s) AND c.gen_type BETWEEN 1 AND 5 ORDER BY a.gen_name;", ('{}%'.format(variant),'{}%'.format(variant),)) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results Is there something wrong with the syntax? I am not getting any error, just results = [] after executing the query and I am sure that that query should return results.