Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Using Django Templates to get data from the database in Javascript
So I am using AJAX to get a response on a form data submitted. I initially used to do it using an HTTP request but then due to other reasons, I shifted to using AJAX where I am thrown with several errors. So firstly from my views.py, I send a JsonResponse back to JS. data = list(Trips.objects.all().values()) return JsonResponse({"noOfTrips":len(data), "trip":data}) And now previously my template.html looks like this... <a class="text-decoration-none text-dark ModalSelector" id="linkTripModalBtn" data-bs-target="#linkTripModal"> <div class="passengerTripListCont font3 p-2 mt-2"> <div class="row1 d-flex align-items-center container-fluid px-0"> <img class="rounded-circle mx-2" width="50" height="50" src="{{trip.user.profiledriver.your_picture.url}}" alt="profPic"> <div> <p class="mb-0"><strong class="driverName">{{trip.user.first_name}} {{trip.user.last_name}}</strong> (#<span class="driverID">{{trip.user.id}}</span>)</p> <small class="text-muted"><span class="driverVehicle">{{trip.vehicle_used.model}}</span> <strong>{{trip.vehicle_used.vehicle_number}}</strong></small><br> <small>Trip refernece: #<strong class="tripID">{{trip.id}}</strong></small> </div> </div> <div class="row2 mt-2 border-top border-dark pt-1"> <p class="text-center mb-1 travelPoints d-flex align-items-center"> <span class="tripDeparture">{{trip.departure}}</span> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-arrow-right-circle mx-1" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM4.5 7.5a.5.5 0 0 0 0 1h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 1 0-.708.708L10.293 7.5H4.5z"/> </svg> <span class="tripArrival">{{trip.arrival}}</span> </p> </div> <div class="row3"> {% if tripsUserData.period == None %} <h6 class="text-center">Travelling <strong class="tripDate">{{trip.date}}</strong> … -
Can you get the django form id from django template using id_fieldname?
I am using a model form that has 3 fields - name, country and city. My template looks like this- <form method="post" id="personForm" data-cities-url="{% url 'ajax_load_cities' %}"> {% csrf_token %} {{form}} <input type="submit" value="Submit"> </form> Following this is a bit more jQuery code that fetches the id for the "country" field using a code like this - $("#id_country").change(function ().... Two things I need to mention here, no where in my code I have id_country except from this jQuery code. Also I haven't set the id attribute for the country field anywhere. So my question is , is this a thing in django or in jQuery where you can get the id for a field using id_ in front of the field name? I read the django documentation, haven't seen anything like this. What am I missing here? Thanks for any input. -
Como puedo descargar una imagen con URL blob en Django?
Tengo una url tipo blob:http://localhost:4200/1d2d99a2-cdb4-4784-bbc6-1047acc0be57 y quisiera poder descargarla, pero simplemente no funciona, ya probé varios métodos def responder(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) content = body['imagen'] url=content[0]['webviewPath'] #url blob -
Solve python ValueError: max_workers must be <= 61 when running pre-commit?
I am using Django to develop an ERP and I want to use pre-commit with my project. I have installed pre-commit, black, flake8, flake8-black. and this is my .pre-commit-config.yaml file configurations content repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black rev: 19.3b0 hooks: - id: black language_version: python3.7 When I commit my code it gives me this error Check Yaml...............................................................Passed Fix End of Files.........................................................Failed - hook id: end-of-file-fixer - exit code: 1 - files were modified by this hook Fixing vms/movement/test/test_model.py Fixing vms/payment/test/test_forms.py Trim Trailing Whitespace.................................................Passed black....................................................................Failed - hook id: black - exit code: 1 Traceback (most recent call last): File "C:\Program Files\Python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\Python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\Scripts\black.EXE\__main__.py", line 7, in <module> File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\black.py", line 3754, in patched_main main() File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\click\core.py", line 1137, in __call__ return self.main(*args, **kwargs) File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\click\core.py", line 1062, in main rv = self.invoke(ctx) File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\click\core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\click\core.py", line 763, in invoke return __callback(*args, **kwargs) File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\click\decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\diaa\.cache\pre-commit\repo4t4vqwkg\py_env-python3\lib\site-packages\black.py", line 435, in main executor = ProcessPoolExecutor(max_workers=os.cpu_count()) File "C:\Program Files\Python37\lib\concurrent\futures\process.py", … -
How to make offline wallet and add money for joining the tournaments in django
my project is based on User Join to the paid Tournaments. after User signup they want to join the Tournament. So I add offline payment function. But it doesn't work Properly. WHAT I NEED: if I adding money using add balance function, When user add balance it stored directly, for example: I have 20rupees in my wallet, so I need to add money for join the tournament. So I add 100 rupees in my wallet, finally in 120rupees my wallet right. But my wallet shows only 100rupees. I mean add balance input directly stored to balance without adding instance. I need instance money + add balance in my wallet.. default balance wallet image Adding 100rupees more image It show 100rupees instead of 120rupess Models.py class Profile(models.Model): user = models.OneToOneField(User,null=True, on_delete=models.CASCADE) pubg_id = models.PositiveIntegerField(null=True,blank=True) pubg_name = models.CharField(max_length=15,null=True,blank=True) phone_no = models.PositiveIntegerField(null=True,blank=True) balance = models.PositiveSmallIntegerField(default="0",verbose_name= _('Enter Amount')) def __str__(self): return str(self.user) def create_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_user_profile,sender=User) Views.py class AddBalanceView(SuccessMessageMixin,UpdateView): template_name = 'bgmiapp/add_balance.html' fields=('balance',) success_message = "Balance added Successfully" success_url= reverse_lazy('home') def get_object(self): return self.request.user.profile templates {% extends 'bgmiapp/base.html' %} {% load static %} {% block title %} Add_Balance {% endblock %} {% block content %} <h3>Add Balance</h3> <form method="POST"> {% csrf_token %} … -
Generic view for different models in django
To summarize the project, I am working on a website that categorizes electronic devices. Each electronic device has a category (Phone, Tablet, Computer, etc...), a manufacturer (Apple, Samsung, Dell, etc...) and the device itself (iPhone 6, iPhone X, Samsung S21, etc...). I have a single template for the 3 different models (Category, Manufacture, Device) and I am looking to simplify the views which are currently just a copy and paste. Here is the current code: @login_required(login_url="/login/") def show_category(request): groups = Category.objects.all() return render(request, "groups/group.html", {'group': 'Category', 'groups': groups}) @login_required(login_url="/login/") def show_manufacturer(request): groups = Manufacturer.objects.all() return render(request, "groups/group.html", {'group': 'Manufacturer', 'groups': groups}) @login_required(login_url="/login/") def show_device(request): groups = Device.objects.all() return render(request, "groups/group.html", {'group': 'Device', 'groups': groups}) Additionally, I have some POST functions which are also copy pastes of the same function for the different models to the same template. I have been able to find examples where multiple models are used at the same time for one template, but I cannot for the life of me seem to find an example of using different models for the same template. Can someone link me to an example or the docs that explains how to accomplish this ? I feel like I have missed … -
I am trying to register users in django but the form fields are not showing up. What is wrong with my code?
this is my forms.py: from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] This is my views.py: from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm def RegisterPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'register.html', context) this is my html template: <div class="col-lg-4 login-bg"> <h4 class="reg-title"><strong>Get Started...</strong></h4> <p class="login-reg">Already have an account? <a class="log-reg-link" href="login.html">Log In </a> here</p> <hr> <form class="" action="/Dashboard/" method="post"> {% csrf_token %} <p class="reg-field-title"><strong>Username*</strong></p> <div>{{form.username}}</div> <p class="reg-field-title"><strong>Email ID*</strong></p> <div>{{form.email}}</div> <p class="reg-field-title"><strong>Password*</strong></p> <div>{{form.password1}}</div> <p class="reg-field-title"><strong>Password Confirmation*</strong></p> <div>{{form.password2}}</div> <button type="submit" class="btn btn-dark btn-lg col-lg-10 reg-btn">Register</button> </form> What am I doing wrong because the form fields are not showing up on the page? I followed a youtube tutorial and went step by step but I don't understand the problem now. -
TypeError at /review/1 __init__() got an unexpected keyword argument 'id'. I am creating a online book buying and selling project
I have added int:id as primary key to the views url of 'review'and also passed it to views of 'review', but it is still showing the error. project/urls.py ''' from django.contrib import admin from django.urls import path,include from home import views urlpatterns = [ path('', views.home, name='home'), path('signup/', views.signup_view, name='signup_view'), path('login/', views.login_view, name='login_view'), path('logout/', views.logoutUser, name='logout'), path('add_product/', views.addproduct, name='add_product'), path('contact/', views.contactus, name='contactus'), path('prod_detail/<int:id>',views.prod_detail,name='prod_detail'), path('review/<int:id>',views.review,name='review'), ]''' ///views.py This is the project/views.py of my project ''' def review(request,id): rform=ReviewForm(id=id) if request.user.is_authenticated: #prod = request.user if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid: user = form.save(commit=False) user.posted_by = request.user user.save() return render(request,'review.html',{'rform': rform}) else: return render(request,'/login.html') ''' ///review.html ''' <div class="card card-outline-secondary my-4"> <div class="card-header"> Product Reviews </div> <div class="card-body"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis et enim aperiam inventore, similique necessitatibus neque non! Doloribus, modi sapiente laboriosam aperiam fugiat laborum. Sequi mollitia, necessitatibus quae sint natus.</p> <small class="text-muted">Posted by Anonymous on 3/1/17</small> <hr> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis et enim aperiam inventore, similique necessitatibus neque non! Doloribus, modi sapiente laboriosam aperiam fugiat laborum. Sequi mollitia, necessitatibus quae sint natus.</p> <small class="text-muted">Posted by Anonymous on 3/1/17</small> <hr> <a href="{% url 'review' rev.id %}" class="btn btn-success">Leave … -
How to write CSS inline with django variable?
I created a progress bar with bootstrap. Which is where there is a style attribute to set the progress width. I linked the progress to the models to retrieve the value. As follows. {% for k in kelas %} <div class="col-sm-6"> <div class="progres"> <div class="kelas mb-2">{{ k.namaKelas }}</div> <div class="progress"> <div class="progress-bar" role="progressbar" style='width:{{k.get_percent}}%' aria-valuenow="{{ k.get_percent }}" aria-valuemin="0" aria-valuemax="100">{{ k.get_percent }}%</div> </div> </div> </div> {% endfor %} But at this point style='width:{{k.get_percent}}%' no response on progress width. And in html file it show red color because there is a code that is considered wrong. How can i get a variable to include django in that style?