Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
uwsgi segmentation fault for one specific route
My django apps works correctly locally, but when I deployed it facing a uswgi seg fault for one specific route. Every others routes works correctly. Here the view: def bunny(request): """ Filter crawler, bot and real user :param request: :return: serve rendered page to crawler / SPA to user """ ......some other codes .... path = request.get_full_path_info() if path.startswith('/news_paper'): # <<-- seg fault for this routes only in production server news_paper = utils(unquote(path[12:])) if news_paper[1] == 0: # if news paper is not found return default list return render(request, 'site_list.html') news = News.objects.filter(news_paper=news_paper[1]).order_by('-created_at')[:15] return render(request, 'news.html', {'news': news, 'title': news_paper[0]}) elif path == '/about/': return render(request, 'about.html') else: return render(request, 'site_list.html') uWsgi conf file: [uwsgi] chdir=/home/.. home = /home/../.env module=xyz.wsgi master=True process = 5 pidfile=/run/xyz.pid socket= /run/xyz.sock stats=/tmp/xyz.stat vacuum=True max-requests=500 logto = /home/../logs/xyz.log log-maxsize = 200480 uid = prism gid = www-data die-on-term = true chmod-socket = 666 chown-socket = www-data and the log file: !!! uWSGI process 4668 got Segmentation Fault !!! *** backtrace of 4668 *** uwsgi(uwsgi_backtrace+0x2c) [0x46d0ac] uwsgi(uwsgi_segfault+0x21) [0x46d471] /lib/x86_64-linux-gnu/libc.so.6(+0x354b0) [0x7f1c373b84b0] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_cleanup_key_block+0xb) [0x7f1c32d3fcab] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_clear+0x16) [0x7f1c32d3d5a6] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(tls1_clear+0x9) [0x7f1c32d49219] /usr/lib/x86_64-linux-gnu/libssl.so.1.1(SSL_new+0x462) [0x7f1c387a5d22] /home../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x23969) [0x7f1c32fd4969] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x24fc5) [0x7f1c32fd5fc5] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectPoll+0xb78) [0x7f1c32fbfba8] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0xfa28) [0x7f1c32fc0a28] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectdb+0x1f) [0x7f1c32fc341f] /home/../.env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x12651) [0x7f1c33214651] /home/../.env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x133df) [0x7f1c332153df] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x16cb06) [0x7f1c37af1b06] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x8b) [0x7f1c37aa810b] … -
Django - Request resolution
I would like to know how Django is resolving request urls urlpatterns in general. My theory: Django at some point turns all its urlpatterns into list of regexes, and then tries to match them against incoming Request's url. Question: Am I correct? If yes, can somebody point me out where in source code is this happening? Looks like there is nothing about this mentioned in django docs, and I feel like I am doing a blind search in source code. Any insights appreciated. -
Django: Table Doesn't exist after shifting MySQL db to server MySQL
Summary: After uploading mysql "site_dump.sql" into server MySQL, and applying proper settings to point to database, I get error 'Table doesn't exist' Error Details: ProgrammingError: (1146, "Table 'evaluation.Evaluator_skill' doesn't exist") Observations: Only User table is showing all the data I had. All other tables are throwing the same error . If I login to MySQL shell, use that new db, and see table data, all the tables and their data is present. What I did exactly: On my local PC, took a sql dump like this: mysqldump -u root -p --databases db_name > mysite_26_11_2018.sql Copied this file into server. Launched MySQL shell on server using root username and created a new db: mysql>create database db_server; Then on prompt uploaded the copied db like this: mysql -u root -p db_server < mysite_26_11_2018.sql Again logged-in to mysql, and execute these steps: mysql>create user server_admin identified by 'admin_password'; mysql>grant all on db_server.* to 'server_admin'@'%'; mysql>flush privileges; What I tried: - 1) Ran makemigrations amd migrate, but no changes . 2) Checked using MySQL shell that all data is present in t he db . 3) Checked using django shell that User data is all present but all other tables give the same error. -
Identify origin of POST request in Django (Active Campaign)
I have set up a webhook to receive POST requests from the Active Campaign API in order to update my CRM data. The problem is that Active Campaign doesn't send any token or credential information with the POST request, so I cannot be sure that the request is really coming from them. Is there a way in Django to check where the request is coming from, in order to prevent anyone from sending POST data to this webhook? -
The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'
I am trying to implement django-audiofield app into my model but i get the following error. ERRORS: audiofield.AudioFile: (auth.E005) The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'. I've done everything according to the docs and can't find where is the problem... -
Django JSONField filter greater than an attribute value
I have the following Django model: class Student(models.Model): student_id = models.CharField(primary_key=True, max_length=10) student_info = JSONField() My data looks like: { “student_id": “1", “student_info":{ “student_name": “Parker", “age": "21", “num_classes": “5", “highest_score": “75", “credits_complete": “13”, “credits_remaining”:”20" } } I want to select all students with credit complete greater than 13. I tried the following which returns me an empty Queryset: Student.objects.filter(student_info__credits_complete__gt='13’) Any idea how to filter greater than or less than the attribute value in JSONField? Thanks! -
How to create union of two different django-models?
I have two django-models class ModelA(models.Model): title = models.CharField(..., db_column='title') text_a = models.CharField(..., db_column='text_a') other_column = models.CharField(/*...*/ db_column='other_column_a') class ModelB(models.Model): title = models.CharField(..., db_column='title') text_a = models.CharField(..., db_column='text_b') other_column = None Then I want to merge the two querysets of this models using union ModelA.objects.all().union(ModelB.objects.all()) But in query I see (SELECT `model_a`.`title`, `model_a`.`text_a`, `model_a`.`other_column` FROM `model_a`) UNION (SELECT `model_b`.`title`, `model_b`.`text_b` FROM `model_b`) Of course I got the exception The used SELECT statements have a different number of columns. How to create the aliases and fake columns to use union-query? -
using templatetags with if in Django
I'm using Django 2.x. I have a simple_tag with returns True or Flase. from django import template register = template.Library() @register.simple_tag(takes_context=True) def aws_require(context): print('test') request = context['request'] if request.user: return True return False Now, I'm using it in the template {% load accounts_tag %} {% aws_require as aws_r %} {% block force_popup %} {% if aws_r %} {% include 'base/force_popup.html' with aws_status=aws_status %} {% endif %} {% endblock force_popup %} But it seems to be not working. It does not go inside if block. I tried printing something in the template tag print('test') but it is not printing in the console log as well. -
Django : Custom save method with queryset
I'm trying to create a custom save method in my model and I would like to get your help in order to improve this one. I'm generating a unique code based on some variables in my form. I generate the code and I make a research before to save it. If another document already gets this code, I generate another one, else I save the object. This is my save() method in my models.py file : def save(self, *args, **kwargs): import random self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}" document = Document.objects.filter(code=self.code) if document: self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}" super(Document, self).save(*args, **kwargs) I think it could me improved, by while instead of if condition. What do you think about it ? Thank you -
How to show Kibana Visualization dashboard in Website?
I have a csv file and I have passed through the ElasitcSearch and create a dashboard in Kibana. Is there any way to display this dashboard in the website. Like any bootstrap kind of script available? Or Any other way to embed in Django or Flask frame work -
Django filter ManyToMany filed in query
I need to filter field with ManyToMany in queryset. There must stay only active Products class Product(model.Model): name = models.CharField(max_length=100) active = models.BooleanField(blank=True, default=True) class Package(model.Model): name = models.CharField(max_length=100) products = models.ManyToManyField(Product) I tried something like this. packages = Package.objects.all() for package in packages: active_products = package.products.filter(active=True) package.products = active_products but it updates my packages in database, when i need only change queryset. expectation: packages = [ {'id': 1, 'name': 'First package', 'products': [ {'id': 1, 'name': 'first product', 'active': True}, {'id': 2, 'name': 'second product', 'active': True}, ]}, {'id': 2, 'name': 'Second package', 'products': [ {'id': 2, 'name': 'first product', 'active': True}, {'id': 3, 'name': 'third product', 'active': True}, ]} ] I thought about creating a list of dictionaries from Packages by .values(), then iterate it and exclude all not active products. Do you know any more elegant way to do it? -
django rest framework " TypeError: 'type' object is not iterable " error
I do not know what configuration to modify. My git repository URL : https://github.com/Nomadcoders-Study/Nomadgram Internal Server Error: /images/all/ Traceback (most recent call last): File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/rest_framework/views.py", line 478, in dispatch request = self.initialize_request(request, *args, **kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/rest_framework/views.py", line 380, in initialize_request authenticators=self.get_authenticators(), File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/rest_framework/views.py", line 274, in get_authenticators return [auth() for auth in self.authentication_classes] TypeError: 'type' object is not iterable -
uwsgi.ini says the Address already in use but running uwsgi with parameter works
If I run the uwsgi command this way and then start nginx then my site loads up and it works fine. uwsgi --socket site1.socket --module main.wsgi --chmod-socket=777 However if I use an wsgi.ini with the following content [uwsgi] # ----- Django-related settings ----- # the base directory (full path) chdir=/home/ec2-user/fooVenv/fooWeb/ # Django's wsgi file module=main.wsgi # the virtualenv (full path) home=/home/ec2-user/fooVenv/ # pidfile=/path/to/site1.pid # max-requests=5000 # ----- process-related settings ----- # master master=true # maximum number of worker processes processes=1 # the socket (use the full path to be safe) socket=/home/ec2-user/fooVenv/fooWeb/ # ... with appropriate permissions - may be needed #chmod-socket=664 chmod-socket=777 # clear environment on exit vacuum=true and then run the file using uwsgi --ini uwsgi.ini I get the error ... ... thunder lock: disabled (you can enable it with --thunder-lock) error removing unix socket, unlink(): Is a directory [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] Any suggestions on why this might be happening ? -
Migrations can't run due to evaluation of QuerySet in Serializer?
Trying to solve this chicken-and-egg issue. I've defined a new model which an existing model foreign keys into, and made the new migrations, including a data migration that provisions some defaults for the new model. In the serializer for the existing model, I wanted to define a default like so: new_thing = serializers.PrimaryKeyRelatedField( queryset=NewThing.objects.all(), default=NewThing.objects.get(id=DEFAULT_NEW_THING_ID), ) I don't understand django's specific mechanism, but this seems to cause problems while running the migrations (although the makemigrations seems fine). It seems the migration runs a series of app checks on the views and eventually the serializer, where it evaluates the NewThing QuerySet and returns an error that the relation for NewThing does not exist (since the migration hasn't been run yet). -
Why we are using @property decorator in Django?
As we know Django provides several decorators that can be applied to views to support various HTTP features. I've seen property but unable to understand why it's needed? class Test(object): @property def hi(self): return "hello" Test().hello # 'Hello, world!' Thanks in advance. -
Does Django multiple database support generate tables for only some specific apps in a database
I aim to store history of tables using django-simple-history library in a seperated database from the main one. When I run migrate --database=the_second_db, django generates all tables for all apps in the second database. How can I make it just generate some specific tables for specific apps that I need in the second database( history tables)? -
Django: Saving in Many To Many Field by adding new data in field
I have a model of Products that can be saved/owned by Users. class Product(models.Model): owner = models.ManyToManyField(User, blank=True) The original owner of the product is Adam. However I would like to allow another user, Eve to own the product as well. def saveProd(request, product_slug): if request.method == "POST": product = Product.objects.get(slug=product_slug) product.owner = request.user ***product.save()*** return redirect('home:saved') But I can't use product.save as it will change the owner in the ManyToMany Field. I just want another user added to the owner. How should I finish the code? Thank you. -
How to modify my poll app models in quiz app?
from django.db import models import time from django.utils import timezone # Create your models here. class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField('date published') def __str__(self): return self.question_text # def was_published_recently(self): # return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question=models.ForeignKey(Question, on_delete=models.CASCADE) choice_text=models.CharField(max_length=200) vote=models.IntegerField(default=0) def __str__(self): return self.choice_text Above code is poll app there are a question has multiple choices and a vote field this is countable, but i want to make quiz app since how to modify this models for making quiz app model? -
Django permissions group by model
I want to make structure like below modelName View Add Change Delete Group Y Y Y Y User Y Y Y Y I seeking data by using user = User.objects.get(username='test') perm = Permission.objects.filter(Q(group__user=user)|Q(user=user)).distinct() Now returning Model Permission log entry view_logentry Demo change_demopurpose group add_group group change_group group delete_group But need to grouping -
adding highlighted code snippets into posts in django
I created a blog in django where i upload posts. so , sometimes you need to add code snippet for the better understanding. for that i used some code highlighting techniques like prismjs and markdown. Now i can upload a code snippet using "pre" and "code" tags like this i am using right now. <pre><code class="language-python"> {% autoescape on %} {{ snippet.code }} {% endautoescape %} </code></pre> and look at my post detail file... <div align="left"> <p>{{ obj.content|capfirst|linebreaks }}</p> </div> now what is want is while writing post i should be able to add snippets in between the text content and also should be able to write content afterwards. means a post contains a paragraph and then code snippet and then paragraph again and continue. -
How to call a method from a Django Class Model to a Django field?
I have created the following Django Model and I am trying to initialize one field - points - with the total number of instances of that same model, that is: class Task(models.Model): DEFAULT_VALUE = 5 description = models.CharField(max_length=60) points = self.total() * DEFAULT_VALUE STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done')) status = models.CharField(max_length=1, choices=STATUS, default='A') def total(self): count_active = len(Task.objects.filter(status='A')) return count_active In the python manage.py shell I can create two instances of Task and I can determine the total number of the instances that have been created with len(Task.objects.filter(status='A'))), however, when I try to implement this same code into a function then I encounter that self is an unresolved reference. What did I miss? -
How to display user computer display name in #Djangos, #python
Apologies if its duplicate query, I am not able to find the answer for my question posting here. I have developed a webpage in Djangos hosted in development server. Webpage is accessible for anyone outside the development box. requiremnet: when User access website, top right corener I want to display user computer name.(note: I am not asking users to register). I wrote below code which is fetching user Name, but it alwyas shows admin display name from develoment box. how to get user computer name where ever the webpage is opened in my LAN. ///view.py import ctypes def get_display_name(): GetUserNameEx = ctypes.windll.secur32.GetUserNameExW NameDisplay = 3 size = ctypes.pointer(ctypes.c_ulong(0)) GetUserNameEx(NameDisplay, None, size) nameBuffer = ctypes.create_unicode_buffer(size.contents.value) GetUserNameEx(NameDisplay, nameBuffer, size) return(nameBuffer.value) def home_page(request): context = { "username":request.user.username, } return render(request,"default.html", context) //default.html <div>{{username}}</div> -
django-channels websocket bridge error when trying to connect web socket
Im trying to implement real time notifications in my django app.I have set up signals and consumers . Im getting an error in the javascript side My javascript code: <script> document.addEventListener('DOMContentLoaded', function() { const webSocketBridge = new channels.WebSocketBridge(); const nl = document.querySelector("#nl"); webSocketBridge.connect('student/dashboard/tasks/'); webSocketBridge.listen(function(action, stream) { console.log("RESPONSE:", action); if(action.event == "New Task") { var el = document.createElement("li"); el.innerHTML = ` <b>${action.username}</b> completed Task ${action.title}`; nl.appendChild(el); } }) document.ws = webSocketBridge; /* for debugging */ }) </script> The error shows on the console : TypeError: Invalid WebSocket constructor. Set `options.constructor -
I want to create a signup form to register a user by verifying weather the user is existed or not in the sqlite3 database
I want to create a signup form to register a user by verifying weather the user is existed or not in the sqlite3 database. here is my root urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('orphanageoperations.urls')), ] sub url file: from django.urls import path from .import views urlpatterns=[ path('',views.orphanage_main_page,name='orphanage_main_page'), path('signup.html',views.signup,name='signup'), path('login.html',views.login,name='login') ] views.py file from django.shortcuts import render from .forms import SignupForm def signup(request): if request.method=='POST': form=SignupForm(request.POST) if form.is_valid(): form.save(commit=True) else: form=SignupForm() return render(request,'orphanageoperations/signup.html',{}) models.py from django.db import models from django.utils import timezone from django.conf import settings # Create your models here. class Signup(models.Model): username=models.CharField(max_length=20); usermail=models.CharField(max_length=20,primary_key=True); userph=models.CharField(max_length=13); userpwd=models.CharField(max_length=20); def createUser(self): self.username; self.usermail; self.userph; self.userpwd; forms.py from django import forms from .models import Signup class SignupForm(forms.ModelForm): class Meta: model= Signup; fields=('username','usermail','userph','userpwd',); signup.html <!DOCTYPE html> <html> <head> <title>Signup</title> <meta charset="uts-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script> function validate_signup_form(){ var username=document.getElementById("name").value; var mobilenum=document.getElementById("phno").value; var mailid=document.getElementById("userMail").value; var password=document.getElementById("pwd").value; if(username==""){ alert("Please Enter the username"); return false; } if(mobilenum==""){ alert("Please Enter mobile number"); return false; } if(mailid==""){ alert("Plese enter your mail id"); return false; } if(password==""){ alert("Plese enter your password"); return false; } } </script> </head> <body> <div class="container"> <br … -
I am getting an error : rest_framework.request.WrappedAttributeError: 'CSRFCheck' object has no attribute 'process_request'
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import home from posts.views import PostListView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', PostListView.as_view(), name='home'), url(r'^post/', include('posts.urls', namespace='post')), url(r'^api/post/', include('posts.api.urls', namespace='post-api')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) api/views.py from rest_framework import generics from posts.models import Post from .serializers import PostModelSerializer class PostListAPIView(generics.ListAPIView): serializer_class = PostModelSerializer def get_queryset(self): return Post.objects.all() api/serializers.py from rest_framework import serializers from posts.models import Post class PostModelSerializer(serializers.ModelSerializer): class Meta: model = Post field = [ 'user', 'content' ] api/urls.py from django.conf.urls import url # from django.contrib import admin # from django.conf import settings # from django.conf.urls.static import static # from .views import home from .views import PostListAPIView from django.views.generic.base import RedirectView urlpatterns = [ # url(r'^(?P<pk>\d+)/update/$', PostUpdateView.as_view(), name='update'), # url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='delete'), # url(r'^(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'), url(r'^$', PostListAPIView.as_view(), name='list'), #/api/tweet # url(r'^$', RedirectView.as_view(url='/')), # url(r'^create/$', PostCreateView.as_view(), name='create'), ] views.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import home from posts.views import PostListView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', PostListView.as_view(), name='home'), url(r'^post/', include('posts.urls', namespace='post')), url(r'^api/post/', include('posts.api.urls', namespace='post-api')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) enter image description here