Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Pagination: switch between paginated/non-paginated ListView
I'm trying to elaborate a smart way to switch between a paginated template and a non-paginated one. I already have a working paginator and I was thinking of adding a button next to it that read "Show all results" that linked to a non-paginated list, from there then there would be another button to go back to the paginated list. 1) Easy Solution Use 2 ListViews with different assignations of the attribute paginate_by (django default to set pagination), but since I have many lists in my project it wouldn't be convenient (not much smart either). 2) Solution I'm stuck on Write a Mixin (that will later be extended by my ListViews) to set the variable paginate_by based on a condition and then add some useful variables to the context : class PaginationMixin: no_pagination = False no_pagination_url = '' def get_paginate_by(self, queryset): # overwrite django method if self.no_pagination: return None else: return super().get_paginate_by(queryset) def get_no_pagination_url(self): return self.no_pagination_url def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['no_pagination'] = self.no_pagination context['no_pagination_url'] = self.get_no_pagination_url() return context class MyListView(PaginationMixin, ListView): #... def get_no_pagination_url(self): return reverse('mylist_urlname') PROBLEM: I don't know how to set the no_pagination variable from the template. Is there some way to do this? Thanks for … -
How to handle Celery WorkerLostError due to c++ assertion in python imported module?
I have a python module with c++ code using pybind11 that I have imported in my django + celery 3.1.25 app. The c++ code contains assertions that might trigger inside of a celery worker which then leads to the WorkerLostError. I have tried to put the calls to the python c++ module inside try: except: scopes, however this does not work and the celery worker still crashes. I have also tried to bind an error callback function using the link_error= argument in my apply_async call to my celery task, however the method never gets called. Ideally I would like to catch the error somehow so I can display an error message to the user. Any suggestions is appreciated! -
Reset Password Functionality
I have an api built with Django Rest framework and a Front end that's built with Angular For the reset password functionality, when the user clicks on the reset password they should provide email within a reset password component on Angular. Then via submit action It hits the POST method of reset_password with the email in the body. Then the reset password controller should send an email to the user with this format base_url/reset_password/<token> When the user hits this url, they should be redirected to a reset password form with new password and confirm password The Question is: Where should this template be stored? Angular component or Django template? What is the best practice for such case? -
TypeError: __init__() takes 1 positional argument but 2 were given( "GET /%3Cint:pk%3E.pk HTTP/1.1" 500 61744)
Help needed. I can't seem to solve this problem. New to Django here. Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: init() takes 1 positional argument but 2 were given template <h1><a href="{% url 'details' Testimony.pk %}">{{testimony.Title}}</h1> urls.py urlpatterns = [ ... re_path('<int:pk>/', views.detail, name='details'), ] views.py def details(self, pk): print('1') Testimony=get_object_or_404(Testimony, pk= pk) print('2') return render(request, 'details.html', {'Testimony': Testimony}) -
Signalling server performance issue: Python vs NodeJS
I'm developing a WebRTC application that requires a specific signalling server implementation. Initially I was developing the server in NodeJS but then I decided to migrate to Python (using Django Channels AsyncWebsocketConsumer to communicate with the clients through Websockets). After the migration I used the WebSocket benchmarking tool Thor to compare both implementations and these are the results obtained (5000 websocket connections, each one sending 1000 messages): Python (Django Channels) Implementation: class SignallingConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.peer = None self.signal = None self.is_peer_registered = False async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data=None, bytes_data=None): pass NodeJS implementation: method.start = function () { this.webServer = this.createWebServer(); this.webServer.listen(this.config.port, function (){ console.log("Web server is listening"); }); this.socket = this.createWebSocket(this.webServer); this.socket.on('connection', function(ws) { var pingsCompleted = 0; ws.on('message', function(evt) { }.bind(this)); // Set out ping/pong mechanism var pingInterval = setInterval(function() { if(pingsCompleted > 2) { ws.close(); } else { ws.ping(); pingsCompleted++; } }.bind(this), config.pingPeriod); ws.on('pong', function(evt) { pingsCompleted = 0; }.bind(this)); ws.on('close', function(evt) { }.bind(this)); Python (Django Channels) Results: Online 30792 milliseconds Time taken 30792 milliseconds Connected 3714 Disconnected 0 Failed 1286 Total transferred 4.43MB Total received 525.91kB Durations (ms): min mean stddev median max … -
Adding custom methods to a Django model_factory object
I have this definition : ProfileForm = modelform_factory(User, fields=('username')) How do I add custom methods to ProfileForm ? -
pip install mod_wsgi on xampp on windows
I want to install mod_wsgi on windows. my xampp server is started on port 80 and I have set "MOD_WSGI_APACHE_ROOTDIR=C:\xampp", but when I try to pip install mod_wsgi I have this error: Command "c:\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ANNABE~1\\AppData\\Local\\Temp\\pip-install-iiqu87d8\\mod-wsgi\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\ANNABE~1\AppData\Local\Temp\pip-record-1ltlbt07\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\ANNABE~1\AppData\Local\Temp\pip-install-iiqu87d8\mod-wsgi\ how canI solve it? -
No module named 'django.core.urlresolvers when using uni_form
I am trying to use uni_form with django 2.1.5 latest version . and after importing from uni_form.helper import FormHelper in the forms.py an error message says : File "D:\installed_apps\python\lib\site-packages\uni_form\helper.py", line 1, in from django.core.urlresolvers import reverse, NoReverseMatch ModuleNotFoundError: No module named 'django.core.urlresolvers' However, after looking arround in stackoverflwo I came up with change the helper.py : from django.core.urlresolvers import reverse, NoReverseMatch to : from django.urls import reverse, NoReverseMatch another problem rises : File "D:\installed_apps\python\lib\site-packages\uni_form\helper.py", line 4, in from utils import render_field ModuleNotFoundError: No module named 'utils' so can any one help me please , and thanks in advance -
Django:` Date: Wed, 09 Jan 2019 09:25:20 GMT Server: WSGIServer/0.2 CPython/3.7.1` will automatically added to my code
I'm creating a website using the django framework. But recently, I found something strange. I loaded the page at 127.0.0.1:8000, but failed. I checked the chrome console log and found a js file with errors. Then I check the error in the js file and find some strings added to my code automatically. If I clean up the cookies and reload the page, I might load the page successfully or these strings might still appear in other js files. Why is it happen? /error js file if ($element.data('on-label') !== undefined) onLabel = $element.data('on-label'); if ($element.data('ofDate: Wed, 09 Jan 2019 09:25:20 GMT Server: WSGIServer/0.2 CPython/3.7.1 f-label') !== undefined) offLabel = $element.data('off-label'); if ($element.data('icon') !== undefined) icon = $element.data('icon'); Sometime below two strings will add into my code automatically When I first visited the page. I can't find any error log in PyCharm when i run runserver, only can see chrome log about the wrong js file. Date: Wed, 09 Jan 2019 09:25:20 GMT Server: WSGIServer/0.2 CPython/3.7.1 -
how to set my django path to http://127.0.0.1:8000/myproject/admin
here is my myproject/urls.py urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls')) ] when i run python manage.py runserver 127.0.0.1:8000 its working fine http://127.0.0.1:8000 http://127.0.0.1:8000/admin http://127.0.0.1:8000/myapp but I want to like this http://127.0.0.1:8000/myproject http://127.0.0.1:8000/myproject/admin http://127.0.0.1:8000/myproject/myapp and all URLs even templates URLs should redirect in the same pattern. where I CAN set the single path/Setting to redirect with /myproject/ to work fine. and later I can change with /myproject/ to /project2/ in a single place. -
How do I create a custom 410 error page using the Django Redirect App?
I am redesigning a website with lots of old (and very poorly optimized) content. It doesn't make sense to migrate the old content, so I am using the Django Redirects App to raise 410 errors in case anybody discovers a link to the old website. https://docs.djangoproject.com/en/2.1/ref/contrib/redirects/ I am currently getting the default Chrome 410 error page. How do I deliver a custom 410 error page? -
Unique autogenerated ID for differet django models
I have 3 model classes that inherit from a parent abstract class, like so: class ParentClass(models.Model): class Meta: abstract = True class ChildClass1(ParentClass): ... class ChildClass2(ParentClass): ... class ChildClass3(ParentClass): ... I was wondering if there was a way to let Django generate id's as usual, but making sure that no instances of either ChildClass1, ChildClass2, or ChildClass3 will have overlapping id's. So for example the following code: a = ChildClass1.objects.create() b = ChildClass2.objects.create() c = ChildClass3.objects.create() print(a.pk) print(b.pk) print(c.pk) shuld return: 1 2 3 -
In Django Admin searching by a Relational Key(1to1)
I have two models Owner and Entity with OneToOne Relationship. class Owner(models.Model): name = models.CharField(max_length=255) ..... def __str__(self): return self.name class Entity(models.Model): owner = models.OneToOneField(Owner, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) ...... For Django Admin, search fields I have: class EntityAdmin(admin.ModelAdmin): ..... search_fields = ('email', 'name', 'owner') If I try to search I get the following error: Related Field got invalid lookup: icontains If I remove owner, but I still want to search by owner -
python-social-auth facebook can't load url the domain of this URL isn't included in app's domains
I'm trying to go through a tutorial on setting up django-social auth https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html and I'm getting an error I don't know how to solve AuthCanceled at /oauth/complete/facebook/ Authentication process canceled: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Facebook app configuration: I'm using forwardHQto set up the url. -
Creating a unique object using DateField()
I would just like to create a model that essentially prevents the same date being selected by two different users (or the same user). E.g if User1 has selected 2019-01-10 as a "date" for a booking, then User2 (or any other Users) are not able to create an object with that same date. I have created a very basic model that can allow different Users to create an object using the DateField(). Using the Django admin page, I can create different instances of objects by two different Users (admin and Test_User). In order to try to ensure that a new object can't be created if that date has already been used by a different object I have tried the following approach: a compare function that utilizes __dict__. models.py from __future__ import unicode_literals from django.db import models, IntegrityError from django.db.models import Q from django.contrib.auth.models import User from datetime import datetime class Booking(models.Model): date = models.DateField(null=False, blank=False) booked_at = models.DateTimeField(auto_now_add=True) booking_last_modified = models.DateTimeField(auto_now=True) class PersonalBooking(Booking): user = models.ForeignKey(User, on_delete=models.CASCADE) def compare(self, obj): excluded_keys = 'booked_at', '_state', 'booking_last_modified', 'user', return self._compare(self, obj, excluded_keys) def _compare(self, obj1, obj2, excluded_keys): d1, d2 = obj1.__dict__, obj2.__dict__ for k,v in d1.items(): if k in excluded_keys: continue try: … -
Authorization of microservices in monolith application
I have a django application that puts a task in a queue. Another service is used to read that queue and process some files. At the end I need to save the processed files in the database managed by the django application. I do not want to give the "microservice" access directly to the database, since I want the responsibility only to be to process the files. So I wanted to post the changes to django using HTTP request. The problem is that I do not have any authorization at the time, even though I know that HTTP from this type of machine is to be accepted. For the django application I use JWT as an authorization token. How is the best way to approach this type of problem? Maybe just send a token together to the queue? But how to make such token? It's not certain when the process will be executed.. -
Django load ES6 javascript file
I would like to use the import feature in ES6 in index.html in django. I do not want to compile to ES5 for browser compatibility. I would like to assume that all the users will have ES6 compatible browsers. Therefore I do not need a ES6 to ES5 compiler such as Babel: https://github.com/kottenator/django-compressor-toolkit I simply would like to serve the ES6 Javascript and the browser to compile it if it can. I tried: <!-- Index.html --> <script type="module" src="{% static 'app.js' %}"></script> //app.js (function(){ console.log("Hello from App.js"); })(); # settings.py if DEBUG: import mimetypes mimetypes.add_type("module", ".js", True) The error I get: Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. -
Django Chartit Theme
Is there any way to change the theme of Django-Chartit library ? Though it's using Highchart.js but I didn't find the way to change the theme in the django-chartit documentation . -
what is best way to email login with custom model Django?
I am trying to make a login with a custom model, and i have tried many tutorials but nothing works for me. this is my model. model.py from django.db import models from .choices import gender_choices, marital_status, districts class UserRegister(models.Model): name = models.CharField(max_length=30) email = models.EmailField() password1 = models.CharField(max_length=300) password2 = models.CharField(max_length=300) termo_resp = models.BooleanField() gender = models.CharField(choices=gender_choices, max_length = 1,null=True) birthdate = models.DateField(blank=True, null=True) marital_status = models.CharField(choices=marital_status, max_length = 1,null=True) districts = models.CharField(choices=districts, max_length = 20,null=True) city = models.CharField(max_length=25, null = True) job = models.CharField(max_length=50, null = True) -
Djago Template Error "TemplateDoesNotExist at"
I can run my server with "py manage.py runserver" with getting no error , then my login page comes and I login to system and main welcome page shows me when I click to customer_list link in that page it gives me an error like below. Error TemplateDoesNotExist at /clist customer_list Request Method: GET Request URL: http://127.0.0.1:8000/clist Django Version: 2.0.2 Exception Type: TemplateDoesNotExist Exception Value: customer_list Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: D:\project\dysapp\templates\customer_list (Source does not exist) django.template.loaders.app_directories.Loader: D:\project\dysapp\templates\customer_list (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\cenk.adalan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\customer_list (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\cenk.adalan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\customer_list (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\cenk.adalan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django_tables2\templates\customer_list (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\cenk.adalan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\import_export\templates\customer_list (Source does not exist) Settings.py - Template config TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, },] After Login to main page then I click this link at "customer_list" and get error {% if user.is_authenticated %} <p></p> {% if perms.dysapp.add_bloodtype %} <li class="passive"><a href="{% url "customer_list" %}"> <i class="fa fa-link"></i> <span>test2</span></a></li> <li class="passive"><a href="{% url "login" %}"> <i class="fa fa-link"></i> <span>test</span></a></li> ** customer_link.html ** {% extends 'ltebase.html' %} {% block title %}Danışanlar{% endblock %} {% block … -
docker setup gdal for django
Based on an existing django webapp I have and some simple introduction to docker I've setup this docker file to handle setting up the site FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code RUN apt-get update && apt-get install --yes libgdal-dev RUN export CPLUS_INCLUDE_PATH=/usr/include/gdal RUN export C_INCLUDE_PATH=/usr/include/gdal WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt and the requirements file Django==2.1.5 psycopg2==2.7.6.1 numpy gdal when I run the command sudo docker-compose build it eventually crashes with this error Building wheels for collected packages: gdal Running setup.py bdist_wheel for gdal: started Running setup.py bdist_wheel for gdal: finished with status 'error' Complete output from command /usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-emkt_bai/gdal/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-1tv4zrfw --python-tag cp37: WARNING: numpy not available! Array support will not be enabled ... Skipping optional fixer: ws_comma running build_ext gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I../../port -I../../gcore -I../../alg -I../../ogr/ -I../../ogr/ogrsf_frmts -I../../gnm -I../../apps -I/usr/local/include/python3.7m -I. -I/usr/include -c gdal_python_cxx11_test.cpp -o gdal_python_cxx11_test.o building 'osgeo._gdal' extension creating build/temp.linux-x86_64-3.7 ... extensions/gdal_wrap.cpp:4073:1: error: ‘VSIDIR’ does not name a type VSIDIR* wrapper_VSIOpenDir( const char * utf8_path, ^~~~~~ extensions/gdal_wrap.cpp:4121:38: error: ‘VSIDIR’ was not declared in this scope DirEntry* wrapper_VSIGetNextDirEntry(VSIDIR* dir) ^~~~~~ extensions/gdal_wrap.cpp:4121:46: error: ‘dir’ was not … -
How can I run plain ES6 in Django?
I would like to use the import feature in ES6 in index.html in django. I do not want to compile to ES5 for browser compatibility. I would like to assume that all the users will have ES6 compatible browsers. Therefore I do not need a ES6 to ES5 compiler such as Babel: https://github.com/kottenator/django-compressor-toolkit I simply would like to serve the ES6 Javascript and the browser to compile it if it can. I tried: <link rel="stylesheet" type='text/module' href="{% static 'app.js' %}"> from here: https://www.techiediaries.com/javascript-tutorial/ I tried: <script type="text/module" src="{% static 'app.js' %}"></script> which loads nothing Also tried: <script type="module" src="{% static 'app.js' %}"></script> which gives error: Failed to load module script: The server responded with a non-JavaScript MIME type of "text/module". Strict MIME type checking is enforced for module scripts per HTML spec. I tried: if DEBUG: import mimetypes mimetypes.add_type("text/module", ".js", True) mimetypes.add_type("module", ".js", True) -
How to add a new record in django admin list_view, in a way similar to what extra forms do in inlines
Using ModelAdmin.list_editable I can edit the fields of records listed in a list view of django admin, in a way similar to what is done with InlineModelAdmin. Using InlineModelAdmin.extra I can show forms to add new records in inline models admin view. How can I show similar empty forms in the admin list view in order to add new records? -
apache2 with django - can't write to log file
I have django running on apache2 server. my settings.py looks like this: WSGI_APPLICATION = 'my_app.wsgi.application' ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s: %(message)s' } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '../django.log', 'formatter': 'verbose', 'maxBytes': 1024 * 1024 * 5, # 5 MB 'backupCount': 5, }, }, 'loggers': { 'my_app': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } My idea was basically to create a log that all the components of my django app will write to, with level INFO. The issue I am facing is, when running the server, the log is created with root permissions: ll ../django.log -rw-r--r-- 1 root root 0 Jan 9 10:17 ../django.log And so, what happens when I try to log to it is: /var/log/apache2/error.log [Wed Jan 09 11:37:43.677755 2019] [:error] [pid 1457:tid 140554321598208] [remote 192.168.254.52:60257] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '../django.log' I did find those issues: Permission Denied when writing log file and Django: Setup an efficient logging system for a website in production. and if I change the permissions of the file to be owned by www-data and not root, it works. My … -
ValueError at / Django
I am getting Error: ValueError at /user-admin/manager/manager-add Cannot assign "<QuerySet [<Groups: Codism>, <Groups: Codism>, <Groups: Codism123221>]>": "UserGroup.usergroup_group" must be a "Groups" instance. Forms.py class ManagerGroupForm(forms.ModelForm): usergroup_group = forms.ModelMultipleChoiceField(queryset=Groups.objects.all()) class Meta: model = UserGroup fields = ['usergroup_group'] Views.py @login_required def ManagerAddView(request): if request.method == 'POST': random_password = User.objects.make_random_password() # generate password here ur_form = ManagerRegisterForm(request.POST, pwd=random_password) pr_form = ManagerProfileForm(request.POST, request.FILES) gr_form = ManagerGroupForm(request.POST) user_role = ACLRoles.objects.get(acl_role_title='Manager') if ur_form.is_valid() and pr_form.is_valid() and gr_form.is_valid(): new_user = ur_form.save(commit=False) new_user.username = new_user.email new_user.set_password(random_password) new_user.save() profile = pr_form.save(commit=False) if profile.user_id is None: profile.user_id = new_user.id profile.user_role_id = user_role.id profile.user_company_id = request.user.userprofile.user_company.id profile.save() # newly added code new_user_group = gr_form.save(commit=False) new_user_group.usergroup_user = new_user.id new_user_group.usergroup_created_by = request.user new_user_group.usergroup_updated_by = request.user new_user_group.save() return redirect('admin_managers') else: ur_form = ManagerRegisterForm() pr_form = ManagerProfileForm() gr_form = ManagerGroupForm() return render(request, 'users/admin/managers_form.html', {'ur_form': ur_form, 'pr_form': pr_form, 'gr_form': gr_form}) The actual problem started when i add ManagerGroupForm() because i want to select multiple select and multiple i have used forms.ModelMultipleChoiceField in my forms.py. Please help me because it is not validating my form and also should i am manually entry data like request.user and new_user.id