Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to integrate django project with nextcloud calendar
We're planning to write a Django application that can manage events for a group of users. The things that we need: There is an easy way for the admins to create new events and upon creation users are notified (per email) and can confirm or decline attendance. The user can integrate these events in their calendar client, e.g. thunderbird, iOS, etc. Depending on people attending to the event, we can create some stats, overviews, graphs, etc. Users can change their RSVP status and the admins are notified per email. Events will have probably several linked data to them (maybe some maps, documents, etc.) and other fields for categories, etc. Events might be recursive or one-time events. There is an easy way to add exceptions for recursive events. There is an overview for all events and RSVP status for the events is easily accessible. The count of attendees is listed for each event. The events overview can be filtered by different criteria (date range, category, ...) We want to use a Django project for managing stats, linked media, listings, etc. And the plan was to add fields for the scheduled date + recurrence. But all existing calendar alternatives for Django I've … -
How to compare some_time|timeuntil with specific time interval in Django templates?
I'm making a new label on my BBS. (When an article is a relatively new one, then a label says 'this is new one' appears.) After reading Django Docs I know |timeunitl returns the value from given time to now. I want to compare this value to a specific time interval such as two days or two hours. So I tired below {% if article.created_at|timeunitl < 2 %} <span class = "label label-new">NEW</span> {% endif %} However, I can't see <span class = "label label-new">NEW</span> in actual page no matter how I change the value of the right side. How Can I compare this value? My Django version is 1.11.16, and Python version is 3.6.7. -
keyerror in verification of email api
in project i am working getting error KeyError at /rest-auth/registration/verify-email/ def get_object(self, queryset=None): key = self.kwargs('key') emailconfirmation = EmailConfirmationHMAC.from_key(key) if not emailconfirmation: if queryset is None: queryset = self.get_queryset() try: emailconfirmation = queryset.get(key=key.lower()) except EmailConfirmation.DoesNotExist: raise Http404() return emailconfirmation -
Django: Some strings are 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 console log and found some js files 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 the two strings will add into my code automatically When I first visited the page. Date: Wed, 09 Jan 2019 09:25:20 GMT Server: WSGIServer/0.2 CPython/3.7.1 js file will auto -
How django resolve the foreign key in its models.py?
I am wondering how django decides which column or field will act as foreign key to another model in One to Many relationship. class Department(models.Model): dept_name = models.CharField(max_length=100) dept_head = models.CharField(max_length=100) dept_abbrv = models.CharField(max_length=100) class Employee(models.Model): dept = models.ForeignKey(Department) emp_name = models.CharField(max_length=100) Now how django knows which column of Department (dept_name, dept_head or dept_abbrv) will map to 'dept' in Employee. In my admin page of Employee details if I have to add a new employee, there is dropdown listing all Department.dept_name against 'dept'. How django decides that? Why it is not dropdown list of dept_head or dept_abbrv ? -
How to make this function easier to test?
I have the function which builds and return Slack message with text and attachments. How can I refactor this function to make it easier to test? Should I split it into multiple functions? def build_list_message(team_id, user_id, msg_state=None, chl_state=None): if not msg_state: msg_state = {} if not chl_state: chl_state = {} resource_type = msg_state.get('resource_type', 'all') availability = msg_state.get('resource_availability', 'all') pages = Page.objects.none() async_tasks = AsyncTask.objects.none() if resource_type in ['web_pages', 'all']: pages = Page.objects.filter( user__team__team_id=team_id).order_by('title') if resource_type in ['async_tasks', 'all']: async_tasks = AsyncTask.objects.filter( user__team__team_id=team_id).order_by('title') if availability == 'available': pages = pages.filter(available=True) async_tasks = async_tasks.filter(available=True) elif availability == 'unavailable': pages = pages.filter(available=False) async_tasks = async_tasks.filter(available=False) channel_id = chl_state.get('channel_id') if channel_id: pages = pages.filter(alert_channel=channel_id) async_tasks = async_tasks.filter(alert_channel=channel_id) user = SlackUser.retrieve(team_id, user_id) attachments = [ _build_filters(resource_type, availability), *[_build_page_item(p, user) for p in pages], *[_build_async_task_item(at, user) for at in async_tasks] ] return { 'text': "Here's the list of all monitoring resources", 'attachments': attachments }