Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is exactly Meta in Django
i want know simply what is Meta class in django and what they do from django.db import models Class Author(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) class Meta: ordering=['last_name','first_name'] -
How to style certain tags when condition is met after extending 'base.html'?
I'd like to change the style of all 'select' in my DetailView, but only when certain condition is met (like {% if object.sth == 'sth' %} ). This html is extended from 'base.html' where I already have my css linked, and all 'select' styled. What would be the best approach? It seems I can not link new stylesheet while I'am already in (after extending base.html) -
Django rest fetch data from bridge model
I want to get all the user details and list of all the roles against the user details model My Models class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userdetail_user', default='111') cn = models.CharField(max_length=200) sn = models.CharField(max_length=200) u_id = models.CharField(max_length=200) display_name_cn = models.CharField(max_length=200) display_name_en = models.CharField(max_length=200) given_name = models.CharField(max_length=200) employee_number = models.CharField(max_length=200) email = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_login = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.given_name class Role(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) def __str__(self): return self.title class UserRole(models.Model): userdetail = models.ForeignKey(UserDetail, on_delete=models.CASCADE, related_name='userrole_userdetail') role = models.ForeignKey(Role, on_delete=models.CASCADE) approver = models.ForeignKey(UserDetail, on_delete=models.SET_NULL, null=True, related_name='userrole_userdetail_approver') created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) My Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class UserRoleSerializer(serializers.ModelSerializer): class Meta: model = UserRole fields = ('id', 'userdetail', 'role', 'approver', 'last_updated', 'status') depth = 1 def to_representation(self, instance): representation = super(UserRoleSerializer, self).to_representation(instance) representation['userdetail'] = UserDetailSerializer(instance.userdetail).data representation['role'] = RoleSerializer(instance.role).data representation['approver'] = UserDetailSerializer(instance.approver).data return representation class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('id', 'title', 'description', 'last_updated', 'status') class UserDetailSerializer(serializers.ModelSerializer): user = UserSerializer() roles = serializers.SerializerMethodField(read_only=True) class Meta: model = UserDetail fields = ('id', 'roles', 'user', 'cn', 'sn', … -
Deploying my Django website to Heroku with DEBUG=False doesn't work
When deploying django onto either localhost or heroku with DEBUG=False, it throws an error saying C:\Users\krish\Envs\PRREMIA\lib\site-packages\whitenoise\base.py:105: UserWarning: No directory at: c:\Users\krish\Documents\python\PRREMIA\staticfiles\ warnings.warn(u'No directory at: {}'.format(root)) [28/Jul/2019 16:05:43] "GET / HTTP/1.1" 500 27 When DEBUG=True, it works fine. Why? And how do I stop and fix this? -
Use of `get` for a `select_for_update` query in order to reduce the number of rows getting locked
I would like to know if there is a good solution for this scenario. When a select_for_update is used in a query set, all matching results are locked until the particular block of code has not finished execution. This has become a little critical as simultaneous requests which could be served are being returned back by DatabaseErrors. Below is a sample query for which select_for_update has been implemented qs = Coupons.objects.select_for_update().filter(brand=brand).values('coupon').order_by('id') return qs[0] If we have 1000 coupons for a particular brand, then the entire 1000 rows are locked. I am unable to use get since we are returning the coupons on a FIFO basis and we would need to return coupons which were added first Is there any way I could use get, or minimize the number of rows being locked -
Aggregate related integer-field values in Django template
I have this model which is related to a Node model, class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name In the template when i query a list of the Node's objects i want to aggregate the value of the 'views_count' of each object. I have tried this in my template {% for tree in tree_result|slice:":14" %} {% for view in tree.related_views.all %} {{ view.views_count }} {% endfor %} {% endfor %} i have all the related count_view of the current tree but what i want to do is to aggregate the value of the related field and show it within the for loop of tree_result. Any suggestions please ? -
Django Blog Page not found (404) - No Post matches the given query
I'm coding a blog with Django,There was an error 404 when I click on address http://localhost:8000/blog/2019/7/28/prim-algorithm-path No Post matches the given query. Raised by: blog.views.blog_detail views.py def blog_detail(request,year,month,day,post): print(year,month,day,post) post = get_object_or_404(Post, slug=post, publish__year=year, publish__month=month,publish__day=day) return render(request,'post.html',locals()) blog/urls.py from django.urls import path from .views import index,blog_detail app_name = 'blog' urlpatterns = [ path('', index, name='index'), path('<int:year>/<int:month>/<int:day>/<slug:post>',blog_detail,name='post_detail'), ] mysite/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] what should I do -
Python dateparser fails when timezone is in middle
I'm trying to parse a date string using the following code: from dateutil.parser import parse datestring = 'Thu Jul 25 15:13:16 GMT+06:00 2019' d = parse(datestring) print (d) The parsed date is: datetime.datetime(2019, 7, 25, 15, 13, 16, tzinfo=tzoffset(None, -21600)) As you can see, instead of adding 6 hours to GMT, it actually subtracted 6 hours. What's wrong I'm doing here? Any help on how can I parse datestring in this format? -
User api request via app online - api server gets user or app IP adress?
I would like to publish an Django app on Vultr hosting. App (on user request) should connect an api on another server and return data to user. Api has requests limits by IP. When user connect api server via my app, api server will get user IP or my app server IP? If API server will get my app server ip my app will be banned after few request. How to avoid ban and send user ip to API server? Thank you for any help! -
How to save MultipleChoiceField to db
I want to create a settings page where a user can select multiple values of skills they have. It will have a main category and then subcategories. I need to save those into my database, so I can query them and show their selected skillset again. I know how to create the MultipleChoiceField but not how to save them to the database. How would I go on about that? Forms.py from django import forms class skills(forms.Form): jobs = [ ('Håndværker', ( ('Gulv', 'Gulv'), ('Væg', 'Væg'), ) ), ('Murer', ( ('Mur', 'Mur'), ('blabla', 'blabla'), ) ), ] job = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=jobs) Views.py from .forms import skills def index(request): if request.method == 'POST': form = skills(request.POST) if form.is_valid(): picked = form.cleaned_data.get('job') # do something with your results else: form = skills return render(request, 'settings/index.html', {"form":form}) It currently looks like this when the page loads which is good. Next step is just how I would save it to the database, so I can display this again with their previous chosen values. -
Error validating Django formset Modelform?
I am learning to implement Django formset using Modelform and I am getting this formset validation errors relating to my datefield. The error that I am getting is formset [{'from_date': ['Enter a valid date.'], 'to_date': ['Enter a valid date.']}] This is what I have tried so far.What could I be doing wrong ? models.py class WorkExperience(models.Model): company = models.ForeignKey(Company,on_delete=models.PROTECT) from_date = models.DateField() to_date = models.DateField() work = models.ForeignKey(Work,on_delete=models.PROTECT) date_last_modified = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True) forms.py class WorkExperienceForm(ModelForm): class Meta: model = WorkExperience fields=('from_date','to_date') def __init__(self, *args, **kwargs): super(WorkExperienceForm, self).__init__(*args, **kwargs) self.fields['name']=forms.CharField( label='Company Name', widget=forms.TextInput(attrs={ 'id': 'company_name', 'class': 'form-control', 'required':True }), ) self.fields['street_address'] = forms.CharField( label='Company Address', widget=forms.TextInput(attrs={ 'id': 'company_address', 'class': 'form-control', 'required': True }), ) self.fields['from_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['to_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['country'] = forms.ChoiceField(choices=Country.objects.all().values_list('id', 'name')) self.fields['country'].widget.attrs.update({'class': 'btn btn-secondary dropdown-toggle','required':True}) self.fields['project_name'] = forms.CharField( label='Project Name', widget=forms.TextInput(attrs={ 'id': 'project_name', 'class': 'form-control', 'required': True }), required=True, ) self.fields['project_details'] = forms.CharField( label='Project Details', widget=forms.Textarea(attrs={ 'id': 'project_details', 'class': 'form-control', 'required': True }), ) from django.forms import modelformset_factory WorkExperienceFormSet = modelformset_factory( WorkExperience, WorkExperienceForm, extra=1, ) views.py def post(self,request,*args,**kwargs): try: print('fromdate',request.POST['form-0-from_date']) formset = WorkExperienceFormSet(request.POST) print('formset',formset.errors) for form in formset: print('form',form.is_valid()) if … -
How to save a model-instance using serializers in django?
I would like to save a class instance in my database using serializers, provided by DRF. Serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' here I try to save an instance: p = Person(Name = "Test") _srlz = PersonSerializer(data = p) The real case is little bit more complicated, but sanse the same. Unfortunately the data - _srlz.data is empty. So if I try to save data via _srlz.save() method then nothing change. Otherwise if I request an existed object p = Person.objects.filter(id = 1) _srlz = PersonSerializer(data = p) Then my _srlz.data will not be empty. How should I save this object if datasource is not JSON-object, but model-class instance?Should I first serialize it and then deserialize again? I already tried to save instance calling a .save() method, provided by model's default Manager, but I would like to separate my model and service methods so all database operations performed by serializers. Or is it OK in this case, because I deal not with pure JSON, but with model instance? But how can I then validate data? -
How to fix this datetime iso format error in django-python which is occuring since I upgraded my python to 3.7
This is the error that I am facing when I try to run migrate or runserver or any command. Please Help. "raise ValueError(f'Invalid isoformat string: {date_string!r}')" Code -
NoReverseMatch at / on the start of the server
It's giving me an error: NoReverseMatch at / targeting the base.html file (shown in the pic).But the base.html file looks fine to me. Base.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Blog</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- Medium Style editor --> <script src="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/js/medium-editor.min.js"></script> <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/medium-editor@latest/dist/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One&display=swap" rel="stylesheet"> </head> <body class="loader"> <!-- Navbar --> <nav class="navbar custom-navbar techfont navbar-default"> <div class="container"> <ul class="nav navbar-nav"> <li><a class="navbar-brand bigbrand" href="{% url 'post_list' %}">My Blog</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="https://www.github.com">GitHub</a></li> <li><a href="https://www.linkedin.com">LinkedIn</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a href="{% url 'post_new' %}" >New Post</a></li> <li> <a href="{% url 'post_draft_list' %}" >Drafts</a></li> <li> <a href="{% url 'logout' %}" >Logout</a></li> <li> <a href="#">Welcome: {{user.username}}</a> </li> {% else %} <li> <a href="{% url 'login' %}" class="nav navbar-right"> <span class="glyphicon glyphicon-user"></span> </a> </li> {% endif %} </ul> </div> </nav> <!-- COntent Block --> <div class="content container"> <div class="row"> <div class="col-md-8"> <div class="blog-posts"> {% block content %} {% endblock %} </div> </div> </div> </div> </body> </html> Post_detail.html {% extends 'blog/base.html' %} {% block content %} … -
how to get previous page url in django template?
i am using the django password reset but i want my template to behave differently when it come from password_rest_email and from password_reset_confirm urls.py from django.conf.urls import url,include #from django.urls import path from dappx import views from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetCompleteView,PasswordResetConfirmView # SET THE NAMESPACE! app_name = 'dappx' # Be careful setting the name to just /login use userlogin instead! urlpatterns=[ url('register/', views.register, name='register'), url('user_login/', views.user_login, name='user_login'), url('google_login/', views.google_login, name='google_login'), url('special/', views.special, name='special'), url('logout/', views.user_logout, name='logout'), url(r'^', include('django.contrib.auth.urls')), url('password_reset/', PasswordResetView.as_view(), name='password_reset'), url('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), url('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] i need that template i.e(password_reset_confirm) to show email is send when it come from password_reset_email and show password reset successful if it come from password_reset_confirm password_reset_complete.html {% extends 'dappx/base.html' %} {% block title %}Check your Email{% endblock %} {% block body_block %} <div class="row no-gutters"> <div class="col-12 col-sm-6 col-md-8"></div> <div class="col-6 col-md-4"> <div class="jumbotron"> <h4>The password reset link has been sent to youre Email</h4> <br> <p>Check your email to reset the password. You can log in now on the <a href="{% url 'dappx:user_login' %}">log in page</a>.</p> <br> </div> </div> {% endblock %} -
Django Data to JsonResponse
I have this model that store all my data. This is my model.py: from django.db import models class Showing(models.Model): movie_id = models.CharField(primary_key=True, max_length=11) movie_title = models.CharField(max_length=100) image_url = models.TextField(blank=True) synopsis = models.TextField(blank=True) rating = models.TextField(default="MTRCB rating not yet available") cast = models.CharField(max_length=100) release_date = models.CharField(max_length=50, blank=True) def __str__(self): return "{}".format(self.movie_id) And I want to retrieve all my data and pass it to context and make a customize JsonResponse like this: "results": [ { "id": "1eb7758d-b950-4198-91b7-1b0ad0d81054", "movie": { "advisory_rating": "PG", "canonical_title": "ROGUE ONE: A STAR WARS STORY", "cast": [ "Felicity Jones", "Donnie Yen", "Mads Mikkelsen" ], "poster_portrait": "", "release_date": "", "synopsis": "Set shortly before the events of Star Wars (1977), Following the foundation of the Galactic Empire, the story will center on a wayward band of Rebel fighters which comes together to carry out a desperate mission: to steal the plans for the Death Star before it can be used to enforce the Emperor's rule. (Source: Disney Pictures)", } }, ] In my views.py I have this function to get all the data, and try just to retrive the movie_id from my model. def show_all_movies(request): movie = Showing.objects.all() context={'result':[{ 'id':movie.movie_id, 'movie': }]} But it gets me an error of 'QuerySet' object … -
how to send pre_save signal only when hit the save button for multiple form in one view (formset)
i trying to send signal only when the user hit the button save class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) @receiver(pre_save , sender=ProductOrder) def create_order(sender, instance, **kwargs): Order.objects.create() if not instance.ordering: instance.ordering = Order.objects.all().order_by('-pk')[0] pre_save.connect(create_order,sender=ProductOrder) forms.py class ProductOrdering(forms.ModelForm): class Meta: model = ProductOrder fields = ['product','ordering','quantity'] ProductFormSet = formset_factory(ProductOrdering , extra=2) i want to make only one id from Order for all forms in the same view , while hit the button ? thanks for advice -
ModelForm add the primary ID for an entry in table based on last entry's primary ID
I am creating a signup system. I am using the django's default User's model to store user details, and I am passing its objects into a model named "Employee" where their department, manager and other info is stored. Here is what I have. models.py: from django.contrib.auth.models import User class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') .... forms.py: from users.models import Employee from django.contrib.auth.models import User from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm class AddNewUserForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class AddNewEmployeeForm(ModelForm): class Meta: model = Employee fields = {'department', 'manager', 'total_leaves'} add_new_user.html: <form method="POST"> {% csrf_token %} {{ form_user.as_p }} {{ form_emp.as_p }} <div class="text-center"> <button type="submit" class="btn btn-success">Submit</button> </div> </form> And this is how I'm processing the data in views.py: def post(self, request): form_user = AddNewUserForm(request.POST) form_emp = AddNewEmployeeForm(request.POST) if form_user.is_valid(): emp_info = form_emp.save(commit=False) emp_info.leaves_taken = 0 emp_info.user = form_user.save() emp_info.save() messages.success(request, "Success!") else: messages.error(request, form_user.errors) messages.error(request, form_emp.errors) return redirect("add_new_user") The problem is that when the post method is run, it tries to add entries into Employee table from the beginning; assuming there are no entries in it. But I have entries in that table and I get the following … -
How can i save some data in Django without adding it in the form?
I have a model which looks like this: class MyModel(models.Model): rate = models.CharField(max_length=100) amount = models.FloatField() userid = models.CharField(max_length=100) def save(self): # ALL the signature super(MyModel, self).save() And a form: class MyForm(forms.ModelForm): rate = forms.CharField() amount = forms.FloatField() class Meta: model = MyModel fields = ("rate", "amount") def save(self, commit=True): send = super(MyForm, self).save(commit=False) if commit: send.save() return send At the actual moment, my form is saving the fields rate and amount on my database, once the user uses the form. I would like to save on my DB the user who submitted the form, the date/time of when the form was saved and some other data that must not be submitted by the user, but saved 'automatically'. How can i do that in Django? -
How to generate a user password in plain SQL with Django + PostgreSQL
I want to insert from a Django into another Django database from other domain a proper password text in auth_user table. I have tried to generate a encrypt function but I don't know how Django generates a password from plain text into hashed password that is stored in database. postgres_insert_query = """ INSERT INTO auth_user (username, first_name, last_name, email, password) VALUES (%s,%s,%s,%s,%s) """ record_to_insert = (username, first_name, last_name, email, password) cursor.execute(postgres_insert_query, record_to_insert) connection.commit() cursor.close() -
Django not serving static on digital ocean ubuntu 18.04
I have just successfully uploaded and run my project on digital ocean. It has been developed before production according to the coreyMS tutorials on youtube with the latest version of django 2.1.7. It has been deployed with this tutorial on ubuntu 18.04 on a digital ocean droplet. I cant make it serve any static files. The structure of my project is: newsite/myforum/ in here is the manage.py In the newsite/myforum/myforum/ is the settings.py and i have 3 apps users, forum and store that are all in folders in the newsite/myforum directory. The static folder according to the coreyms tutorial for the latest django version is supposed to be in my main app, therefore forum/static/forum. So the total path is newsite/myforum/forum/static/forum My settings are: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' In the nginx configuration i have specified the path, home/myuser/mydir/myenv/newsite/myforum maybe i should try: home/myuser/mydir/myenv/newsite/myforum/forum/static/forum or just: home/myuser/mydir/myenv/newsite/myforum/forum/static/ Or should i change my django settings and then run a collectstatic command. It took me a long time to get this far with the deployment and i dont want to run a stupid command and ruin it. Thank a lot for the help!!!!!!!!!! -
Generict django content type , get the object stored in contentype
Well similar questions have been asked, but none of the answers works for me . Bellow is my contentype model class notifyall(models.Model): target_instance=models.ForeignKey(ContentType,null=True,on_delete=models.CASCADE,blank=True) object_id=models.PositiveIntegerField(null=True) target_object=GenericForeignKey('target_instance', 'object_id') As you can see, contentype has a GenericForeignKey to store different kind of objects from different models when notifyall object is created , this is what i will get >>object_id= e.g 20 >>target_instance = class_name_of_model what is the right way to go about retrieving the object stored in contentype model as object_id and target_instance -
Circular import error when importing weasyprint's HTML
I am trying to generate a pdf and I am getting the error below. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'tenderwiz.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The error occurs when I include this line in my view from weasyprint import HTML utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.conf import settings import os from django.template.loader import render_to_string from weasyprint import HTML def render_to_pdf(template_src, context_dict={}): html_template = render_to_string('invoice_render.html', context_dict) pdf_file = HTML(string=html_template).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="invoice.pdf"' return response user_accounts/views.py from .utils import render_to_pdf from django.shortcuts import render, render_to_response, redirect, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.contrib import auth from django.template.context_processors import csrf from packages.models import Packages from .forms import (CustomUserForm, CompanyProfileForm, CompanyProfileEditForm, BankingDetailsForm, PayFast_Form, ) from django.contrib.auth import update_session_auth_hash from .models import CompanyProfile, OurDetails from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm, PasswordResetForm from tender_details.models import Category, Keywords, Province from django.core import serializers from django.http import HttpResponse from django.contrib import messages from django.urls import reverse import json from urllib.parse import urlencode, quote_plus import hashlib from django.conf import settings … -
How to test django channel layer with virtual-env on windows 10?
I'm using anaconda to make virtual environment and using it to develop my django apps. Now I'm working on a project that needs to use websocket to send notifications. I followed this Tutorial and first part worked well but this second part needs to open a port on computer to send data between users, using channel_redis and redis on docker to do this stuff, but as I said I'm using virtual-en on my local system. so is there a way to make it happen? The Output: raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) Sorry for bad english 😓 -
TypeError: 'ShiftSerializer' object is not callable
I am trying to do with ModelViewSet. I am facing this error now Here is my viewset=> class ShiftViewSet(viewsets.ModelViewSet): queryset = Shift.objects.all() serializer_class = ShiftSerializer() # filter_backends = (filters.DjangoFilterBackend,) # filterset_fields = ('shiftid',) @action(methods=['get'], detail=False) def newest(self, request): newest = self.get_queryset().order_by('Created_DT').last() serializer = self.get_serializer_class()(newest) return Response(serializer.data) @action(methods=['get'], detail=False) def shiftsum(self, request): query = ( Shift.objects.values('shiftid') .annotate(shiftdesc=Max('shiftdesc')) .annotate(overnight=Max('overnight')) .annotate(isspecialshift=Max('isspecialshift')) .annotate(ct=Count('*')) # get count of rows in group .order_by('shiftid') .distinct() ) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) @action(methods=['get'], detail=False) def byshiftid(self, request): shiftid = self.request.query_params.get('shiftid',None) query = self.get_queryset().filter(shiftid=shiftid) serializer = ShiftSerializer(query,many=True) return Response(serializer.data) Here is my router and url => router.register('shifts_mas', ShiftViewSet, base_name='shifts') path('api/', include(router.urls)) Normally I can call like /api/shifts_mas/ and I will get all record of shift but just now i got this error and i dont know why. May i know why?