Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-taggit only allow current tags for users
I have not been able to find any related questions on this. I have a create-post page where i want users to only be able to pick between current tags(could be done using scroll-down button) and not be able to create their own tags when creating a post. my approach so far has been trying to set the tag field with values of the link im pressing in the scroll down button. Image 4 shows the tag options where i want to display the tag name on the tag model field when that specific tag name is pressed on the scroll down button. images of my code: [models.py][1] [form.py][2] [views.py][3] [my create post page][4] [1]: https://i.stack.imgur.com/YafQ3.png [2]: https://i.stack.imgur.com/OnQF9.png [3]: https://i.stack.imgur.com/K3M6Z.png [4]: https://i.stack.imgur.com/yA2I4.png -
Django project deploy on Heroku failed
After I successfully deployed my Django project to Heroku, the page didn't show anything but the application error. It suggest me use the command to find the problem: heroku logs --tail and it shows lines of error, and here's part of them: 2021-03-19T10:06:26.966003+00:00 app[web.1]: Traceback (most recent call last): 2021-03-19T10:06:26.966003+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-03-19T10:06:26.966004+00:00 app[web.1]: worker.init_process() 2021-03-19T10:06:26.966004+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-03-19T10:06:26.966005+00:00 app[web.1]: self.load_wsgi() 2021-03-19T10:06:26.966005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-03-19T10:06:26.966005+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-03-19T10:06:26.966006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-03-19T10:06:26.966006+00:00 app[web.1]: self.callable = self.load() 2021-03-19T10:06:26.966007+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2021-03-19T10:06:26.966007+00:00 app[web.1]: return self.load_wsgiapp() 2021-03-19T10:06:26.966008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2021-03-19T10:06:26.966008+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-03-19T10:06:26.966008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2021-03-19T10:06:26.966009+00:00 app[web.1]: mod = importlib.import_module(module) 2021-03-19T10:06:26.966009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-03-19T10:06:26.966009+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-19T10:06:26.966010+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-03-19T10:06:26.966010+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in exec_module 2021-03-19T10:06:26.966012+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, … -
exclude content field from crispy forms
forms.py from django import forms from tinymce import TinyMCE from .models import Article class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = Article fields = ('title', 'major', 'semester', 'book', 'unit', 'content') article_form.html {% extends "base.html" %} {% load static %} {% load tailwind_filters %} {% block title %}Create{% endblock title %} {% block content %} {{ form.media }} <div class="row form-error"> <div class="column" id="content"> <form method="post" action='' enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input class="button" type="submit" value="Save"> </form> </div> </div> {% endblock %} I using TinyMCE to implement a rich text editor. when I reload the page it gives me this: AttributeError at /article/new/ 'CSSContainer' object has no attribute 'tinymce' I just want to use crispy forms on all fields and exclude the content field from crispy forms. -
Can't refer to Django templates
Below is my directories created by using Django isap/users needs to get templates from isap/isap/templates/users/login.html isap/ L isap L templates L users L login.html L .... L .... L ..... L ... L users L views.py L urls.py So, I added TEMPLATE = [{..., "DIRS": [os.path.join(BASEDIR2, "templates/")],APP_DIRS=True,....}]in settings.py and BASEDIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '\\isap' Also, I already added the apps PROJECT_APPS = [isap.apps.IsapConfig, users.apps.UsersConfig, ...] But, the 404(Page not found) error is generated. below is my users/views.py import os import requests from django.utils import translation from django.http import HttpResponse from django.contrib.auth.views import PasswordChangeView from django.views.generic import FormView, DetailView, UpdateView from django.urls import reverse_lazy from django.shortcuts import redirect, reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.core.files.base import ContentFile from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from . import forms, models, mixins class LoginView(mixins.LoggedOutOnlyView, FormView): template_name = "users/login.html" form_class = forms.LoginForm def form_valid(self, form): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(self.request, username=email, password=password) if user is not None: login(self.request, user) return super().form_valid(form) def get_success_url(self): next_arg = self.request.GET.get("next") if next_arg is not None: return next_arg else: return reverse("core:home") How can I link the templates to isap/users/views.py? -
adding python dicts to django JsonResponse
the time data in my MySQL database is in ISO time and i'd like to create two bar charts that show taxi rides by day of the week/ by hour. after querying the iso time from the database, i have the week of day count and hourly count saved in two dictionaries, and was wondering how i can render these dictionaries to JsonResponse (if JsonReponse takes in dicts) to render a chart.js bar chart. i have the following code written in my views.py and have no idea what it prints (or whether count is iterating through the dictionary correctly), so if there are any pointers as to how i can visualise this dictionary before charting that'd also be great. def charts(request): dow_queryset = Member.objects.order_by('member_created_time').values( 'member_created_time') hkt = timezone('Asia/Shanghai') dt_obj = hkt.localize(datetime.datetime.fromtimestamp(dow_queryset)) # naive datetime obj w/o tz info """ data - rides by the hour """ hour_count = {} for obj in dt_obj: if obj.hour == 0: hour_count['midnight'] += 1 elif obj.hour < 6: hour_count['early_morning'] += 1 elif obj.hour < 12: hour_count['morning'] += 1 elif obj.hour < 19: hour_count['afternoon'] += 1 else: hour_count['night'] += 1 """ data - rides by weekday (bar chart) """ weekday_count = {} for obj in … -
How can I relate two models in Django, where for each insertion in model1, model2 will automatically insert some fields from model1?
I have the model User which is inserted with data each time a user connects. And I have the model Client which is related to the User model. My goal is simple I want Client to be extended from User where for each row created in User Client should also create that row. I did the following code but still not the results that I want. class Client(User): # on_delete is for what operation we execute for the Client if the User got deleted # default option gives a default date before the user choose the date birthDate = models.DateField(null=True, default=django.utils.timezone.now) phone_number = models.CharField(null=True, max_length=30) id_card_number = models.IntegerField(null=True) address = models.CharField(null=True, max_length=300) # Below are optional entries in case the client chose a certaine type of an insurence # ( than it become required when the client want to sign a contract of that type ) children_number = models.IntegerField(null=True) entry_date = models.DateField(null=True) numberplate = models.IntegerField(null=True) marital_status = models.CharField(choices=Marital, max_length=20, null=True) def __str__(self): return self.username def create_client(sender, instance, created, **kwargs): if created: Client.objects.create(user_ptr=instance) post_save.connect(create_client, sender=User) -
Best practise for creating database objects from .csv file
My situation is: having .csv file with some columns e.g. name, surname, age, activity, and others I want to create objects in my relational database with row from this file being single object. Column names correspond to model fields and with others being multiple columns defined by user who creates .csv (those others land in model's filed comment separated with commas). Having relational db, base on model_1's object I create model_2 and model_3, all with the info from this .csv file. My project is based on django rest framework and react. Up till now my solution for this was to analize .csv file on with react using FileReader and readAsArrayBuffer which did it's job most of the time. With react I not only have to analyze the file, but for every row make at least 3 x POSTing with axios. Sequentional posting is not ideal all the time. My question is: > should files be analyzed on front- or back-end side ? Heaving it done on the backend side with python seems a lot easier, but there might be a better solution of which I can't think of. -
How to implement SSE using Django Framework?
I want to notify the UI(Reactjs), whenever new data gets added to the Database(MySQL). The Reset APIs are written using the Django framework. I want to do something similar to this : Server-Sent Event #1 - Spring Tutorial Practice. The code for which the API is successfully running is as follows: models.py from django.db import models from rest_framework.generics import ListAPIView from datetime import * # Create your models here. class FirstModel(models.Model): firstModelname=models.CharField(max_length=250,unique=True) firstModelID=models.AutoField(primary_key=True) def __str__(self): return self.firstModelname class SecondModel(models.Model): secondModelName=models.CharField(max_length=250) startTime=models.DateTimeField(default=datetime.now,blank=True, null=True) endTime=models.DateTimeField(default=None,blank=True, null=True) internal_secondModelID=models.AutoField(primary_key=True) internal_firstModelID=models.ForeignKey(FirstModel,on_delete=models.CASCADE,default=None) def __str__(self): return self.secondModelName viewset.py from django.shortcuts import render from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from . models import FirstModel, SecondModel import datetime from . import models from . serializers import FirstModelSerializer, SecondModelSerializer class FirstModelViewSet(viewsets.ModelViewSet): serializer_class = FirstModelSerializer def get_queryset(self): firstModelDetails = FirstModel.objects.all() return firstModelDetails def retrieve(self, request, *args, **kwargs): params = kwargs pk = params['pk'] firstModel = FirstModel.objects.filter(firstModelName=pk) serializer = FirstModelSerializer(firstModel, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): data = request.data newFirstModel = FirstModel.objects.create( firstModelName=data["firstModelName"]) newFirstModel.save() serializer = FirstModelSerializer(newFirstModel) return Response(serializer.data) @staticmethod def getFirstModel(firstModelName): firstModel, created = FirstModel.objects.get_or_create( firstModelName=firstModelName) return firstModel class SecondModelViewSet(viewsets.ModelViewSet): serializer_class = SecondModelSerializer def get_queryset(self): secondModelDetails = SecondModel.objects.all() return secondModelDetails def retrieve(self, request, … -
How can I test that using Python?
I would like use that assertation : self.assertEqual(type(mytest), str) But I got that error : AssertionError: <class 'method'> != <class 'str'> How can I do to test the type method ? I tried that : self.assertEqual(type(mytest), method) But it does not work unfortunately Thank you very much ! -
I want to make a signup login ----etc with jwt
class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('user not found') if not user.check_password(password): raise AuthenticationFailed('incorrect password') payload ={ 'id': user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm=['HS256']).decode('utf-8') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'message':"success", 'jwt':token } return response class UserView(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('unauthenticated(not token)') try: payload = jwt.decode(token, 'secret', algorithm=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('unauthenticated~') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) here are my <views.py>codes... and why can't I make a LOGIN func??? ㅜㅜ (register func is very well done, but login is not working,, like 403forbidden..) please help me((())) -
Import a variable from another model django
I am trying to import only "is_ppc" from User models into the order models as ForeignKey. But I am not aware of the step on how to do it. Your assist will be highly appreciated. Order/models.py from django.db import models from users.models import User class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) partno = models.CharField(max_length=50) description = models.CharField(max_length=50) season = models.ForeignKey(Season, on_delete=models.CASCADE, null=True) style = models.CharField(max_length=50, blank= True) standard = models.PositiveIntegerField(default= 0) quantity = models.PositiveIntegerField(default= 0) limit = models.PositiveIntegerField(default= 0) created_date = models.DateField(auto_now_add=True) is_ppc = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,) Users/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_operation = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_ppc = models.BooleanField(default=False) I want only to import is_ppc from User model to Order model. -
Django paginator returning same data on seperate pages
Problem: I am developing an application in django that uses paginator for the list page of a model, it is set to display 25 instances of the model per page, when i view the first page everything works fine but when i move to the second page it shows some values from the first again. Details: snips of list for the first and second page First: https://imgur.com/tyY5xu0 Second: https://imgur.com/UcGWEFN (note CO01, 4 and 5 appear again) Views.py: def view_jobs(request): query_results = Job.objects.select_related('contract').order_by('-active', '-order_date') paginate = Paginator(query_results, 25) page_no = request.GET.get('page') page_obj = paginate.get_page(page_no) context = {"query_results": page_obj} return render(request, 'view_jobs.html', context) view_jobs.html: <table id="PageTable" class="table table-striped"> <thead> <tr> <th class="dropdown"> <a class="dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <h6>Number</h6> </a> </th> </tr> </thead> <tbody> {% for item in query_results %} <td> <small>{{ item|filter_prep:"order" }}</small> {% if item.help_text %} <small style="color: grey">{{ item.help_text }}</small> {% endif %} {% for error in item.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> <div class="pagination"> <span class="step-links"> {% if query_results.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ query_results.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ query_results.number }} of {{ query_results.paginator.num_pages }}. </span> {% if query_results.has_next %} <a href="?page={{ … -
create() takes 1 positional argument but 2 were given in python
models.py class UserAttributes(models.Model): airport = models.ForeignKey('airport.Airport', related_name='user_attributes_airport', on_delete=models.SET_NULL, null=True, blank=True) location = PointField(blank=True, null=True) user = models.ForeignKey( 'users.AerosimpleUser', related_name='user_attributes', on_delete=models.CASCADE, null=True, blank=True) views.py class LocationViewSet(viewsets.ModelViewSet): serializer_class=LocationRetrieveSerializer http_method_names = ['get', 'post', 'patch', 'put'] def get_permissions(self): switcher = { 'create': [IsAuthenticated], 'list': [IsAuthenticated], 'retrieve': [IsAuthenticated], 'update': [IsAuthenticated], 'partial_update': [IsAuthenticated], } self.permission_classes = switcher.get(self.action, [IsAdminUser]) return super(self.__class__, self).get_permissions() def get_queryset(self): return UserAttributes.objects.filter( airport__id=self.request.user.aerosimple_user.airport_id).order_by('pk') serializers.py class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' def create(self, validated_data): if UserAttributes.objects.filter(user_id=self.context["request"].data['user'],airport_id=self.context["request"].data['airport']).exists(): obj=UserAttributes.objects.get(user_id=self.context["request"].data['user']) obj.location=self.context["request"].data['location'] obj.save() return obj user_attributes = UserAttributes.objects.create(validated_data) return user_attributes what changes should i make -
Serializer create() methods sends 2 queries to DB
I have a serializer class MappingSerializer(ExtendedModelSerializer): default_landing_page_url = serializers.URLField(read_only=True) class Meta: model = models.Mapping fields = ('id', 'name', 'settings', 'campaign','default_landing_page_url') def create(self, validated_data): instance = super().create(validated_data) profile_id = instance.settings.integration.profile_id instance.default_landing_page_url = helpers.get_landing_page_url(profile_id, instance.campaign) instance.save() return instance In this case, there is a 2 queries into db,first when calling super().create(validated_data) and second is instance.save(). How can I avoid doing 2 queries with the same logic. I could add extra field validated["default_landing_page_url"] = helpers.get_landing_page_url(profile_id, instance.campaign) and then call super().create() but in this case I can't reach profile_id, which can be accessible only after instance is created -
Getting invalid Signature in django JSONWebTokenAuthentication for valid token
I keep getting invalid signature [Error 401:Unauthorized] when i try to authenticate user bearer token. My LoginSerializer generates jwt token for me and validates the user but when i try to use that token to access other Api endpoints, i get invalid signature error. UserLoginSerializer.py class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=255, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) user = authenticate(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except CustomerUser.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'email': user.email, 'token': jwt_token } In my settings.py, I set settings for the JWT authentications. JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': 'SECRET_KEY', 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': timedelta(days=30), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': False, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=30), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_AUTH_COOKIE': None, } In views.py, I have UserLoginView class to Retrieve user and fetch the token. class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = … -
values from views not getting rendered in HTML page using Django in pycharm IDE
I have copied a project on which I was working on using normal editor to Pycharm IDE so that I can debug further while developing the site. But when I run the project in pycharm, values are not getting rendered in HTML file but was when using editor. In pycharm, I have created venv and installed all the libraries. As a result, website also opens when python manage.py runserver is ran. But the values which I submit in the form, the values are not getting rendered somehow in html page. HTML snippet is given below. <div class="order-1 text-center sticky-top chartbutton border-bottom shadow-sm"> <form action="{% url 'trend' %}" method="post"> {% csrf_token %} {{ new_prodform }} <input type="submit" value="Submit"> </form> </div> <script type="text/javascript" class="var-class"> var prod_name, end_date; prod_name = '{{prod_name}}'; <!-- prod_name value is null here after submit --> end_date = '{{end_date}}'; <!-- end_date value is null here after submit --> </script> <script type="text/javascript" src="{% static 'trend/chart_plot.js' %}"></script> Views.py: if request.method == 'POST': filled_form = ProductForm(request.POST) if filled_form.is_valid(): product = filled_form.cleaned_data['product'] new_spform = ProductForm() prod_milestone = main_query_script(product) #some function to retrieve and return trend details in dict form context_dict.update(sp_milestone) context_dict.update({'new_prodform':new_prodform}) return render(request, 'trend/chart.html', context=context_dict) else: form = ProductForm() context_dict.update({'new_prodform':form}) return render(request, 'trend/chart.html', … -
Can't make migrations to django app after i added a new field to one of the models
So, this was my Category model before: class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title I had run makemigrations and migrate commands and the app was working just fine Then i had to add one more field to the model: class Category(models.Model): restricted = models.BooleanField(default=False) title = models.CharField(max_length=20) def __str__(self): return self.title Now when i run makemigrations, it gives the following error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: events_category first it gave "no such column" error, but i don't really care about the data right now so i deleted the sqlite file and all migrations and started over, that's when this error showed up The model has been set up as a foreign key in another model called Post: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default=DEFAULT_EXAM_ID) # and other fields... Can someone please help me perform migrations properly after i added this field?? -
How To Assign User in The Same Category To Each Other
I have had issues with this code and i seriously need help. I want to assign user to another user in the same payment category like a queue. There will be a sending users and a receiving user- the sending user will request for a payment of the amount in my category (for example $5, $10, $15) then the system will automatically assign the user to another user requesting to receive a payment in that category. Lets say it will be a queue and it will be first come first serve. user to user payment and a category to category user pairing or assigning to pay each others. please take a look at my code from django.db import models from django.contrib.auth.models import User from collections import deque d = deque('receiving') m = deque('sending') class PaymentCategory(models.Model): price = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, ) class Senders(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Receivers(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Payment(models.Model): senders = models.ForeignKey(Senders, on_delete=models.CASCADE) receivers = models.ForeignKey(Receivers, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE) def __init__(self, request, receivers=None, senders=None, *args, **kwargs): super(Payment).__init__(*args, **kwargs) if self.senders.paymentcategory.price == receivers.paymentcategory.price: senders.amount = receivers.amount def join_payment_users(self, request, receivers=None, senders=None, ): receiving_user = request.senders.user.amount sending_user = request.receivers.user.amount all_receiving_user = receivers.user … -
uwsgi process taking lots of memory
I'm working with Django + uwsgi and below are some main settings uwsgi [uwsgi] pythonpath=/usr/local/server chdir=/home/server env=DJANGO_SETTINGS_MODULE=conf.settings module=server.wsgi master=True pidfile=logs/server.pid vacuum=True max-requests=1000 enable-threads=true processes = 4 threads=8 listen=1024 daemonize=logs/wsgi.log http=0.0.0.0:16020 buffer-size=32000 When I try to get a excel file from my server the memory of one uwsgi process is growing fast and after seconds of time, browser get a Nginx 504 timeout but the memory is still growing. The file was about 30M generated by 450k rows data in my db. top -p 866 PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 866 soe 20 0 7059m 5.3g 5740 S 100.8 33.9 4:17.34 uwsgi --ini /home/smb/work/soe_server Main logic codes from openpyxl.writer.excel import save_virtual_workbook from django.http import HttpResponse ... class ExcelTableObj(object): def __init__(self, file_name=None): if file_name: self.file_name = file_name self.wb = load_workbook(file_name) else: self.wb = Workbook() def create_new_sheet(self, title='Sheet1'): new_ws = self.wb.create_sheet(title=title) def write_to_sheet(self, sheetname, datas, filename): ws = self.wb[sheetname] for data in datas: ws.append(data) self.wb.save(filename) def update_sheet_name(self, sheetname): ws = self.wb.active ws.title = sheetname def append_data_to_sheet(self, sheetname, data): ws = self.wb[sheetname] ws.append(data) def save_file(self, file_name): self.wb.save(file_name) self.wb.close() def get_upload_file_data(self, name=None): if name: ws = self.wb.get_sheet_by_name(name) else: ws = self.wb.worksheets[0] rows = ws.max_row cols = ws.max_column file_data … -
Reactifying a Django Project
I have a huge Django project that was built over the years with more than 50 apps. It is starting to show it's age, and i would like to use React for the front end. This will be a colossal task, that will take over 6 month of development I believe. My question is, is it possible to start "Reactifying" the project slowly? Like using React for certain url's/pages and use Django templates for the rest? This way we can still update the project normally, and slowly add React to the project. -
django - How to reuse a field from an existing table for django user authentication
A bit of information about Github repositories, libraries, blogs, etc. that might be helpful is fine. If you know of a better way to do this, please give me any advice you can. I'm not familiar with the concept of django or English, so I may be wrong about some things. ○Purpose: I would like to use the values of the existing TABLE fields (*1-3) in the existing DB being used in the existing system as is for user authentication (login with ID and password). If possible, I would like to make it expandable for later use. ○Other restrictions: In the current situation, if the authentication process can be performed and information such as EmployeeId can be used while logging in, we think there is no problem. (Adding/updating/deleting user information can be done using the existing system or by the administrator directly hitting the DB. We believe that the ability to add, update, and delete user information on the django side is temporarily unnecessary.) Since the django system is not running yet, you can delete all you want from the DB migration history, standard django tables, etc. We don't want to use the standard django tables or create additional tables … -
Accessing lists inside a dictionary with Django Template tags
Bit stuck on how to access list values within a dictionary. I've tried the following answers to no avail: Access Dictionary Value inside list in Django Template Accessing items in lists within dictionary python I am passing in through my view.py file the following: context = {'checkoutList': CheckoutList, 'cartItems': cartItems} return render(request, 'posts/checkout.html', context) A queryset I am trying to access is Checkoutlist, and is as follows: {'id': [30, 6], 'title': ['Lorem Ipsum', 'another title'], 'location': ['Multiple Locations', 'city2'], 'imageurl': ['/media/image/img.jpg', '/media/image/img.jpg'], 'url': ['/products/lorem-ipsum', '/products/another-title']} I am trying to access the list values in my Checkout.html page but I can't figure out how. Currently I can get the key and the entire list value, see below: {% for key, value in checkoutList.items %} {{key}} {{value}} {% endblock %} This is returning the key values and the entire list, not the values inside the list. id [30,6] title ['Lorem Ipsum', 'another title'] etc.. What I am actually after is the values in the list on each for loop first iteration 30 lorem ipsum multiple locations second iteration 6 another title city2 etc How do I get the values like this? -
Can anyone Help us integrate Power Bi embed with Python Django Framework
We have Built an application using Python Django Framework, now need to Integrate the Power Bi Embed in the same application. all the Available resources are made for Flask. and we are not able to use the logic in Django. -
Cannot force an update in save() with no primary key. in django?
#admin.py from django.contrib import admin from studetails.models import Branches admin.site.register(Branches) #models.py from django.db import models class Branches(models.Model): STATUS = ( ('ACTIVE', 1), ('INACTIVE', 0) ) id = models.AutoField(primary_key=True) branchname = models.CharField(max_length=50) pro_pic = models.FileField(null=True) status = models.CharField(max_length=30, choices=STATUS) What is the save option I have to place in this model as I am not getting this error? -
Django template large data pagination link issue
I am using the django paginator in my template. Its working ok with less data, but not working good when there's large numbers of pages. Pagination links code is given bellow: <div class="paginationWrapper mt-3"> {% if match_list.paginator.num_pages > 1 %} <ul class="pagination"> {% if match_list.has_previous %} <li> <a href="?p={{ match_list.previous_page_number }} {% if request.GET.search %}&search={{ request.GET.search }} {% endif %}" class="page-link"><i class="fas fa-angle-double-left"></i></a> </li> {% endif %} {% for j in match_list.paginator.page_range %} {% if match_list.number == j %} <li class="active"><a class="page-link" href="#">{{ j }}</a></li> {% else %} <li><a href="?p={{ j }}{% if request.GET.search %}&search={{ request.GET.search }} {% endif %}" class="page-link">{{ j }}</a></li> {% endif %} {% endfor %} {% if match_list.has_next %} <li> <a href="?p={{ match_list.next_page_number }} {% if request.GET.search %}&search={{ request.GET.search }}{% endif %} " class="page-link"><i class="fas fa-angle-double-right"></i></a> </li> {% endif %} </ul> {% endif %} </div> After this i am gettin the links in my template like : what i actually want is i want to display only 10 links after that ... to show more can anyone please help me relatred this i am stuck here