Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VirtualEnv apache2 server No module named 'django'
I am running a virtual environment for my apache2 server from inside /home/myname/myproject/venv I activate my virtual environment with source venv/bin/activate Running which django-admin Returns the correct file from inside my virtual environment. Running import django django.__file__ Returns /home/myname/myproject/venv/lib/python3.6/site-packages/django/__init__.py Running pip freeze Returns all of my needed packages. I also have my apache2 config file pointing to the venv directory with the python-path argument However, after restarting the server I'm still getting a ModuleNotFoundError for django. What's the issue here? -
mod_wsgi cannot be loaded as Python module http 500 error
I am trying to deploy mod_wsgi with apache to run a django application but I am getting an error 500 internal server error. This is what apache log shows: [Sun Dec 30 12:46:44.179450 2018] [mpm_event:notice] [pid 21350:tid 139933131320256] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Sun Dec 30 12:46:44.179649 2018] [core:notice] [pid 21350:tid 139933131320256] AH00094: Command line: '/usr/sbin/apache2' [Sun Dec 30 12:46:45.681614 2018] [wsgi:error] [pid 21353:tid 139933017503488] [remote 109.8.128.207:52109] mod_wsgi (pid=21353): Target WSGI script '/home/betourne/tonnerrekalaraclub/tonnerrekalaraclub/wsgi.py' cannot be loaded as Py$[Sun Dec 30 12:46:45.687031 2018] [wsgi:error] [pid 21353:tid 139933017503488] [remote 109.8.128.207:52109] mod_wsgi (pid=21353): Exception occurred processing WSGI script '/home/betourne/tonnerrekalaraclub/tonnerrekalaraclub/wsgi.py'. And this is my virtual host conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/betourne/tonnerrekalaraclub/static <Directory /home/betourne/tonnerrekalaraclub/static> Require all granted </Directory> Alias /media /home/betourne/tonnerrekalaraclub/media <Directory /home/betourne/tonnerrekalaraclub/media> Require all granted </Directory> WSGIScriptAlias / /home/betourne/tonnerrekalaraclub/tonnerrekalaraclub/wsgi.py WSGIDaemonProcess django_app python-path=/home/betourne/tonnerrekalaraclub python-home=/home/betourne/tonnerrekalaraclub/venv WSGIProcessGroup django_app <Directory /home/betourne/tonnerrekalaraclub/tonnerrekalaraclub> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> I'm not sure what else to try, I've been looking for a solution for 2 days now, considering each thread on the forum. WWW-DATA has every rights to access directory, I checked that there's no mispelling... I am on Ubuntu 18.04.1 -
Django admin custom form submission force to select action from dropdown list
I want to add a custom form to a django admin-site change list view. As soon as I add a submit button it asking to select the custom action from the drop-down list. I created a separate form with a unique id. Still it look for a action be select. How can I overcome this? Here is my template code. {% extends "admin/change_list.html" %} {% load staticfiles %} {% block content %} <div align="right"> <form id="generate-form" method="POST"> {% csrf_token %} <select> <option value="">-- section name --</option> {% for section in sections %} <option value="{{ section.short_name }}">{{ section.name }}</option> {% endfor %} </select> <input type="text" name="from_date" class="vTextField" placeholder="from"> <input type="text" name="to_date" class="vTextField" placeholder="to">&nbsp; <input type="submit" value="Generate" class="default" id="gen-schedules" style="margin:0; height: 30px; padding-top: 5px;"> <form> </div> {{ block.super }} {% endblock %} -
Django templates not executed in a container and no errors displayed in the logs
I'm running django 2.1.3 in to a python3 container based on alpine image, I create my own image by following this guide: https://docs.docker.com/compose/django/ (with other project works) this time the templates are not showed, the page I receive is the render of the called template the extends part are not present. I try to run code in a bind folder instead docker volumes and had no change. Dockerfile: FROM python:3-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir -p /code/ WORKDIR /code/ ADD requirements.txt / RUN apk update && \ apk add postgresql-libs && \ apk add --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r /requirements.txt --no-cache-dir && \ apk --purge del .build-deps docker-compose (django image section): django: build: "./django" image: registry.gitlab.com/vaschetto.marco/project-docker-File/django:v0.1 container_name: Project_django restart: always command: python3 manage.py runserver 0.0.0.0:8000 env_file: - ./django/.env volumes: - django:/code/ - django_static:/code/static/ depends_on: - psql Template structure: . βββ db.sqlite3 βββ Dockerfile βββ project ... β βββ settings.py β βββ urls.py β βββ wsgi.py βββ manage.py βββ requirements.txt βββ sito #app β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations ... β βββ models.py β βββ __pycache__ ... β βββ templates β β βββ sito β β βββ body.html β¦ -
Not able to use two models in the same django view
I'm quite new to django, and can't seem to make two models in the same view work. I have tried the guide in the djano docs, but can't seem to be able to use two different models templates in the html. Is it possible that i've misunderstood how the OneToOneField works? The html just renders an empty div. The account templates works fine. Models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django import template import phonenumbers # Create your models here. class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk')), blank=True) phoneNumber = models.IntegerField() birthDate = models.DateField() streetAdress = models.CharField(max_length=255) zipCode = models.CharField(max_length=4) city = models.CharField(max_length=255) def formatedPhone(self, country=None): return phonenumbers.parse(Account.phoneNumber, "NO") def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) def get_absolute_url(self): return reverse("account-detail", kwargs={"pk": self.pk}) class Meta: verbose_name = "Account meta" verbose_name_plural = "Accounts meta" class Notes(models.Model): userNoted = models.OneToOneField(User, on_delete=models.CASCADE) note = models.TextField() date = models.DateTimeField((""), auto_now=False, auto_now_add=True) active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("note-detail", kwargs={"pk": self.pk}) class Meta: verbose_name = "Note detial" verbose_name_plural = "Notes details" Views.py from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.views.generic.detail import DetailView from django.views.generic.edit import * β¦ -
django-rest-framework and http to https redirect
I want to redirect all http requests to https in my django app. The app has also an api through which I make request to database. Those requests are made through http protocol and I want to redirect them to https as well . Below configuration works well with requests made in web browser (http are correctly redirected to https and the website displays). However, the requests through api cause 301 error (Moved Permanently). Am I missing something here? This is my nginx configuration: server { listen 80; server_name myurl.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name myurl.com; ssl_certificate /path_to_cer; ssl_certificate_key /path_to_key; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_redirect off; #proxy_buffering off; } Django settings: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True -
FloatField returns str object instead of Float in Django
While working on something in Django, I stumbled upon this wierd error (cuz it never happened before). If in a FloatField I saved a float value as string i.e. '245.4' instead of actual float value i.e. 245.4, then on accessing the value it returns back the string instead of float! the reason why abs(modelname.floatfield) threw TypeError today. On research found this old thread in Django's forum (https://code.djangoproject.com/ticket/19565). Is it decided and implemented yet or should I typecast values manually from now on or anyone has a better solution? -
organization and departments hierarchy database schema
I have a database design in django that have the following tables: organization table id name contact department table name parent (another department self referencing ) organization (referencing the organization table if this is the top department only) How to inherit the organization relationship instead of having to set it every time i am creating a new department? -
Filtering by Field on Foreign Key
I've got two models that are related to one another class IndustryService(models.Model): title = models.CharField(max_length=120) pricingisarate = models.BooleanField(default=False) class UserService(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.ForeignKey(IndustryService, on_delete=models.CASCADE, null=True, blank=True) Within a view, I'm trying to develop a queryset of UserService instances that a) belongs to a user b) on the foreign key, has pricingisarate == True I've tried the following query, but it doesn't work: services = UserService.objects.filter(user=user, industryservice__pricingisarate__is=True) Thanks for your help!!! -
How to fix ValueError: Expecting property name: line 4 column 1 (char 43)
when I tr to run python manage.py runserver code is giving error . And its traceback is strange , I tried JSON ValueError: Expecting property name: line 1 column 2 (char 1) and all similar questions but didn't get what exactly I am facing. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/tousif/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/tousif/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/home/tousif/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/tousif/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/tousif/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/tousif/Desktop/ITP/ITP/itpcrm/itpcrm/settings.py", line 55, in <module> cfg = json.loads(open('/home/tousif/Desktop/ITP/ITP/itpcrm/config.json', 'r').read()) File "/usr/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 4 column 1 (char 43) Project should run. -
django: custom code integration into django project
Noob here with django. I have the following folder structure for a dhango app, which is inside the main project folder. my_app/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py I have a command line python script I wrote to fetch a json file and parse it to displays very specific information. it's using requests library for JSON and data parsing. My question is how do I integrate my script into django app. specifically how to bring the logic of it and to place under which file? My thinking is to create another file and import them into views. and pass them into render function - this may be not the right and django way, but kinda stuck there. Oh and I don't use any DB, the script uses a text file and writes to it as well. -
2 django apps installed locally are not working properly on same browser, facing login/logout problem
I am working on 2 Django app which is running on ports - 8001 and 8002. But the problem is when I click on any link on the second app, the first app make me log out and when I log in to the first one, the second app makes me log out. Is there any session conflict? Can anyone suggest me how to solve this? -
Unable to see logging messages in django using the logging module
I'm a newbie to logging. I added the code for logging in my views.py file and I added the settings as per the django documentation in my settings.py file. However, the logging.txt file shows other exceptions at DEBUG level or no output at WARNING level. The website is working properly and I have it live on an EC2 instance. Here's the code for in my views.py file: import logging # Get an instance of a logger logger = logging.getLogger(__name__) def index(request): ... logger.error("THIS IS A LOG ERROR!!!") logger.warning("THIS IS A LOG WARNING!!!") ... return render(...) Here's the code in my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logging.txt', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } What am I doing wrong? -
django oauth2 creating application redirect problem
when I want to create an application with this url http://127.0.0.1:8000/o/applications/ , it always redirects me to this address http://127.0.0.1:8000/accounts/login/?next=/o/applications/ how can I solve it?, note that I don't want to use Django admin -
How to send javascript variable and form data on same time in django?
i have javascript variable and i want to sent it to django view with ajax() method here is my code. $('#orderDetails').submit(function() { // catch the form's submit event $.ajax({ type: 'POST', url: 'order/', headers: {"X-CSRFToken":'{{ csrf_token }}'}, data: { 'test': 12, } }); return false; }); here is form code <form action="{% url 'order:order_detail' %}" method="post" enctype="multipart/form-data" id="orderDetails"> {% csrf_token %} <input type="submit" value="Proceed" class="btn"> </form> and here is views.py def order_detail(request): test = request.POST.get('test') print(test) it print none.any one can help please? -
Looking for a tool for approve or reject user actions
I have a requirement in my app where user registration is to be approved or rejected. Same thing is also valid for when a user edits his/her profile. It should be approved or rejected by admin. I tried to use django-moderation but it has countless of different bugs and seems not well maintained for years. What different tool can I use for this goal? -
How to make a follow button in django?
I am trying to make a list of post which will have a follow button to follow that particular user, but for saving instance of that user, we usually uses django forms via post methods where a user fills that form. I want to make follow button like that of instagram on explore page. can i use javascript to fill the form? if yes, please elaborate. -
django-admin.py is using Django 1.11 instead of Django 2
I have both python2 and python3 installed on my ubuntu machine Also I have both versions of Django Installed whenever I make a new project in django django-admin is using Django 1.11 by default How do I create a project in Django 2 ?? -
Javascript interfering with django forms
I have an issue where somewhere in my code the javascript is interfering with the form updates. Django form not submitting or providing error messages I've also uploaded all the code on github; I've tried almost everything and I think it may be one of the 3rd party packages installed. https://github.com/lkal88/djangoproject If anyone could point me in the direction to help identify/fix the issue, it'll be awesome! -
How to fix NoReverseMatch in django
I am developing an ecommerce website just for a practice and all the codes were working fine but all of a sudden I am getting a error at the django template I have tried following most of the answers but none of it seems to working This is my urls.py urlpatterns = [ url(r'^$', views.cart_detail, name='cart_detail'), url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'), url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'), ] this is my main urls.py of the project urlpatterns = [ # Examples: # url(r'^$', 'myshop.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^cart/', include('cart.urls', namespace='cart')), url(r'^orders/', include('orders.urls', namespace='orders')), url(r'^paypal/', include('paypal.standard.ipn.urls')), url(r'^payment/', include('payment.urls', namespace='payment')), url(r'^coupons/', include('coupons.urls', namespace='coupons')), url(r'^', include('shop.urls', namespace='shop')), ] this is the template in which I am getting error {% block content %} <h1>Your shopping cart</h1> <table class="cart table-striped "> <thead> <tr> <th>Image</th> <th>Product</th> <th>Quantity</th> <th>Remove</th> <th>Unit Price</th> <th>Price</th> </tr> </thead> <tbody> {% for item in cart %} {% with product=item.product %} <tr> <td> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %} {{ product.image.url }} {% else %}{% endif %}"> </a> </td> <td>{{product.name}}</td> <td> <form action="{% url 'cart:cart_add' product.id %}" method="post"> {{item.update_quantity_form.quantity}} {{item.update_quantity_form.update}} <input type="submit" class=" btn btn-default outline" value="update"> {% csrf_token %} </form> </td> <td> <a href="{% url 'cart:cart_remove' product.id %}">Remove</a> </td> <td class="num">${{item.price}}</td> β¦ -
Python Django heroku error "remote rejeced"
Whenever I type command: git push heroku master Enumerating objects: 32, done. Counting objects: 100% (32/32), done. Delta compression using up to 4 threads Compressing objects: 100% (30/30), done. Writing objects: 100% (32/32), 11.43 KiB | 557.00 KiB/s, done. Total 32 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.7 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting dj-database-url==0.5.0 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/d4/a6/4b8578c1848690d0c307c7c0596af2077536c9ef2a04d42b00fabaa7e49d/dj_database_url-0.5.0-py2.py3-none-any.whl remote: Collecting Django==2.1.3 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/d1/e5/2676be45ea49cfd09a663f289376b3888accd57ff06c953297bfdee1fb08/Django-2.1.3-py3-none-any.whl (7.3MB) remote: Collecting django-heroku==0.3.1 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 3)) remote: Downloading https://files.pythonhosted.org/packages/59/af/5475a876c5addd5a3494db47d9f7be93cc14d3a7603542b194572791b6c6/django_heroku-0.3.1-py2.py3-none-any.whl remote: Collecting gunicorn==19.9.0 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 4)) remote: Downloading https://files.pythonhosted.org/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl (112kB) remote: Collecting psycopg2==2.7.6.1 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 5)) remote: Downloading https://files.pythonhosted.org/packages/bc/2a/61a8f9719bd6df5b421abd91740cb0595fc3c17b28eaf89fe4f144472ca6/psycopg2-2.7.6.1-cp36-cp36m-manylinux1_x86_64.whl (2.7MB) remote: Collecting pytz==2018.7 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 6)) remote: Downloading https://files.pythonhosted.org/packages/f8/0e/2365ddc010afb3d79147f1dd544e5ee24bf4ece58ab99b16fbb465ce6dc0/pytz-2018.7-py2.py3-none-any.whl (506kB) remote: Collecting whitenoise==4.1.2 (from -r /tmp/build_731c5da72f871fc9827c03c3e6dfa9eb/requirements.txt (line 7)) remote: Downloading https://files.pythonhosted.org/packages/fd/2a/b51377ab9826f0551da19951257d2434f46329cd6cfdf9592ea9ca5f6034/whitenoise-4.1.2-py2.py3-none-any.whl remote: Installing collected packages: dj-database-url, pytz, Django, whitenoise, psycopg2, django-heroku, gunicorn remote: Successfully installed Django-2.1.3 dj-database-url-0.5.0 django-heroku-0.3.1 gunicorn-19.9.0 psycopg2-2.7.6.1 pytz-2018.7 whitenoise-4.1.2 it give error here remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: β¦ -
django oauth2 creating application redirect problem
when I want to create an application with this url http://127.0.0.1:8000/o/applications/ , it always redirects me to this address how can I solve it?, note that I don't want to use Django admin -
Why attribute of a dictionary works in template html through connection with codes in view.py ?
I am new to Django, and I am following a tutorial in which he writes something like {%for post in posts %} {{post.author}}in the template html file. He describes that the template responds to the key 'posts'. To my understanding, post is a dictionary according to what he writes in view.py? How does it work? posts = [ { 'author': 'JosephJ', 'title': 'Blog Post1', 'content': 'First post content', 'date_posted': 'August 27, 2018' }, { 'author': 'RogerL', 'title': 'Blog Post2', 'content': 'Second post content', 'date_posted': 'August 28, 2018' } ] def home(request): context = { 'posts': posts } return render(request, 'blog/home.html', context) -
ordering by descending order in django views
I am using sorted() to combine two queryset and then ordering them by DatePosted but i want to sort it in reverse order, that is, new to oldest. How can i do it? def feed(request): if request.user.is_authenticated: result_list=post.objects.none() usrpost=post.objects.none() channel_result=channel.objects.none() chnpost=channel.objects.none() userprofile=FollowingProfiles.objects.filter(Profile__user=request.user) for p in userprofile: postuser=post.objects.filter(Profile__user__username=p.ProfileName) result_list=sorted(chain(usrpost,postuser),key=operator.attrgetter('DatePosted')) usrpost=result_list result_list=usrpost postuser=post.objects.none() profile_result=Profile.objects.filter(user__username=request.user.username) -
Django - how to access a ForeignKey parent's attribute?
I'm a newbie in Django, and I don't know how to this. I have a model 'Seller': class Seller(models.Model): seller_name = models.CharField(max_length=50) def __str__(self): return self.seller_name and a model 'Item': class Item(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE) item_name = models.CharField(max_length=100) item_category = models.CharField(max_length=100, choices=ALL_CATEGORIES) item_price = models.FloatField() item_preview = models.ImageField(upload_to='previews/<the seller's name>') def __str__(self): return self.item_name connected via ForeignKey to Seller. In this model, I have an ImageField, and I want it to upload the files to previews/Seller's name directory, but I don't know how to access the Seller's name from Item. Is it possible? Or am I doing something I am not supposed to? Because I couldn't find any similar cases in the internet.