Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery object has no attribute on_after_configure when trying to start the Celery workers
I want to start the Celery server but whenever I try to do so with celery -A app.tasks worker --loglevel=INFO I get AttributeError: 'Celery' object has no attribute 'on_after_configure'. The code below is defined in the root of the Django project, in a file called tasks.py. app = Celery("tasks", broker="redis://localhost") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(hour=23, minute=55), monthly_analytics.s(), ) sender.add_periodic_task( crontab(hour=23, minute=57), calc_average_rating.s(), ) sender.add_periodic_task( crontab(hour=5, day_of_month=1), per_view_payouts.s() ) -
Stripe Checkout - Capturing email and save it in django
My use case requires me to save the users email to a django session. However I don't want them inputting their email twice - in stripe checkout and in my django form. Ideally I want to grab the email they input when making their payment and save that to my django session. Here is my stripe payment.html: <a href="#" id="buy_now_btn" class="btn btn-primary">Buy Now</a> <script src="https://js.stripe.com/v3/"></script> <script> const buy_now_button = document.querySelector('#buy_now_btn') buy_now_button.addEventListener('click', event => { fetch('/checkout/') .then((result) => { return result.json() }) .then((data) => { var stripe = Stripe(data.stripe_public_key); stripe.redirectToCheckout({ // Make the id field from the Checkout Session creation API response // available to this file, so you can provide it as parameter here // instead of the {{CHECKOUT_SESSION_ID}} placeholder. sessionId: data.session_id }).then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `result.error.message`. }); }) }) </script> here is my view: def payment(request): return render(request, 'main/payment.html') From what I've seen in my attempts to solve this, it seems stripe obfuscates the info put in at checkout, so I am not sure it is even possible. -
Input type datetime-local won't save to database having field type datetime in Django
I have a form which has an input type of datetime-local. However, Im unable to process it in my views for saving to the database. Im not using Django forms. How can I do it please? Error message: "DateTimeField %s received a naive datetime (%s )" Here is my code snippet: html file <label>Scheduled Date and Time<label> <input type="datetime-local" id="test_datetime" name="test_datetime" id="test_datetime"> views.py def add_test(request, pid): if not request.user.is_authenticated: messages.warning(request, "Please login first") return redirect('login') if request.method == 'POST': test_datetime = datetime.strptime(request.POST['test_datetime'],'%Y-%m- %dT%H:%M') and it continues.... -
How can I change my project path on Django?
I have a Django project on an ubuntu server v20.04 with apache2. Whenever I run on local, I have to change the TEMPLATES Dir as follow: 'DIRS': ['templates'], Before deploying to the server I am rechanging again: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/crawl/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] There was no problem when I was using CentOs. After I move to ubuntu I have a path problem. I also add my WSGI and config file. WSGI: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = get_wsgi_application() Here is my config file for apache2: <VirtualHost xx.xxx.xxx.xxx:80> ServerName xxx.xxx.com DocumentRoot /home/crawl redirect permanent / https://xxx.xxx.com RewriteEngine on RewriteCond %{SERVER_NAME} =xxx.xxx.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost xxx.xxx.xxx.xxx:443> ServerName xxx.xxx.com DocumentRoot /home/crawl <Directory /home/crawl/project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess project processes=2 threads=12 python-path=/home/crawl:/home/crawl/venv/lib/python3.8/site-packages WSGIProcessGroup project WSGIScriptAlias / /home/crawl/project/wsgi.py #WSGIPythonPath /home/crawl/ <Directory /home/crawl/project > Require all granted </Directory> Alias /media/ /home/crawl/media/ Alias /static/ /home/crawl/staticfiles/ <Directory /home/crawl/staticfiles> Require all granted </Directory> <Directory /home/crawl/media > Require all granted </Directory> SSLEngine on SSLCertificateFile /etc/letsencrypt/live/xxx.xxx.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/xxx.xxx.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf ErrorLog syslog LogLevel emerg </VirtualHost> Do you have any suggestions to fix the path … -
Send Email with Django to contact
I am trying to send a templated email to a contact saved in a database. How can pre enter the email detail of the contact and remove the forms. I have tried to replace recipient = str(sub['Email'].value()) by recipient = str(sub['lead.id'].value()) but it didn`t work. views.py @login_required(login_url="/login/") def subscribe(request, lead_id): lead = Lead.objects.get(pk=lead_id) sub = forms.Subscribe() if request.method == 'POST': sub = forms.Subscribe(request.POST) subject = 'Introduction' message = 'Good morning,' recipient = str(sub['Email'].value()) send_mail(subject, message, EMAIL_HOST_USER, [recipient], fail_silently = False) return render(request, 'subscribe/success.html', {'recipient': recipient, 'lead': lead}) return render(request, 'subscribe/index.html', {'form':sub, 'lead': lead}) forms.py class Subscribe(forms.Form): Email = forms.EmailField() def __str__(self): return self.Email urls.py url(r'^(?P<lead_id>[0-9]+)/subscribe$', views.subscribe, name='subscribe'), Many Thanks -
Not redirecting from createView form to Home
I am learning fresh django development. Working on a blog project I am facing a issue that, while publishing a new blog, that doesn't redirects to home/blogs page. I tried to manually to go home It says, OperationalError at /blog/ no such column: App_Blog_blog.author_id I tried to debug several times, searched in documentation can't get away with this author_id. These are my codes: Views.py class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'App_Blog/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image',) def form_valid(self, form): blog_obj = form.save(commit=False) blog_obj.author = self.request.user title = blog_obj.blog_title blog_obj.slug = title.replace(" ", "-") + "-" + str(uuid.uuid4()) blog_obj.save() return HttpResponseRedirect(reverse('index')) class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name = 'App_Blog/blog_list.html' Views.py of main project file def index(request): return HttpResponseRedirect(reverse('App_Blog:blog_list')) urls.py from django.urls import path from App_Blog import views app_name = 'App_Blog' urlpatterns = [ path('', views.BlogList.as_view(), name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), ] models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField( upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title create_blog.html {% … -
django/css - where does the individual form fields like {{form.name}} etc. go in css form
I am trying to create a form using django and css. My Views.py looks like this - //MY VIEWS.PY LOOKS LIKE THIS from django.shortcuts import render from .forms import ContactForm # Create your views here. def home(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): pass else: form = ContactForm() return render(request, 'home.html', {'form':form}) My forms.py looks like this- //MY FORMS.PY LOOKS LIKE THIS from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length = 30) email = forms.EmailField(max_length = 254) message = forms.CharField(max_length = 2000, widget = forms.Textarea(),help_text = "Write Your Message here") def clean(self): cleaned_data = super(ContactForm, self).clean() name = cleaned_data.get('name') email = cleaned_data.get('email') message = cleaned_data.get('message') if not name and not email and not message: raise forms.ValidationError('You have to write something!') When I try to add the form to my html page like the following it doesn't show up. Just the button shows up, no form fields - {% extends 'store/main.html' %} {% load static %} {% block content %} <h3>Store</h3> <form method = "post" novalidate> {% csrf_token %} {{ form }} <button type='submit'>Submit</button> </form> {% endblock content %} If I do css form instead it obviously show up the way it should. {% extends 'store/main.html' %} … -
django cache expensive calculation into database
So I have models like this. class User(CoreModel, AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, verbose_name=_('email'), help_text=_("user's email address"), max_length=255 ) username = models.CharField( verbose_name=_('username'), help_text=_("display name"), unique=True, db_index=True, max_length=32, validators=( MinLengthValidator(2), UnicodeUsernameValidator ) ) avatar = models.ImageField( verbose_name=_('avatar'), help_text=_("user avatar"), upload_to='avatars/', default='avatars/default.jpg', ) is_verified = models.BooleanField( default=False, verbose_name=_('verified'), help_text=_("whether the user's email is verified") ) @property def space_used(self): output_field = models.DecimalField() aggregate = self.upload_set.aggregate( space=Coalesce( models.Sum('size'), models.Value(0), output_field=output_field ), ) return aggregate.get('space') class Upload(CoreModel): size = models.DecimalField( editable=False, verbose_name=_('size'), help_text=_("size in bytes"), max_digits=19, decimal_places=10, db_index=True ) name = models.CharField( blank=True, verbose_name=_('name'), help_text=_("upload name"), max_length=100, validators=( MinLengthValidator(2), ) ) parent = models.ForeignKey( to='uploads.Folder', verbose_name=_('folder'), on_delete=models.CASCADE, null=True, db_index=True ) owner = models.ForeignKey( to=settings.AUTH_USER_MODEL, verbose_name=_('owner'), on_delete=models.CASCADE, editable=False ) file = models.FileField( verbose_name=_('file'), help_text=_("raw file"), upload_to='uploads/' ) As you can see, the space_used property is an expensive operation. If the number of uploads per user increases, then more time will be taken to calculate. Actually, I use this property a lot via my serializers. So, what would be a better approach to improve performance? Have a db field called space_used and update it whenever an upload is created or deleted? Or is there any other better implementation? I don't want to use cached_property because … -
Django REST framework test case order
I want to test the APIs of a Django app. For example I have these APIs: /user/register/ /user/login/ I wrote test.py like this: class UserTest(APITestCase): def test_register(self): # ... # self.assertEqual( ... ) def test_login(self): # ... # login with registered user (test_register function) The test_register works properly but test_login does not work. The user that I created in test_register not exists in database when test_login running. How can I keep the state of database in test process? And how can I set the running order for test class? -
Filter recipients based on ingredients in a panty
so I am trying to create a filter in Django which will be able to return all recipes based on what ingredients a user has in their pantry. So for example: if a user has tomatoes, onions and cabbages in their pantry, the filter should return all recipes with the three listed recipes. I do know this will be a many to many relationship but am confused how to get started and filter recipes based on the multiple ingredients in the pantry. Any help would be appreciated. Thank you -
Trigger a function in Javascript when the Django database get altered
I want a clients browser to run a Javascript function when a row in my Django database gets altered. I am using Django 3.2 and I have hosted my website in Linode using apache2. In simple terms, I want my web browser, to continuously run the query Order.objects.filter(pk=20).first().paid where paid is a boolean value. As soon as the value changes from false to true I want my Javascript to run a specific function. How should I approach this situation, I would like if someone could explain to me a concept and the logic behind this method a what technologies should I use behind this. Do I need to use WebSockets? If so how do I continuously query the database to check for the change? Any help is greatly appreciated! -
How do I upload (image) file to Django server via http?
I have a Django server where I can create a new object of class "Picture", which contains class Picture(models.Model): artist_id = models.ForeignKey(ArtistProfile, on_delete=models.CASCADE, null=True) image = models.ImageField(max_length=255, null=False, upload_to="images/") description = models.TextField(null=True, blank=True) *some other fields* I can create new object via Admin page (admin/main/picture/add/). After uploading the image is stored on server and everything works great. Now I want to create a new object from API client (Android app). How do I send POST request, that contains cookies, basic string fields (artist_id/description/...) and image field? How exactly image field looks like, "image" : "BYTE_ARRAY_OF_IMAGE_FILE"? I use okhttp3 (Android app) for other simple get/post requests and cookie handling -
Django root path not found after adding handler404
I added a handler404 to my project and it immediately broke the root path and the 404 page is shown. I wonder how I need to change my urls.py to make it work correctly with i18n_patterns. I would appreciate any advice on the issue. The URLs with the language prefix work fine. mysite.com 404 why???? mysite.com/en/ OK mysite.com/fr/ OK mysite.com/gffg 404 Here's the urls.py of my project. urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), #apps path('', include('apps.webapp.urls')), path('user/', include('apps.userapp.urls')), path('client-area/', include('apps.accountapp.urls')), #additional paths path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('ckeditor/', include('ckeditor_uploader.urls')), path('rosetta/', include('rosetta.urls')), ) + [ path("robots.txt", TemplateView.as_view(template_name="web/robots.txt", content_type="text/plain"),), ] handler404 = 'apps.webapp.views.handler404' -
Jquery can't add class to dynamicly added nav-link
I have a JQuery code that adds a nav-link dynamicly to a nav-item. The problem is this nav-link doesn't change to active when clicked. I tried to dynamicly give it the active class but it doesn't take it. it seems after the page reloads everything is rest and it's always the first nav-link that takes the active class. Here's the navbar code : <div class="collapse navbar-collapse mt-5 h-100 justify-content-between" id="navbarsExampleDefault" > <ul class="navbar-nav accordion" id="SideBar"> <li class="nav-item"> <a class="nav-link" href="{{index}}">home</a> </li> <li class="nav-item"> <a class="nav-link" href="{{list}}" >list</a> </li> <li class="nav-item"> <a class="nav-link dropdown-toggle" href data-toggle="collapse" data-target="#A" aria-controls="collapseOne" > A </a> </li> <ul class="collapse" id="A" data-parent="#SideBar" > <li class="nav-item"> <a class="nav-link" href="{{B}}" >B</a> </li> <li class="nav-item"> <a class="nav-link" href="{{C}}" >C</a> </li> </ul> And for JQuery here's what I'm doing $('#A').append( '<li class="nav-item">' +'<a class="nav-link" href="{{dynamic_link}}?id=1" >Dynamicly Added</a>' +'</li>') ; $( document ).on( 'click', '.collapse li', function ( e ) { $( this ).addClass( 'active' ).siblings().removeClass( 'active' ); It's of course wrapped inside $(documen).read(). I also tried to wrap it inside $(window).load() but same problem. If you can spot the problem I'd appreciate your guidance. -
Django error: cannot cast type date to time without time zone
Please help me with this error: File "/Users/ecommerce/proshopvenv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.CannotCoerce: cannot cast type date to time without time zone LINE 1: ..." ALTER COLUMN "createdAt" TYPE time USING "createdAt"::time The above exception was the direct cause of the following exception: "a lot of code, and:" django.db.utils.ProgrammingError: cannot cast type date to time without time zone LINE 1: ..." ALTER COLUMN "createdAt" TYPE time USING "createdAt"::time In models i have: createdAt = models.DateTimeField(auto_now_add=True) and how i understand from docs https://docs.djangoproject.com/en/3.2/ref/models/fields/ "The auto_now and auto_now_add options will always use the date in the default timezone at the moment of creation or update." But zone doesn't create, or error in something else, i creating new database, so i can delete all tables Maybe there is step in django where it initials time zone? Readed this topic postgreSQL alter column data type to timestamp without time zone and many others but can't fix it to 'migrate' without errors -
How to add conditions in Q objects search
how do i filter my objects if user entered product_length 10 than my objects should return length is greater than equal to 10 for example i am using Q objects to filter out my data. in my views.py def search(request): query=request.GET.get("q").lower() post = CreateIndustrialPost.objects.filter( Q(product_length__icontains=query,admin_approval=True,user_remove_post=False) ).values() in this it returns all data i want to filter as above mention. -
page not found error ,even though I have that page in url code
THIS IS THE ERROR IM GETTING: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Raised by: django.views.static.serve Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin/ ^(?P.*)$ The empty path matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. THIS IS MY URL/ SETTINGS file code: settings: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'jobs.apps.JobsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'portfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', … -
Django moving javascript code and form outside a for loop
using django, I want to create a popup modal form when someone clicks on delete. I’m trying this thing I got from here : https://www.w3schools.com/howto/howto_css_modals.asp The problem is that I don’t want to repeat that form and js code on each for loop item, I want it outside the loop with a unique product pk or id on each click here my is html code: {% extends 'base.html' %} {% block content %} <div class="container"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li> {% endfor %} </ul> {% endif %} <div class="grid-container"> {% for product in products %} <div class="grid-item"> <div> <img src="{{ product.image_url.url }}" alt="{{ product.title }}"> <h5>{{ product.title }}</h5> <!-- DELETE Trigger/Open The Modal --> <button id="myBtn">Open Modal</button> </div> </div> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <h1>are you sure you want to delete: "{{product.title}}"؟</h1> <form class="form_container" enctype="multipart/form-data" action="{% url 'delete' product.pk %}" method="post"> {% csrf_token %} <label for="pincode">enter your code to delte:</label> <input type="number" id="pincode" name="pincode"> <input type="submit" name="Confirm" value="delete"> </form> </div> </div> <script> var modal = document.getElementById("myModal"); // Get the button … -
Django actions on admin re-query SQL so time waiting is double
I have model using the DjangoQLSearchMixin for filtering class FollowerAdmin(DjangoQLSearchMixin, NumericFilterModelAdmin, SpecialActions): and I use also def get_queryset(self, request): I get the results on the admin page, later I export to csv using : But it do the sql query over again after I export. Any idea Y ? -
StreamingHttpResponse not working with ASGI but work fine with WSGI
I'm trying to use channels for some WebSockets-related stuff, but it keeps loading and not showing any streaming response when I reload my web page. Here is my code which works fine with this setting: # settings.py # WSGI_APPLICATION = 'main.wsgi.application' # work fine ASGI_APPLICATION = "main.asgi.application" # not working And here is my views.py: @gzip.gzip_page # for performance def video_stream(request: HttpRequest): video = VideoContainer.objects.last() video_path = video.file.path return StreamingHttpResponse(generate_frames(VideoCamera(video_path)), content_type="multipart/x-mixed-replace;boundary=frame") Here is my code for generate_frames and VideoCamera: import cv2 class VideoCamera: def __init__(self, video_path: str): self.video = cv2.VideoCapture(video_path) def __del__(self): self.video.release() def get_frame(self): while (self.video.isOpened()): img = self.video.read()[1] # because web-page looking for image/jpeg content type jpeg = cv2.imencode(".jpg", img)[1] return jpeg.tobytes() # we stream it in byte form for frontend def generate_frames(camera) -> bytes: while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') -
When creating a package, how do I manage migrations of a weak dependency?
I have a Django app that I would like to package and offer the community through Pipy. Its only strong dependance is Django. It also integrates nicely with Django CMS and offers additional integration for Django CMS. I plan to offer this additional functionality only to projects with Django CMS installed. (This is what I call a weak dependency - will install and work without it, but work even bitter with it.) Specifically, some models are only defined if the base model CMSPlugin from Django CMS is installed. Is there a good/right way to manage migrations, though? I cannot include migrations of models depending on CMSPlugin in the package since users w/o a Django CMS installations will not be able to run it. If I omit the migrations depending on CMSPlugin users with Django CMS will create them on first installation. I fear, however, that on every update of the package those migrations will be lost on pip install upgrade when the package is overwritten. -
Incorrect string value: '\\xF0\\x9F\\x88\\xB2\\xE4\\xB8...' for column 'welcome_msg' at row 1
I got this problem when saved the object by Django. I have checked my table CharSet, As the following picture. I dont know why this happen, Thanks for any ideas! -
django rest framework how to check if phone already exist?
I want to check if phone number is already existing or not. My serializer class teacherInfoCustomSer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['first_name', 'last_name', 'phone'] apiView def teacherInfoCustom(request, pk): custom = CustomUser.object.get(id=pk) serializer = teacherInfoCustomSer(instance = custom, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) and my JS let data1 = JSON.stringify({ "first_name": tch_name.value, "last_name": tch_lastname.value, "phone": tch_phone.value }) const teacherInfoCustom = ('/p/teacherInfoCustom/' + "{{ request.user.id }}") fetch(teacherInfoCustom, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: data1, }).then((response) => { console.log(response) }).catch(err => { console.log(err.response.message) }) In model's phone field phone = models.CharField(max_length=15, unique=True, blank=True, null=True) and if a phone number already exist it won't give me status 400 but gives status 200 and it didn't save(i think because I set unique=True in my model). And if I enter phone number that didn't exist it will save. -
ValueError: The view did not return an HttpResponse object
I am writing a Django server. I had to use generic views for my API class. Now, Whenever I test the code using postman, everything works fine. But if I test it using other clients like Talend API tester or my Chrome browser, it returns 500 Error saying API did not return any HttpResponse object. Here's my skeleton codebase @method_decorator(csrf_exempt, name='dispatch') class ClassName(View): @throttle def post(self, request) -> JsonResponse: try: data = (json.loads(request.body)) except JSONDecodeError: # decoding error of Json File. msg = "An error occurred while decoding the input" return message_handler(msg, 500) ...... some other application logic ...... return JsonResponse({ "status": True, "message": "", }, status=200) All of my API is using the same format, they are returning a JsonResponse, so what am I doing wrong? -
How to give priority to a certain field in SearchFilter fields in django rest framework?
I have a simple search api which search the db based on the query parameter provided to the search keyboard. It works fine, but it has some issues. For example, I have a category named Tv and home appliances. It has products like LG speakers and led tv. I have search qeury parameters for both category name and product name. When I search tv, speaksers products are coming in the first page while tv products are coming in the 5th page which I dont want. It is because, category name has Tv and Home. What I want is tv prodcuts to be appear in the first page while speakers to the other pages. For this I have to prioritise the product name field rather than category name. How to do that?? { id:1 category: TV and Home, product: 1500 W Speakers } { id:2 category: Tv and Home, product: Led Tv 32" } I want id:2 to be appeared first then, the id:1, if I search with Tv. class PrdouctSearchAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() print(queryset) serializer_class = ProductSerializer filter_backends = [SearchFilter,OrderingFilter] search_fields = ['name','brand__name','collection__name','sub_category__name', 'description','variants__color','category__name'] pagination_class = CustomPagination My local endpoint is: http://127.0.0.1:8000/api/productsearch?search=tv My model: class Product(models.Model): merchant …