Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx Open file Cache Increased memory
I have a website where I am giving load 800RPS. My nginx configuration for open file cache is given below. open_file_cache max=10000 inactive=30s; open_file_cache_valid 60s; open_file_cache_min_uses 2; open_file_cache_errors on; At beginning it is giving good performance but after sometime, It is consuming more memory. Can anyone tell me why and what is exact config. -
How to annotate with count in Django using datetimes() queryset function
In my application users visit a center to take examinations. Each day they can take one two or more examinations. I would like to filter all users that have visited the center more than 3 times (regardless of the number of examinations). I don't store visit count. I only store examination data for each user. So, in order to get the number of times a user has visited the center (regardless of the number of examinations they had on each day) I do this: user.examinations.all().datetimes('added', 'day').distinct().count() for this model. class Examination(models.Model): user = models.ForeignKey(User, related_name='examinations') added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) How can I annotate this value (number of visits to the center) to a set of filtered users? e.g.: User.objects.all().annotate(Count('examinations__added')).distinct() (keep in mind that added is a DateTimeField) PS: For this project I am using Python 2.7 and Django 1.8. -
Python failed when trying to log into admin page of Django
I set up Django in Pycharm and try to log into the admin page,however,the page failed. I was able to open the page where I am supposed to enter the username and password,but when I click the 'enter'button it just crash and showing that Python has failed.It really makes me confused... The picture shows the situation. -
how to find if a specific channel is online django channels?
I am working on a django project with django 2.2.1 installed and channels 2.3.0 with having redis as channel layer backend. I store every channel_name in a database(in connect method of consumer). I want to know other than deleting channel_name on disconnect is there any other way to find out if a specific channel_name is still online? -
Django (only when running with wsgi) throws "Internal server error Sorry, there seems to be an error." Please try again soon template
I want to deploy my django/wagtail app using wsgi. When I tried to run code locally, to check if everything works it seemed to work - curl returned html of correct site. BUT - when I ran uwsgi (after using fuser -k 8054/tcp): uwsgi --http 127.0.0.1:8054 --chdir /home/ketohubp/KetoHub.pl --wsgi-file /home/ketohubp/KetoHub.pl/Wagtail_Django_Static_Blog/wsgi.py --master --processes 1 -- workers 1 --threads 1 --daemonize=/home/ketohubp/KetoHub.pl/log.txt And then called curl: (venv) ketohubp@hs7:~/KetoHub.pl$ curl localhost:8054 <!DOCTYPE html> <html class="no-js"> <head> <meta charset="utf-8" /> <title>Internal server error</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <h1>Internal server error</h1> <h2>Sorry, there seems to be an error. Please try again soon.</h2> </body> </html> It shown an error. I tried adding ALLOWED_HOSTS = ['*'], but it changed nothing. uwsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Wagtail_Django_Static_Blog.settings.production") application = get_wsgi_application() vhost: DocumentRoot /home/ketohubp/KetoHub.pl WSGIScriptAlias / /home/ketohubp/KetoHub.pl/Wagtail_Django_Static_Blog/wsgi.py WSGIDaemonProcess ketohub.pl processes=2 threads=15 display-name=%{GROUP} python-home=/home/ketohubp/venv python-path=/home/ketohubp/KetoHub.pl WSGIProcessGroup ketohub.pl WSGIApplicationGroup %{GLOBAL} <directory /home/ketohubp/KetoHub.pl> SetHandler wsgi-script AllowOverride all Require all granted Options ExecCGI FollowSymlinks <Files wsgi.py> Require all granted </Files> </directory> Alias /static/ /home/ketohubp/KetoHub.pl/Wagtail_Django_Static_Blog/static/ <Directory /home/ketohubp/KetoHub.pl/Wagtail_Django_Static_Blog/static> Require all granted </Directory> Comment if you want to ask about other files. -
ModuleNotFoundError: No module named 'textencoder' error when upgraded to python 3
Currently I have migrated my python2 django project to python 3 & after conversion to py3 I am getting below kind of error for below code. from hubarcode.code128 import Code128Encoder encoder = Code128Encoder(pur_num, {'is_reliable': False}) Trackeback is as below. from hubarcode.code128 import Code128Encoder File "D:\production\sparrow_v2\venv\lib\site-packages\hubarcode\code128__init__.py", line 16, in from textencoder import TextEncoder ModuleNotFoundError: No module named 'textencoder' I have tried to search for solution online on google but not able to solve it. Any suggestions ? Thanks. -
Django Rest Framework - exclude group from using viewsets
I would like to restrict the api usage of a certain group to only one view @api_view(['POST]) def get_something(request): # let's do something here... return Response(...) whereas all ViewSets and ModelViewSets should return a 403 or 405 error. What is the best practice for doing so? So far I checked for the request.user.groupin the class methods e.g. class MyModelViewSet(ModelViewSet): ... def list(request): if restricted_group in request.user.groups.all(): return Response(status=Http_403) else: return super(list, ...) -
value too long for type character varying(25)
I have troubles uploading a CSV file into my database, when I try to upload the file I get a "value too long for type character varying(25)" error message for the field performance_exccy (see below for my django model). This error message started occuring when I switched from SQLite to PostgreSQL (using ElephantSQL), with SQLite the upload worked out perfectly. The value causing the problem was 0.000000000000000000, which has 20 characters, but in my model I defined max_digit = 40 and dec_places =20 - so the number of digits should not be an issue. What I also noticed is that the upload error did not start with the first row of the CSV file but with the 12th row, with the rows before having values of similar lenght. My model: class Testdata3(models.Model): key = models.CharField(max_length=100, primary_key=True) mnemonic = models.CharField(max_length=50) assetclass = models.CharField(max_length=25) value = models.DecimalField(max_digits=25,decimal_places=10) performance = models.DecimalField(max_digits=40,decimal_places=20) performance_exccy = models.DecimalField(max_digits=40,decimal_places=20) performance_abs = models.DecimalField(max_digits=40,decimal_places=20) performance_abs_exccy = models.DecimalField(max_digits=40,decimal_places=20) date = models.DateField() def __str__(self): return self.key My view: def file_upload(request): template = "upload.html" prompt = { 'order': 'Order of the CSV should be "placeholder_1", "placeholder_2", "placeholder_3" ' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): … -
nginx: [warn] conflicting server name "domain" on 0.0.0.0:80, ignored
I've bought domain, deployed my django application to digitalocean, but this error doesn't let me use application. How can I ignore this error ? Here are my codes: setting.py: ALLOWED_HOSTS = ['blablabla.com', '64.225.12.157'] nginx: server { listen 80; server_name blablabla.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/sammy/myproject/myproject.sock; } } -
Python3 - Django2 - TypeError: __init__() missing 1 required positional argument: 'on_delete'
I have recently migrated my project from python2 to python3 and it has hundreds of ForeignKey relations. Using the solution to go line by line and add on_delete argument is not possible. What can be the alternate way of resolving this error? I have tried editing the library where I can add the argument in the init function with a default value but it doesn't look like catching it sometimes. -
Trouble integrating jquery/ajax into django project
I am relatively new to coding and am having problems getting jquery/ajax to work in my django/bootstrap project. At the start of my header I have included the following code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> However, when trying to run a simple function: <script> {% block jquery %} var endpoint='/api/data/' $.ajax({ method: 'GET', url: endpoint, success: function(data){ console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) {% endblock %} I keep getting the same two errors displayed in the console: jquery.min.js:2 jQuery.Deferred exception: $.ajax is not a function TypeError: $.ajax is not a function at HTMLDocument.<anonymous> (http://127.0.0.1:8002/chart/:87:7) at e (https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js:2:29453) at t (https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js:2:29755) undefined Uncaught TypeError: $.ajax is not a function at HTMLDocument.<anonymous> ((index):87) at e (jquery.min.js:2) at t (jquery.min.js:2) Most answers that I have seen here seem to revolve around installing the slim version of jQuery that does not include Ajax. However, I believe that this is not the case here. Would greatly appreciate any help! -
sudo permission denied in SSH terminal
I Have a Django Project and have uploaded in cPanel via FileZilla . I want to instlall Django and PIP via SSH terminal . I am getting an error "bash: /bin/su: Permission denied" (MyDjangoEnv) epaysave@epaysave.com [~/public_html/epaysave.com/epaysave/epaysave_stageone]# sudo yum install python-pip [sudo] password for epaysave: epaysave is not in the sudoers file. This incident will be reported. (MyDjangoEnv) epaysave@epaysave.com [~/public_html/epaysave.com/epaysave/epaysave_stageone]# su epaysave bash: /bin/su: Permission denied -
Changing MEDIA_ROOT in open edx not working
I want to change where my courses are exported to in open edx but I'm facing certain issues. I have tried changing my MEDIA_ROOT in edx-platform/lms/envs/common.py from /edx/var/edxapp/media/ to /edx/app/edxapp/edx-platform/media/ however the course is still being exported to /edx/var/edxapp/media/ instead of /edx/app/edxapp/edx-platform/media/. I tried printing my MEDIA_ROOT in the studio shell and it shows that my MEDIA_ROOT has been changed to /edx/app/edxapp/edx-platform/media/ however it is still exporting the course to /edx/var/edxapp/media/. Any help will be much appreciated. -
How to loop 'add' tag in Django template?
I want to count how many Product variations available in each Market. For now I'm only able to count Product variations for each Distributor. I'm thinking about using 'add' built-in template tag to sum Product variation in each Distributor to solve this problem, but don't know how to implement this in template for loop. Or is there any better solution? I'm open for suggestions. My 4 related models in Django: class Market(models.Model, RecordStatus): name = models.CharField(max_length=100) class Country(models.Model): market = models.ForeignKey(Market, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=100) class Distributor(models.Model, RecordStatus): headquarter = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) class ProductStock(models.Model): distributor = models.ForeignKey(Distributor, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) stock = models.PositiveIntegerField(null=True, blank=True) My views.py: def market_list_view(request): markets = Market.objects.all() context = { 'market_list': markets, } return render(request, 'product_visualizers/market_list.html', context) My current attempt on market_list.html template: {% for market in market_list %} <h3>{{market.name}}</h3> <p>{% for country in market.country_set.all %} {% for distributor in country.distributor_set.all %} {{ distributor.productstock_set.all|length }} # should I write |add besides |length to sum the numbers? {% endfor %} {% endfor %}</p> {% endfor %} What should I code in the nested for inside the template? -
Django: Query for __range
I created the following query but receive the following error SyntaxError: positional argument follows keyword argument. The problem seems to be created__range(start_date, end_date). created is a timestamp saved in the following format: 2019-12-10 21:01:58.309276+00 start_date = datetime.date(2019, 10, 1) # Filtering a DateTimeField with dates won’t include items on the last day, # because the bounds are interpreted as “0am on the given date”. end_date = datetime.date(2019, 11, 1) Order.objects.filter( event__organizer=176, created__range(start_date, end_date), status__in=( OrderStatus.PAID, OrderStatus.REFUNDED, OrderStatus.PARTIALLY_REFUNDED, ) ).count() -
What Is The Best Way To Translate Dynamic Texts in Django?
I want to translate completely random texts users create in my service. Users will create texts in each one of their language. And I want to auto-translate it and provide in other multiple languages. I looked at Django-Translation, but it does not seem to work for completely dynamic content. I do not have a format. I want random texts users generated to be translated in other languages. When I first glanced at Django-modeltranslation, I misunderstood that it would auto-translate an original field into other language fields, but it was not. It just adds fields for to-be-translated languages, but no more. Is the only solution using third party apps such as Google Translate or Transifex? If I want to use them, I will need to send requests to their servers and wait until the translation arrives. Or I can make the client side to send the request to translation service providers' servers and send my Django server an already-translated texts package. For the last option, I was looking into directly using GNU gettext() using Python, but it does not seem to be feasible. I cannot find any example that used .PO and .MO for translating real-time dynamic texts. But I am … -
Celery: Instance becomes slow after a week or two
I have a django app with a celery instance that consumes and synchronizes a very large amount of data multiple times a day. I’ll note that I am using asyncio to call a library for an API that wasn’t made for async. I’ve noticed that after a week or so the server becomes painfully slow and can even become days behind in tasks after a few weeks. Looking at my host’s profiler the RAM or CPU usage isn’t going wild, but I know it’s becoming slower and slower every week because that celery instance also handles emails at a specific time which send out hours and hours later as the weeks pass. Restarting the instance seems to fix everything instantly, leading me to believe I have something like a memory leak (but the ram isn’t going wild) or something like unclosed threads (I have no idea how to detect this and the CPU isn’t going wild). Any ideas? -
Django autocomplete-light not populating output
I am new to Django ,in my project im using Django 2.2 and django-autocomplete-light 3.3 with below given code.but autocomplete is not working with 'asset_type' field.i have tried in many ways but no useful.Please fix this issue. template page : {% extends 'header.html' %} {% load static %} <link href="{% static '/autocomplete_light/select2.css' %}" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="{% static '/autocomplete_light/autocomplete.init.js' %}"></script> <script type="text/javascript" src="{% static '/autocomplete_light/select2.js' %}"></script> <script type="text/javascript" src="{% static '/autocomplete_light/forward.js' %}"></script> {% block content %} <strong><h2 class="text-success"> {{result}} </h2></strong> <h3 class="text-warning">Stock In Form:</h3> <br> <div class="form-group"> <form method="POST"> <table class="table table-bordered"> {% csrf_token %} {{ form.as_table}} </table> <input type="submit" class="btn btn-primary" value="Submit"> </form> </div> {{form.media}} {% endblock %} forms.py : from django import forms from stock.models import stock_in from stock import models from dal import autocomplete class stock_inward(forms.ModelForm): class Meta: model = stock_in fields = ('asset_type','category','subcategory','model_name','manufacturer','serial_no','invoice_date','warranty_date','vendor_name','price') widgets = { 'asset_type':autocomplete.ModelSelect2(url='/assettype_autocomplete/'), model.py is : from django.db import models from django.utils import timezone # Create your models here. class asset_type(models.Model): asset_type = models.CharField(max_length=252,unique=True) def __str__(self): return self.asset_type class category(models.Model): asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE) category = models.CharField(max_length=252,unique=True) def __str__(self): return self.category class subcategory(models.Model): asset_type = models.ForeignKey('asset_type', on_delete=models.CASCADE) category = models.ForeignKey('category',on_delete=models.CASCADE) subcategory = models.CharField(max_length=50,unique=True) def __str__(self): return self.subcategory class model_details(models.Model): … -
Creating python registration with pre-built template
I've been working with django for a week or two now. I had made a template wit css styling before I started working on my django project. I made signup and signin template but I found that there's no way to link fields with backend and I have to create form in django first. This is my html template but I'm unable to see the django form in the signup.html <form method="POST"> {% csrf_token %} <fieldset class='form-group'> <legend class='border-bottom-mb mb-4'>Join Today</legend> {{ form.as_p }} </fieldset> <div class='form-group'> <button type="submit" class="btn-submit">Sign Up</button><br> </div> <div class="border-top pt-3"> <small class="text-muted"> Already have an account? <a class="ml-2" href="#">Sign In</a> <small> </div> </form> views.py (users app) def signup(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect('web-home') else: form = UserCreationForm() return render(request, 'users/signup.html', {'forms': form}) urls.py(django project file) from django.contrib import admin from django.urls import path, include from users import views as users_view urlpatterns = [ path('admin/', admin.site.urls), path('signup/', users_view.signup, name='signup'), path('', include('web_home.urls')), ] How can I make my pre-built template with css styling use the django registration functionality? -
Bearer Token extraction from request django
If I have a post request with this JSON : { "user_id":230, "name":"Anthony" } I can extract the name by : name = json.loads(request.body).get("name") Now I have a GET request in which I am passing bearer token. How should I extract it in Django? -
URL doesn't exist after creating
Here's my views.py: class LanguageViewSet(viewsets.ModelViewSet): queryset = Language.objects.all().order_by('name') serializer_class = LanguageSerializer class FrameworkViewSet(viewsets.ModelViewSet): queryset = Framework.objects.all() serializer_class = FrameworkSerializer class SelectedLanguageViewSet(viewsets.ModelViewSet): queryset = Language.objects.all() serializer_class = FrameworkSerializer def get_queryset(self): request = self.request language_id = request.query_params.get('language_id') language = Language.objects.filter(id=language_id) self.queryset = language.framework_set.all() return self.queryset And my urls.py: router = routers.DefaultRouter() router.register(r'languages', views.LanguageViewSet) router.register(r'frameworks', views.FrameworkViewSet) router.register(r'language/<int:language_id>', views.SelectedLanguageViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] However, only languages and frameworks work. language doesn't exists. Is this because of the get_queryset? I even tried removing the <int:language_id> in the url params but it still won't show up. EDIT: Forgive my naiveness, I'm quite new to django and DRF -
Django development server stops after logging into admin
I have installed django 3.0 in python 3.7 and started a basic django project. I have created a superuser and run the development server using python manage.py runserver. When I go to localhost:8000/admin it shows me ui to login after I entered my credentials it redirects back to localhost:8000/admin but at that time server stops running without any error on console. The last message I see in log file is (0.002) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2019-12-11T08:52:16.929697+00:00'::timestamptz AND "django_session"."session_key" = 'tqpcf2gv6iqatc42pdmz6zdjpy7iri37') LIMIT 21; args=(datetime.datetime(2019, 12, 11, 8, 52, 16, 929697, tzinfo=<UTC>), 'tqpcf2gv6iqatc42pdmz6zdjpy7iri37') (0.002) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 LIMIT 21; args=(1,) Has someone faced this issue? What could be the solution? -
How to filter with ManyToMany field .?
Offer has multiple products. When I try to print the details of the selected products, it shows some errors Model class Products(models.Model): name = models.CharField(max_length=30) price = models.CharField(max_length=30) class Offer(models.Model): offer = models.IntegerField(default=0) products = models.ManyToManyField(Publication) Serializer class ProductSerializer(serializers.ModelSerializer): class Meta: model = Products fields = ['name', 'price'] class OfferSerializer(serializers.ModelSerializer): products_list = serializers.SerializerMethodField() class Meta: model = Offer fields = ['id', 'offer', 'products_list'] read_only_fields = ['id'] def get_products_list(self, instance): products_id = instance.products products = Products.objects.filter(id=products_id) return ProductSerializer(products, many=True).data Error TypeError: int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager' -
Django Admin Navigation Bar in backend
Can anyone help me in adding Navigatinon Bar in Django Admin Panel in Backend. I have to generate some customized reports using Aggregate function link Sum, Count, Group by on models. Sample Demo Example (https://www.google.co.in/search?q=django+admin+navigation+menu&prmd=ivn&sxsrf=ACYBGNSHJG7vHN1SDOrm9hRuJHm__qvEOg:1576052777763&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjGuNyPlq3mAhX763MBHelFCf0Q_AUoAXoECA8QAQ&biw=412&bih=778&dpr=2.63#imgrc=RRwoZAKmLNBCDM) -
Django User model foreign key
I'm struggling writing a relational database in Django. Basically what I am trying to achieve is to create a user foreign key to one of the tables. I found plenty of similar questions over here but for some reason, it doesn't seem to work on my cause, maybe it's because of the version or I don't know. This is my model: from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) and for autenthification I used the build-in functionality path('api-auth/', include('rest_framework.urls')), and this is the error that I get: IntegrityError at /category/ NOT NULL constraint failed: category_category.user_id Request Method: POST Request URL: http://127.0.0.1:8000/category/ Django Version: 2.2.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: category_category.user_id Exception Location: C:\Users\Terkea\Anaconda3\envs\django_api_template\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users\Terkea\Anaconda3\envs\django_api_template\python.exe Python Version: 3.7.5 Python Path: ['C:\\Users\\Terkea\\PycharmProjects\\django_api_template', 'C:\\Users\\Terkea\\PycharmProjects\\django_api_template', 'C:\\Program Files\\JetBrains\\PyCharm ' '2019.2.3\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\python37.zip', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\DLLs', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\lib', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2019.2.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Wed, 11 Dec 2019 08:08:11 +0000