Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django+Bootstrap4 raise Error: "mysqlclient 1.4.0 or newer is required; you have 0.10.0."
I Use Django 3.1.2 with MySQL, and it worked normal with database. But affter i've installed Botstrap 4 (pip install bootstrap4) and load it in my Tamplate {% load bootstrap4 %} i get Error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.0. raised by bootstrap as you can see bellow. But in my venv i have installed module mysqlclient version 2.0.1 (not 0.10.0). (As PyCharm show me.) I don`t understend it. And how css/js library like bootstrap even apply to Database engine? How to solve it? "C:\Program Files\JetBrains\PyCharm 2019.3.3\bin\runnerw64.exe" C:\MyProject\venv\Scripts\python.exe C:/MyProgect/MySite/manage.py runserver 8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\User\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line … -
ERROR: Failed building wheel for cryptography
Hey guys I was installing "channels" "pip install channels" but I received this Error. Failed building wheel for cryptography Running setup.py clean for cryptography Failed to build cryptography Could not build wheels for cryptography which use PEP 517 and cannot be installed directly What should I do now? -
how to update with a foreign key field that also has a foreign key field
I have three sample models below: Class User(Model): ...some other fields receiving_info = OnetoOneField('ReceivingInfo') Class ReceivingInfo(Model): ...other fields receiving_address = OnetoOneField('Address') Class Address(Model): street = CharField(max_length=100) house_number = CharField(max_length=100) city = CharField(max_length=200) I am trying to update them below using this: address = Address( street='new st', house_number='new number', city='new city' ) user = User.objects.get(id=id) user.receiving_info.receiving_address = address user.save() but somehow it doesn't work, any ideas how to make it work? -
How to retrieve user id from token?
There is a Plan model that has a user field and I want to fill the user field with user's token so that user can not send user id to create the model for another user and just send post request for themself, here is my model: class Plan(models.Model): """Plan object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) and my view is: class PlanViewSets(viewsets.ModelViewSet): """A viewset for non-admin user see list and admin can curd plan model""" model = Plan queryset = Plan.objects.all().order_by('-id') serializer_class = serializers.PlanSerializer permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def get_queryset(self): """retrieve plan just for its own user who is authenticated already""" return self.queryset.filter(user=self.request.user) How to create Plan just for user without getting user field by request body? -
django-haystack not removing stale record when used with django-safedelete
I use django-haystack 2.5 with Django 1.11 and elasticsearch 2.3. I have some indexed models that use django-safedelete. This means that rather than deleting the object, I mark them as deleted with a flag on the object. In my haystack search index, I have specified the queryset to exclude the "deleted" items, of course. However, if I update_index --remove, the stale records are not deleted, so they are returned in search results as they were indexed before they got deleted. Any suggestions on how to solve this issue? Thanks! -
how to get the slug from object name in django
hey i want to get the slug from my product name automaticlly forexamle if my product name is (product number one) i want the slug be(product_number_one) how can i do thaat? here is my code : models.py class Product (models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) description = models.TextField(null=True, blank=True) color = models.ForeignKey(Color , on_delete=models.DO_NOTHING) material = models.ForeignKey(Material, on_delete=models.DO_NOTHING) image = models.ManyToManyField(Image) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING , default=0) slug=models.SlugField(max_length=300 , allow_unicode=True , blank=True , null=True , unique=True,) view = models.IntegerField(default=0) def __str__(self): return self.name -
How to write JS that will count date and change table color?
i need a JavaScript that counts date between an input and another input. If result is smaller then 24 hours, table row needs to be colorized as red. I'll give some codes below; class Campaigns(models.Model): start_date = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Starting Date") end_date = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Ending Date") broadcast = models.CharField(choices=BROADCAST_STATUS, blank=False, verbose_name="Broadcast Situtation", max_length=10) This is my table rows : {% for campaign in campaigns %} <tr> <td class="text-center">{{ campaign.agency }}</td> <td class="text-center">{{ campaign.brand }}</td> <td class="text-center">{{ campaign.channel }}</td> <td class="text-center">{{ campaign.target_group }}</td> <td class="text-center">{{ campaign.start_date }}</td> <td class="text-center">{{ campaign.end_date }}</td> <td class="text-center">{{ campaign.date_to_take_place }}</td> <td class="text-center">{{ campaign.day_part }}</td> <td class="text-center">{{ campaign.impression }}</td> <td class="text-center">{{ campaign.broadcast }}</td> </tr> {% endfor %} So what i need as mathematic is : campaign.start_date - campaign.end_date = result , if result < 24 hours , table row color becomes red. Thanks for any tip/solution! -
Django forms: how to get product's data from db with ajax
I have models (ShopStock and SaleItem), I have registered product and price in ShopStock model, in SaleItem model i also have product and price fields. What i want is when i select a product in (SaleItemForm) the price field to be filled with a price from Shopstock model. I have no idea how to do it in javascript. Models class Product(models.Model): name = models.CharField(max_length = 100, blank=True) class ShopStock(models.Model): products = models.ForeignKey(Product, null=True, blank=True, on_delete = models.SET_NULL) price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) class SaleItem(models.Model): product = models.ForeignKey(ShopStock, null=True, blank=True, on_delete = models.SET_NULL) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) I tried this to solve my problem but it's not working Views def price(request): if request.method == 'GET': total_price = SaleItem.price response_data ={} response_data['price'] = total_price return JsonResponse(response_data) Templates $(document).ready(function() { $('#id_product').change(function(){ var query = $(this).val(); console.log(query); $.ajax({ url : "/price/", type : "GET", dataType: "json", data : { client_response : query }, success: function(json) { document.getElementById('id_price').value=json.price; }, failure: function(json) { alert('Got an error dude'); } }); }); }); Forms class SaleItemForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=ShopStock.objects.all(), widget=forms.Select(attrs={'class':'form-control', 'id':'id_product'})) class Meta: model = SaleItem fields = ['product', 'quantity', … -
create, download PDF and return form on submit with Django
For a small project i want users to fill in a form and when they submit, it has to download a PDF with the form data & return them to the same page. But i'm not sure how to achieve this. Im using a generic CreateView and a createPDF() function. This is what i've tried so far: class FormView(CreateView): model = ExampleModel succes_url = reverse_lazy('Create') fields = ["first_name", "last_name"] def form_valid(self, form): formData = form.save(commmit=False) first_name = formData.first_name last_name = formData.last_name createPDF(requests, first_name, last_name) return super().form_valid(form) def createPDF(request, first_name, last_name): buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(15, 800, first_name, last_name) p.showPage() p.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='example.pdf') The problem here is that i dont see any errors, so i'm not sure what's going wrong. With the code above users can fill in the form and when they submit, they will return to the form again, which is good, but unfortunately the PDF file never downloads.. what is going wrong here? appreciate any help :) -
Azure AD token to connect SQL Server - Django
I have successfully connected the Azure SQL Server using AccessToken in the pyodbc. Here I didn't use username or password to connect the DB. conn = pyodbc.connect(connString, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:tokenstruct}); #sample query using AdventureWorks cursor = conn.cursor() cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid") row = cursor.fetchone() while row: print (str(row[0]) + " " + str(row[1])) row = cursor.fetchone() Reference Link: https://github.com/felipefandrade/azuresqlspn Now the problem is how to use this in the Django framework? We can't have a username or password to connect the database when using azure token. -
Bootstrap table not allow clicks (link) on search or filter result
I am new to Bootstrap table and use this https://codepen.io/AurelieT/pen/JGxMgo example and added click function which working fine until I apply any bootstrap features such as filtering, search, pagination, and others after applying any bootstrap features not able to click as before my table-row function not work, and not able to get table row id for selected checkbox its only show ('btSelectItem': ['on', 'on']) on Django View console instead of table id or name once click some button. <td class='table-row' data-href="{% url 'detail' item.slug%}">{{ item.item_name }}</td> my css style .table-row{cursor:pointer;color: blue;} query for click $(document).ready(function($) { $(".table-row").click(function() { window.document.location = $(this).data("href"); }); }); Appreciate your help and advice. -
Paginating in ListView django
I am trying to paginate data in my table in html template, but it is not working. I am using default paginate system from list views. Also I have a form in which user can pass items per page value. This is my code for views.py: def get_paginate_by(self, queryset, **kwargs): itemsForm = ItemsPerPageForm(self.request.GET) if itemsForm.is_valid(): itemsPerPage = itemsForm.cleaned_data.get('items_per_page') print(itemsPerPage) if itemsPerPage is None: return 4 else: if itemsPerPage > 0 and itemsPerPage <= Category.objects.get_queryset().count(): return itemsPerPage else: return 4 And this is my django template: </table> <tbody> {% for category, expenses in noOfExpenses %} <tr> <td>{{ page_obj.start_index|add:forloop.counter0}}.</td> <td>{{ category.name|default:"-" }}</td> <td>{{ expenses }}</td> </tr> {% empty %} <tr> <td colspan="6">no items</td> </tr> {% endfor %} </tbody> </table> <hr/> {% include "_pagination.html" %} {{page_obj}} <form method="get" action=""> {{itemsForm.as_p}} <button type="submit">submit</button> </form> And _pagination.html: <div class="pagination"> <span class="pagination__nav"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} <br/> Total items: {{page_obj.paginator.count}} </span> </div> So in the end, on the website, despite that I have only 4 items, I have 2 … -
os.path.join('BASE_DIR','template') problem
When i run following code In settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', **'DIRS': ['os.path.join('BASE_DIR','template') '],** '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', ], }, }, ] its shows an error template not found but when i execute following code in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', **'DIRS': ['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', ], }, }, ] this work fine!!! what this os.path.join('BASE_DIR','template') actually means?? Thanks in advance!!!! -
Django - My key object id jumped from 11 to 44. Why?
I had added a few movies and their object ids were sequential: 1,2,3,4,5,6,7,8,9,10,11. But today I just added a new movie and the last one before it had 11 as id, but this new movie was given id 44. Why is this, why did it skip 12 and go all the way to 44? example.com/admin/movies/movie/1/change/ example.com/admin/movies/movie/2/change/ ... example.com/admin/movies/movie/10/change/ example.com/admin/movies/movie/11/change/ example.com/admin/movies/movie/44/change/ class Movie(models.Model): name = models.CharField(max_length=255) create_date = models.DateTimeField() owner = models.ManyToManyField(User) def __str__(self): return self.name -
React JS: How to pass static files to front-end (Django, React, Webpack) + ( no loaders are configured for .MP4 files )
I'm using a combo of Django + react js + webpack to build my application and I'm still really green on react js and webpack so I have no clue how to host or pass the files to frontend. So basically I don't pass the static files via django, and I don't have any configuration for static files in django. I'm trying to pass the static files which are in react js main directory. This is my project structure: And you can also see the webpack config that I have right now. But my question is how do I have to pass static files to react js? My code: import React from 'react'; import Video from '../videos/video.mp4'; import { HeroContainer, HeroBg, VideoBg } from './HeroElements'; const HeroSection = () => { return ( <HeroContainer> <HeroBg> <VideoBg /*src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4" */ src={Video} type="video/mp4" autoPlay loop muted /> </HeroBg> </HeroContainer> ) } export default HeroSection; -
Createing url paths with following integers Django
Trying to create a path such as hostname://homesapp/1/1 using regular integers for the first number and pk for the second, i know using re_path it would be similar to from django.contrib import admin from django.urls import path, include, re_path from .import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.LocationView.as_view(), name='property'), re_path(r'^([0-9]+)/(?P<pk>[0-9]+)/$', view.PropertyDetail.as_view(), name="propertyview"), ] but not sure about just using path for the final url -
TypeError: 'User' object is not iterable using Django
I am trying to route an AJAX GET request through views.py and return it to a template, but only show the object items connected with the logged in user. I am attempting to use filter() but am getting the following error: 'User' object is not iterable. Here is the views.py class: class user_playlist(ListView): template_name = 'testingland/dashboard.html' context_object_name = 'playlist' model = UserVenue def get_queryset(self): venue = self.request.GET.get('venue', None) list = self.request.GET.get('list', None) return UserVenue.objects.filter(self.request.user) Here is the template: <body> {% block content %} <div class="container-fluid" style="padding:15px"> <!--location --> <div class="row"> <div class="col-sm-3" id="playlist"></div> <ul class = "cafe-playlist"> {% for item in playlist %} <li> <div> <h6 class="playlist-name">{{ item.list }}</h6> </div> </li> {% endfor %} </ul> </div> {% endblock %} And here is the AJAX Call for good measure: //dashboard $(document).ready(function(){ console.log('Document Ready') $.ajax({ type: "GET", url : '/electra/playlist', dataType: "json", data: { 'venue': 'venue', 'list': 'list', }, success: function(data){ $("#playlist").html(data); console.log(data) }, failure: function(errMsg) { alert(errMsg); } }); }); For those interested here is the full traceback: Internal Server Error: /electra/playlist Traceback (most recent call last): File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get _response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users//Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/views/generic/base.py", line … -
Django REST Framework view permissions not called
I am trying to create a custom permission for my view that allow read and write permissions to the owner of the model in the QuerySet but do not allow any permission/request to other users or un-authenticated ones. Source: https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ View: class My_classListCreateAPIView(generics.ListCreateAPIView): queryset = Model.objects.all() serializer_class = ModelSerializer permission_classes = [IsModelOwner] Permission: class IsModelOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Permissions are only allowed to the owner of the model and admins. if request.user.is_staff == True: return True return obj.owner == request.user unfortunately it seems that my view is not even calling my custom permission class. (I imported it etc.) If instead of my custom permission class, I use a default one like permissions.isAuthenticatedOrReadOnly that works instead. What am I missing here? Thanks. -
Django multiple sessions for same domain
I'm looking for a way to serve 2 independent Single Page Applications from different paths on the same domain, and have both of these talk to 1 single Django backend. e.g. 2 independent Single Page Applications FOO webapp served at https://app.com/foo/ BAR webapp served at https://app.com/bar/ 1 Django backend served at https://api.app.com/ It seems an odd requirement to me, but that's not in my control. Unless there is a real technical limitation here that's the approach I have to take. I'm unsure how this could work, particularly in terms of sessions. Django uses a cookie to track sessions. This cookie is called sessionid by default, and that can be controlled by the SESSION_COOKIE_NAME setting. I think a sensible approach would be to have 2 separate session cookies, foo_sessionid and bar_sessionid in the example above. I'm not sure if there is a way to do this and would grateful for any insights. -
Shopify Public App Access to Discount Code API
I am using the python-shopify library and django to build a shopify app, using this. I wanted to retrieve all the discount codes currently in place on my development store, using the following code: discounts = shopify.PriceRule.find() But I have the following error being thrown out. This action requires merchant approval for read_price_rules scope python shopify Please help -
find MAX,MIN and AVG of a set in Django
I have an object called meter and it has a set called powerConsumptionReport_set. This is the models.py : class Meter(models.Model): region = models.PositiveSmallIntegerField(null=1) IPAddress = models.GenericIPAddressField(default=0,null=False,blank=False,unique=True) PortNumber = models.IntegerField(default=1024) SerialNumber = models.IntegerField(default=00000000,null=False,blank=False,unique=True) class PowerConsumptionReport(models.Model): meter = models.ForeignKey(Meter, blank=True, null=True, on_delete=models.CASCADE) power = models.FloatField() I need to find Max value of power field from the powerConsumptionReport_set and display it in my template. This is the DetailView i used to show each Meter : class MeterDetailView(DetailView): model = Meter template_name = 'meter/specificMeter.html' And the template is here: <h1 class="card-text text-md-center"> *** here i want to show min value of the set **** - {{ meter.powerconsumptionreport_set.first.power }} </h1> how can i access Max,Min and AVG value of power field from the powerConsumptionReport_set related to each meter. Cheers. -
How can i remove videos from later for individual users?
views.py here in views.py i have tried to make logic for remove any song from watch later but, i am not able to build logic for it.Basically dont know how to bring watch_id(primary key) of my watch later model. def deletewatchlater(request): if request.method=="POSt": user=request.user video_id=request.POST['video_id'] # watch_id=request.POST['watch_id'] wat=Watchlater(user=user,video_id=video_id) wat.delete() messages.success(request,"Song delete from watch later") return render(request,'watchlater.html') def watchlater(request): if request.method=="POST": user=request.user video_id=request.POST['video_id'] watch=Watchlater.objects.filter(user=user) for i in watch: if video_id==i.video_id: messages.success(request,"Song is already added") break else: wl=Watchlater(user=user,video_id=video_id) wl.save() messages.success(request,"Song added to watch later") return redirect(f"/index/subpage/{video_id}") wl=Watchlater.objects.filter(user=request.user) ids=[] for i in wl: ids.append(i.video_id) preserved=Case(*[When(pk=pk,then=pos) for pos,pk in enumerate(ids)]) song=Allmusic.objects.filter(sno__in=ids).order_by(preserved) return render(request,'watchlater.html',{'song':song}) urls.py I have made post request for it when user clicks button remove from watch later than it will send details of user and song_id and watchlater id from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('postComment',views.postComment,name="postComment"), path('',views.home,name='home'), path('index/',views.index,name='index'), path('indexmovie/',views.indexmovie,name='indexmovie'), path('index/subpage/<str:sno>',views.subpage,name='subpage'), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), #User Login Logout Signup path('signup',views.handleSignup,name='handleSignup'), path('login',views.handleLogin,name='handleLogin'), path('logout',views.handleLogout,name='handleLogout'), path('search/',views.search,name='search'), #User Saved path('index/watchlater',views.watchlater,name='watchlater'), path('index/history',views.history,name='history'), path('index/likedsongs',views.likedsongs,name='likedsongs'), path('index/deletewatchlater',views.deletewatchlater,name='deletewatchlater'), ] watchlater.html {% extends 'base.html' %} {% block title %} watch Later {% endblock %} {% block css %} <style> </style> {% endblock %} {% block body %} <h1 style="text-align:center;padding-top: 5%; "> WATCH LATER</h1> {% if song|length … -
Django: cannot render an empty modelform in template
I am trying to build a form that would let the user create one or many database table rows at once. Right now, what is being rendered from my view is the entire db table. I understand that it is a basic behavior of a modelform to return the entire db table data, but according to django docs there is a way to override the default behavior (https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/). That's what I tried to do but it does not seem to work, the entire db table keeps being rendered. here is what my view look like: def New_Sales(request): context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) if request.method == 'POST': formset = form(queryset= historical_recent_data.objects.none()) if formset.is_valid(): formset.save() for check_form in formset: quantity = form.cleaned_data.get('Quantity') id = form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F(StockOnHand) - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F(stock_reel) - quantity) return redirect('/dash2.html') else: form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) context['formset'] = form return render(request, 'new_sale.html', context) and my model: class historical_recent_data(models.Model): id = models.AutoField(primary_key=True, default= 0) Id = models.CharField(max_length=100, verbose_name= 'references') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) def __str__(self): return self.reference any help on this would be appreciated! -
Unable to login with correct username and password in Django with custom User model
I successfully created superuser and when I try to login it says your password is incorrect. I checked mu code and I tested it with deleting database and migrations and creating them again many times but couldn't figure out what is wrong. Here is my code From models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import MinLengthValidator class UserManager(BaseUserManager): def create_user(self, email, phone_number, first_name, last_name, social_id, password=None, is_staff=False, is_superuser=False, is_active=False): if not email or not phone_number or not first_name or not last_name or not social_id: raise ValueError('fill all the fields') if not password: raise ValueError('must have pasword') user = self.model( email = self.normalize_email(email), phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id ) user.set_password(password) user.is_staff = is_staff user.is_superuser = is_superuser user.is_active = is_active user.save(using=self._db) return user def create_staffuser(self, email, phone_number, first_name, last_name, social_id, password=None): user = self.create_user( email, phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id, password=password, is_staff=True, ) return user def create_superuser(self, email, phone_number, first_name, last_name, social_id, password=None): user = self.create_user( email, phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id, password=password, is_staff=True, is_superuser=True, ) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=False) last_name = … -
ContentNotRenderedError: The response content must be rendered before it can be iterated over. Django REST
I am getting an error : The response content must be rendered before it can be iterated over. What's wrong with below line of code..?? if anybody could figure out where i have done mistakes then would be much appreciated. thank you so much in advance. serializers.py class GlobalShopSearchList(ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): try: query = self.request.GET.get('q', None) print('query', query) if query: snippets = ShopOwnerAddress.objects.filter( Q(user_id__name__iexact=query)| Q(user_id__mobile_number__iexact=query)| Q(address_line1__iexact=query) ).distinct() return Response({'message': 'data retrieved successfully!', 'data':snippets}, status=200) else: # some logic.... except KeyError: # some logic....