Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not redirecting to profile page after login. What is wrong with my code?
This is my views.py def LoginPage(request): username = password = '' next = "" if request.GET: next = request.GET['next'] if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None: login(request, user) if next == "": return HttpResponseRedirect('/Profile/') else: return HttpResponseRedirect(next) context = {} return render(request, 'login.html', context) This is my template: {% if next %} <form class="" action='/Profile/' method="post"> {%else%} <form class="" action="/Login/" method="post"> {% endif %} {% csrf_token %} <p class="login-field-title"><strong>Username*</strong></p> <input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Enter Username" required> <p class="login-field-title"><strong>Password*</strong></p> <input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} <button type="submit" class="btn btn-dark btn-lg col-lg-10 log-btn">Log In</button> </form> I don't understand what I'm doing wrong. Some help would be very appreciated. Even after logging in with a registered user it is not redirecting me to the desired page and when i change the action, even with the un registered user it redirects me to the next page. -
how to check if start date and end date takes then raise an error django
I'm working on a project for a hotel , i have to prevent from select wrong dates for example check_in = 27-6-2021 2:30PM check_out = 30-6-2021 2:30PM i want to prevent from selecting any date into that two dates for example check_in=28-6-2021 2:30PM check_out=2-7-2021 2:30PM and so on .. this is my Booking model class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') takes_by = models.ManyToManyField(Vistor) check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() #my form class BookingForm(forms.ModelForm): takes_by = forms.ModelMultipleChoiceField(queryset=Vistor.objects.all()) check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) check_out = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) class Meta: model = Booking fields = ['takes_by','check_in','check_out'] my views.py @login_required def add_booking(request,room_no): room_number = get_object_or_404(Room,room_no=room_no) if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.room_no = room_number obj.admin = request.user obj.save() messages.success(request,f'room number {room_number} added') form = BookingForm() return render(request,'booking/add_booking.html',{'form':form,'lists':lists,'room_number':room_number}) what should i do to prevent from takes a room in an existing date twice ? thank you so much -
How to add new row to table on button click and get all the datas in a form containing table and other input fields to save in django sqlite3 DB
---HTML--- One table row contains itemname(select2 dropdown) , Nos , Price , Amount , Toggle button... Totally 5 td's in one row. Need one button somewhere which can be used to add indentical row to the table containing all those 5 td's. Last row of the table will always be the total bill amount field which does calculations and displays total amount. This all goes into a form and submit button should trigger GET to fetch all values in the form including the datas in table. <table id="bill" class="table table-sm"> <thead> <tr class="d-flex"> <th class="text-center"> <th class="col-5"> Item Name </th> <th class="col-1"> Nos </th> <th class="col-2"> Price </th> <th class="col-2"> Amount </th> </th> <th class="col-2"> </th> </tr> </thead> <tbody> <tr class="d-flex"> <td class="col-sm-5"> <div class="form-outline"> <select id="selectitem1" class="selectitem" "form-control" style="width: 100%" onchange="myFunction(event,1)" > <option selected disabled="True" class="form-control">Item Name </option> {% for item in showdrop %} <option value="{{item.item_price}}" class="form-control">{{item.item_name}}</option> {% endfor %} </select> </div> </td> <td class="col-sm-1"> <div class="form-group"> <input type="text" class="form-control qty" name="qty"> </div> </td> <td class="col-sm-1-5"> <div class="form-group"> <input id="myText1" type="text" class="form-control price" value=" " name="price"> </div> </td> <td class="col-sm-2"> <div class="form-group"> <output class="form-control amt" name="amt" readonly > </div> </td> <td class="col-sm-2 "> <div class="form-group"> <div class="col-sm-15 align-self-center"> <div … -
Using widgets on Django forms
I'm having issues with running my widgets on my Django forms. Below is the block of code. Prior to this, I had already installed the necessary Bootstrap element to my base.html file. Please help. Thank you. from django import forms from .models import Post class PostForm (forms.ModelForm): class Meta: model= Post fields= ('title', 'title_tag', 'author', 'body') widgets= { 'title': forms.TextInput (attrs= {'class': 'form-control', 'placeholder': 'Enter title here'}), 'title': forms.TextInput (attrs= {'class': 'form-control'}), 'author': forms.Select (attrs= {'class': 'form-control'}), 'body': forms.Textarea (attrs= {'class': 'form-control'}), } -
Django ModelForm widgets not modifying on the page
I want to style Django forms, but widgets are not taking any effect. My code: forms.py class bidForm(forms.ModelForm): class Meta: model=bid fields = ['bid'] widgets = { 'place a bid': forms.NumberInput(attrs={ 'class': "form-control", 'style': 'font-size: xx-large', 'placeholder': 'place a bid', }) } models.py class bid(models.Model): listing = models.ForeignKey('listing', on_delete=models.CASCADE, related_name='listing') user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2,) def __str__(self): return f"{self.bid}, {self.listing}, {self.user}" What is the reason it's not working? Answer would be greatly appreciated! -
My password reset view in django shows up only when the user has logged in but not when logged out
When I click on forgot password django takes me to another page other than the password reset page, but this doesn't happen when I am logged in only happen when I am logged out. I want it to happen when logged out Please help! views.py @login_required def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "password/password_reset_email.txt" c = { "email": user.email, 'domain': '127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'sample@gmail.com', [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, 'A message with reset password instructions has been sent to your inbox.') return redirect("/password_reset/done/") messages.error(request, 'An invalid email has been entered.') password_reset_form = PasswordResetForm() return render(request=request, template_name="password/password_reset.html", context={"form": password_reset_form}) urls.py urlpatterns = [ path('signup/', signup), path('login/', login_request), path('logout/', logout_request), path('', TemplateView.as_view(template_name="index.html")), path('Admin/Links/', update_profile_links), path('Admin/Appearance/', update_profile_appearance), path('Admin/Social_Links/', update_profile_social), path('Admin/Profile/<str:username>/', profile_view), path('password_reset/', password_reset_request), path('password_reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), path('delete_account/', delete_user) ] project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Home.urls')), path('', include('UserManagement.urls')), path('', include('UserLinks.urls')), ] -
How can I resolve this issue when I am trying to uninstall django from system?
enter image description here First I checked the version of django so I got 3.1.3 but when I tried to uninstall with pip uninstall django it says 'Skipping django as it is not installed'. -
Retrieving Django model value based on another model
I was following a youtube's django database model queries but try doing it with different context to see if I understand the model concept and not just blindly following (and it turns out i do not understand it at all). I was trying to retrieve the "views" values in the model based on the tag name. I manage to pull the individual item but i do not know how to retrieve the view count based on the tag name. The table look similar to this: title author body views tags title a author a blog post a 10 apple, orange, pear title b author a blog post b 100 banana, orange title c author a blog post c 50 banana, pear, apple, orange title d author a blog post d 1 grape the value i hope to retrieve is the sum of views that the tags are associated, like this tags|count --|-- apple|60 orange|160 banana|150 grape|1 pear|51 This is the current model class Tag(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return f'{self.name}' class Blog(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() views = models.IntegerField(default=0) tags = models.ManyToManyField(Tag) class Meta: verbose_name_plural = "Blogs" def __str__(self): return f'{self.title} | … -
test db is not able to query from second db
i am writing a test in Django using django.test TestCase and in this test i am acessing both the db but i am getting error like i db is not there in my testdb settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'xxx', 'PORT': 'xxx', 'TEST': { 'MIRROR': 'default', }, }, 'middle': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'xxx', 'PORT': 'xxx', 'TEST': { 'MMIRROR': 'middle', }, } } error in console {'error': "Database queries to 'middle' are not allowed in this test. Add " - "'middle' to file.tests.TestFunc.databases to ensure proper " - 'test isolation and silence this failure.', -
How to set attributes of a long list of times in a shorter way?
I have to do something like this class AuthTestings(TestClass): def setUp(self): ... self.user = user self.user2 = user2 self.token = token self.token2 = token2 self.myval = myval ... def test_smth(self): ... #and ..... my goal to get a shorter way to do to add attributes to self. maybe I can use setattr or any other way that shorten the job for me from varname.helpers import Wrapper x = [user,user2,user3,token,token2,token3,client] for i in x: i = Wrapper(i) setattr(self,i.name,i.value) # this don't work att al because i.name return i instead of user, user2... -
why i cant use template tags in django
I tried to loop the link and name in the list but it's not working, can someone explain to me why it is not working? picture -
How can I use a global/module level ThreadPoolExecutor in my python django server?
So this is the code setup I want. I'm using python2. I'm looking for do's and don'ts here. And to know if I am doing it right. Also another solution. I am trying this out, since my pods crash very quickly when doing load tests at around 100 rps. and with profiling I was seeing that each request was creating too many threads. The one problem I still have with this setup is that it does close idle threads after some timeout, while keeping only a handful of threads when the app is idle. pool = ThreadPoolExecutor(100) def function_a(): output = Queue() fs = [] for _ in range(5): fs.append(pool.submit(do_five_db_calls, output)) pool.wait(fs) def function_b(): output = Queue() fs = [] for _ in range(5): fs.append(pool.submit(do_five_elastic_calls, output)) pool.wait(fs) def function_c(): output = Queue() fs = [] for _ in range(5): fs.append(pool.submit(do_five_io_calls, output)) pool.wait(fs)``` -
how to give random colors to every post in my post's list
here is my code: {% for post in post_list %} <div class="mybox"> <div id="post"> <h1 ><a class = 'title_font' href="{% url 'blog:post_detail' pk=post.pk %}"><strong>{{ post.title }}</strong></a></h1> <a href="{%url 'blog:post_detail' pk=post.pk %}">Comments :</a> </div> </div> <script src='{% static 'js/blog.js' %}'></script> {% endfor %} in my blog.js javascript file if when i assign mybox random colors, all the posts have the same random background color. how can i get different colors for each .mybox element??? -
Django - Is it possible to add template render conditional based off content inside model field?
I would like to render content inside a template using a conditional that detects for string matching. If first few strings pass the conditional, then I would like for said object field to render, if not, then skip the object. The field in question is a large content field used to store blog text. This field has HTML tags such as <p> or <iframe>. I would like for this template render to detect for <iframe> string, as the conditional. Here is my code: View.py: def homepage(request, *args, **kwargs): obj = blog.objects.filter(posted=True).order_by('-date_posted') posts = { 'object': obj } return render(request=request, template_name="home.html", context=posts) html: <div class="container px-5 py-10 mx-auto md:px-20 lg:px-30"> {% for post in object|slice:":4" %} <div class="p-12 md:w-1/2 flex flex-col items-start"> <span class=" inline-block py-1 px-2 rounded bg-indigo-50 text-indigo-500 text-xs font-medium tracking-widest font-sans " >{{ post.subtitle }}</span > <span class="mt-1 text-gray-500 text-sm font-mono" >{{ post.date_posted }}</span > <a href="articles/{{ post.url_title }}"> <h2 class=" sm:text-3xl text-2xl title-font font-medium text-gray-900 mt-4 mb-4 font-sans " > {{ post.title }} </h2> </a> <p class="leading-relaxed mb-8 font-sans"> {{ post.content|truncatechars:300|striptags }} </p> <div class=" flex items-center flex-wrap pb-4 mb-4 border-b-2 border-gray-100 mt-auto w-full " > <a href="articles/{{ post.url_title }}" class="text-indigo-500 inline-flex items-center font-mono" >Read More <svg … -
Django Rest Framework - Add pagination(limit on no of objects) on a Viewset view list API, without having a Django Model class
I am trying to build a web scraper API, in which it will fetch a list of data from a website and return it. I want to add limit to the result. My current API path is /api/country/ I am looking for something like /api/country/?limit=1 views class CovidCountryViewSet(viewsets.ViewSet): serializer_class = CovidCountrySerializer def list(self, request): summary = CovidDataSraper().fetch_summary_data() serializer = CovidCountrySerializer( instance=summary["data"], many=True) return Response(serializer.data) serializer.py class CovidCountrySerializer(serializers.Serializer): country = serializers.CharField(max_length=256) total_cases = serializers.IntegerField() active_cases = serializers.IntegerField() total_deaths = serializers.IntegerField() population = serializers.IntegerField() total_recovered = serializers.IntegerField() percentate_of_population_infected = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=False) recovery_rate = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=False) models.py class CovidCountry: def __init__(self, **props): fields = ['country', 'total_cases', 'active_cases', 'total_deaths', 'population', 'total_recovered'] for field in fields: setattr(self, field, props.get(field, None)) urls.py router = routers.DefaultRouter() router.register(r'covid-summary', views.CovidCountryViewSet, basename="covid") urlpatterns = [ path('api/', include((router.urls, 'covid'), namespace='covid')) ] -
Django pagination last page is empty
I get empty page errors trying to Page my posts. I have 7 posts but I get a blank page error when I want to go to Page seven and i can't see my last post. new_list = list(zip(yeni_ders_tarih, yeni_ders_saat, yeni_ders_ismi,yeni_ders_ogretmen, yeni_derslik, yeni_yoklama)) paginator = Paginator(new_list, 1) sayfa = request.GET.get('post') page7 = paginator.page('7') page = page3.object_list try: listeler = paginator.page(post) except PageNotAnInteger: listeler = paginator.page(1) except EmptyPage: listeler = paginator.page(1) Also, I can get page seven manually. return render(request, 'pages/ogrenci-profil.html', context={ 'new_list':listeler, 'page':page }) This is my template.html <tbody> {% for a, b, c, d, e, f in new_list %} <tr> <td>{{ a }}</td> <td>{{ b }}</td> <td>{{ c }}</td> <td>{{ d }}</td> <td>{{ e }}</td> <td> {% if f == 'Katıldı' %} <div class="katildi"> <div style="margin:10px;">{{ f }}</div> </div> {% else %} <div class="katilmadi"> <div style="margin:10px;">{{ f }}</div> </div> {% endif %} </td> </tr> </tbody> {% endfor %} This is manually get page seven This is my page seven error -
how to check date is between a range from models
I have a list of dates and I want to check if dates are in between the range then it will pass. here range means I have model Splitrule which has startDate and endDate. I want to check if a date is between startDate and endDate. what I have tried so far: dates = list(set(OrderDetail.objects.all().values_list('orderDate', flat=True))) for date in range(len(dates)): check_date = SplitRule.objects.filter(startDate__lt=date,endDate__gt=date) print(f'check date',check_date) it gives me an error: File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/simpsoft/Desktop/sct-service/simpsoftService/orders/views.py", line 220, in post check_date = SplitRule.objects.filter(startDate__lt=date,endDate__gt=date) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/simpsoft/Desktop/sct-service/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, … -
TemplateSyntaxError 'apptags' is not a registered tag library
I have made a custom template tag , in apptags.py file which is inside templatetag folder and templatetag folder is inside my application folder, with the following code from django import template import datetime register=template.Library() @register.simple_tag(name="get_date") def get_date(): now = datetime.datetime.now() return now and im using it in my html file as % load static %} {% load apptags %} {% get_date as today %} <h2>Today is {{today}} </h2> and it is showing the below error: TemplateSyntaxError at /exam/show-test/ 'apptags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz P.S :- Templatetag is a package as i've made a init.py file inside it -
Add extra data in JWT header, simple jwt
I want to override or extend Django simple JWT obtain token method to add 'kid' key to the token header, JWT format is header.payload.signiture, I know how to add it to payload but I need to add it to the header, is there any way? -
Download model data in django admin panel with download button
i want to download model data from Django admin panel by adding download button on that panel. can someone please guide me through it . how can i do it? -
Setting.py Configuration for Production mode and Deployment
What I want to do is make all necessary changes in settings.py for Production purpose.When I set DEBUG=True,Everything works all right but when I set DEBUG=False,It makes me feel so tired and depressed.I have been trying for many days but could't figure out.Setting DEBUG=False, Static files runs and some don't but mediafiles completely stop working and i get Server Error (500) in some of the pages.And,I know the fix is in settings.py but don't know how to? import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = ')osa2y(^uk4sdghs+#(14if-)b1&6_uo@(h#0c%sci^a#!(k@z' DEBUG = False ALLOWED_HOSTS = ['dimensionalillusions.herokuapp.com','127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #CUSTOM APPS 'EHub.apps.EhubConfig', 'EBlog.apps.EblogConfig', 'EDashboard.apps.EdashboardConfig', 'mptt', 'ckeditor', 'taggit', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Dimensionalillusions.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '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', ], }, }, ] WSGI_APPLICATION = 'Dimensionalillusions.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ … -
i want to show employe names of each depertment on the side . how can i do that. in django
this is my model. emplye and depertment class. emplye is a child of depertment. #models.py from django.db import models from django.urls import reverse # Create your models here. class emplye(models.Model): name = models.CharField(max_length=30) email= models.CharField( max_length=20) phone =models.CharField( max_length=20) address =models.CharField( max_length=20) # dept_id =models.IntegerField(max_length=20) depertment =models.ForeignKey("depertment", on_delete=models.CASCADE) def __str__(self): return self.name class depertment(models.Model): name = models.CharField( max_length=20) about =models.CharField( max_length=20) here is my views.py file.i am annotating emplye objects and from deperment. i am trying to show the emplye names in each depertment . #views.py from django.shortcuts import render from .models import * from django.db.models import Count def index(request): b = depertment.objects.all().annotate(emp=(Count('emplye'))) print("Return:",b) print() print("SQL Quey:",b.query) context = { 'b':b, } return render(request, 'employe/index.html',context) here is my html file #index.html {% for z in b %} <h1>{{ z.name }} {{ z.emp }} {{z.emp__name}} </h1> {% endfor %} here is my current result -
TypeError: PanelReview() got an unexpected keyword argument 'panelmember'
I'm unable to post a review from react side, However at backend it's working fine. When I hit button to submit review this error comes on frontend And at Backend Django expecting something else and error is Internal Server Error: /api/panel/1/reviews/ Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "E:\eCommerce_Projects\remote-hospital\panel\views\panelmembers_views.py", line 66, in createPanelMemberReview review = PanelReview.objects.create( File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 451, in create obj = self.model(**kwargs) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 503, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: PanelReview() got an unexpected keyword argument 'panelmember' [27/Jun/2021 11:48:07] "POST /api/panel/1/reviews/ HTTP/1.1" 500 121143 Problematic Code: PanelMemberDetailScreen.js Removed Irrelevant Lines import React, { useState, useEffect … -
Remove objects with duplicated values from Django queryset
I want to remove objects with the same field value from a queryset. I've seen some related answers here, but none of them use the annotate and Min feature and I don't know if that approach is even possible. Imagine I have a 'Book' model with a 'Library' model FK. A Library could have multiple Books with the same title. How can I obtain a list of Books from that Library with different titles and lower price? I've tried different approaches with no success: Book.objects.annotate(count_id=Count('title'), min_price=Min('price')).filter(library__id=21, price=F('min_price')).values_list('title') Example: Having this objects | ID | Title | Price | |:---- |:------:| :-----| | 1 | Trainspotting | 3 | | 2 | The Catcher in the rye | 2 | | 3 | Trainspotting | 1 | | 4 | Lord of the Rings | 5 | | 5 | Trainspotting | 5 | I want to obtain the following queryset: ID Title Price 2 The Catcher in the rye 2 3 Trainspotting 1 4 Lord of the Rings 5 Thanks you very much for your help! -
JWT: How do I implement my custom error message on password or username is wrong Django REST
I want to implement my own custome error message when user types wrong password in Django Rest JWT authentiction as of now default error message is "detail": "No active account found with the given credentials" I have inherited Token Obtain pair view as class TokenPairSerializer(TokenObtainSerializer): default_error_messages = { 'login_error': _('Username or Password does not matched .') } @classmethod def get_token(cls, user): return RefreshToken.for_user(user) @classmethod def get_user_type(cls, user): if user.is_superuser: return 'super_user' elif user.is_student: return 'student_user' elif user.is_teacher: return 'teacher_user' def validate(self, attrs): data = super().validate(attrs) self.validate_user() refresh = self.get_token(self.user) I don't know where can I need to overrid error message to get response as this 'login_error': _('Username or Password does not matched .') any help will be helpful.