Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sorl-thumbnail with memcached - 404 errors when trying to access thumbnail
I'm using django on a shared webhost, so all the memcached stuff is automatically configured and meant to work without issue in django. I have strings returned to a template which specify a URL to an image. They are not an ImageField, just a text string. My code in the template is : {% for instance in prods %} {% thumbnail instance.image_url "300x300" crop="smart" as im %} <img src="{{ im.url }} " > {% endthumbnail %} {% endfor %} This generates a URL like /static/media/cache/8f/cb/8fcbe5bd955ad8d999652c15eeda0959.jpg I have my media_dir and media_urls to be within /static, so this is correct. However, whenever I try to access this image url directly, I get a 404 error, and the image does not display in the page. Browsing the cache directory does reveal thumbnails generated from my images, none being used by my page currently. Searching my entire system for 8fcbe5bd955ad8d999652c15eeda0959.jpg returns nothing. How can I trouble shoot this? -
Django on docker running on cloud9
I'm setting up django application on cloud9. I click Run button to execute docker-compose, and then click Preview Running Application but browser says your access is denied. I'm not sure where I have to check to address the cause of this problem. What is the cause of this problem and what should I do to solve it? The application works on my local PC. Here is the part of my docker-compose.yaml. version: "3" services: django: build: context: ../app container_name: django working_dir: /app ports: - "5000:5000" privileged: true links: - mysqld - redis volumes: - app_static:/app/static - app_media:/app/media env_file: - django.env command: /usr/local/bin/uwsgi --ini /app/uwsgi.ini --touch-reload=/app/uwsgi.ini nginx: build: context: ../nginx container_name: nginx ports: - "8080:80" volumes: - /var/log/nginx - app_media:/app/media:ro - app_static:/app/static:ro links: - django -
I have different models in my project, but I want the same base.html template file for all of my modules. Is there a way I can set that up?
I am making a website for my church. I am using the django framework and I want to have a common base.html file througout all my apps/models. Is there a way to make that happen? I have tried using ../../ notation to get to a file that is in my main directory, but that raises the following error ... Exception Type: TemplateSyntaxError at / Exception Value: The relative path ''../../../sure_foundation_baptist /index.html'' points outside the file hierarchy that template 'main/index.html' is in. main/templates/main/index.html {% extends '../../../sure_foundation_baptist/base.html' %} {% block content %} ... {% endblock %} sure_foundation_baptist/base.html ... {% block body %} {% endblock %} I expected it to extend the file correctly, but the actual output is the previous error -
django include template without reloading tag
I have a base template in which I added some code which uses some tag sets. {% load staticfiles thumbnail load_permissions %} I decided to modularize this by separating some HTML code into a separate file and including it like so: {% include './sidepanel.html' %} the problem is that this sidepanel.html file uses some of the tags of the base file. Now I'm getting a TemplateSyntaxError complaining about a non loaded tag. Do I have to load them in both files or is there a more correct/elegant approach? -
Django change color of the tab in chrome
I ahve an app that monitors a few processes and alerts if some are failing. It does so by changing the background color of the body. However, due to lack of screen real estate the browser is often covered and I only have the top part visible, showing the tabs and maybe the address bar. So, I thought it would be neat if I could change the tab color as an alert. Chrome has the tabs above the address bar I can modify the title of the head... <head class="{{mode}}"> <title>ProcessMonitor</title> </head> but changing the background color here doesnt seem to do anything head.alert { background-color: #FFD6C6; font-family:'Source Sans Pro', sans-serif; } Is it possible to change the color of that tab somehow or does chrome just not support that? -
not able to login to admin: custom user model
I can authenticate using the command line >>> from django.contrib.auth import authenticate >>> user = authenticate(username='shiva@gmail.com',password='123456') >>> user <Employee: shiva@gmail.com> >>> but I am not able login using the url : http://localhost:8000/admin/login/?next=/admin/ model from django.db import models from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser, PermissionsMixin) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Employee(AbstractBaseUser,PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField(default=None) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = MyUserManager() REQUIRED_FIELDS = ['date_of_birth'] -
Django sitemap set custom paginate size?
So I'm using Django (1.11)'s sitemap framework and I need to add about 3.6m records into a sitemap. Django's built-in index sitemap automatically creates a paginated version of the sitemap. I believe each paginated sitemap page contains up to 500,000 records. That is too big and takes too long to load. Is there some way to set a custom number of records contained within each paginated sitemap page? -
How can I return HTML in a Django view?
I am trying to display a matlib plot on my browser, I’m using Django. So far I have: import matplotlib.pyplot as plt import base64 from io import BytesIO fig = plt.figure() #plot sth tmpfile = BytesIO() fig.savefig(tmpfile, format='png') encoded = base64.b64encode(tmpfile.getvalue()) html = 'Some html head' + '<img src=\'data:image/png;base64,{}\'>'.format(encoded) + 'Some more html' with open('test.html','w') as f: f.write(html) However, instead of f.write(html), I want something like: return render_to_response(html) How do I do this with a large html string? -
Django: import errors from corsheaders
I am doing angular/django crud tutorial. I have done in virtual env: pip install django-cors-headers I believe it was successfully installed. But when I start the server with: python manage.py runserver I get the error: 'Import error:No module named djangocrud.apicorsheaders' I added 'corsheaders' to Installed Apps and 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', at the top of MiddleWare in settings.py -
How to count consecutive rows with same value for a column in a database using django?
My App consists of a notification module. If the notifications are consecutively arrived from a same user, I would like to show "n notifications from john doe". eg: 5 notifications from john doe 2 notification from james 4 notofications from john doe How would I count these consecutive rows with same value in a column using django orm? -
How to move Admin pages to static html
Pretty new to Django, and web programming in general, so apologies ahead of time if I am not using correct terminology. I have added Calendar creation and modification functionality to my Admin pages based on this gentleman's page: https://alexpnt.github.io/2017/07/15/django-calendar/. However I would like to embed the calendar pages to ALSO be in it's own Django app that has has additional controls create in jquery and static HTML. Using python 2.7 and Django 1.11. I assume that part of it is to change the urls.py so that instead of url(r'^fullcalendar/', TemplateView.as_view(template_name="fullcalendar.html"), name='fullcalendar') I point to the app I created and a path to it's template directory. However where I am stuck is in the template itself, how would I reference the pages that currently make it up? {% extends "fullcalendar.html" %} in the app template.html file? TIA... -Caolan -
django channels error message on websocket start (Sessions.py)
Whenever I start my django channels websocket. I get this: 2019-01-10 00:24:09,463 - WARNING - server - Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at C:\Users\JAYK~1\Envs\jyst\lib\site-packages\channels\sessions.py:175> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000001B067F32E58>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 57367] path=b'/jysts/m/KIDA_TG'> took too long to shut down and was killed. -
Django order_by on two fields, but one needs to be reversed
I figured out how to do an order by with multiple fields thanks to this post: Django: Order_by multiple fields But I ran into the issue of, one field is a number, the other is a persons name. I need it to be ordered in descending from the highest dues to the lowest, but within that be sorted by name in alphabetical order. I tried this: invoice_items = InvoiceItem.objects.filter(invoice__exact=inv.id).order_by('dues', 'provider').reverse() It does the dues right, goes from group of highest dues like 350 to lowest, but then the names are also reverse so top of the list are names starting with Z y etc... What I need: Bob 350 Carl 350 Mike 350 Thomas 350 April 200 Gary 200 etc.. instead what I get: Thomas 350 Mike 350 Carl 350 Bob 350 Gary 200 April 200 Not sure the right syntax to achieve this. -
Why isn't my migration run from PyCharm affecting my local db?
I'm using PyCharm 2018.2 with Python 3.7. I have defined my database in my settings.py file ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mainsite', 'USER': 'mainsite', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } And using "Option + R" on my Mac, I can bring up the "manage.py" console, where I wish to run a migration. I do so by running the following. It appears to be successful ... manage.py@mainsite_project > sqlmigrate mainsite 0002 bash -cl "/Users/davea/Documents/workspace/mainsite_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py sqlmigrate mainsite 0002 /Users/davea/Documents/workspace/mainsite_project" Tracking file by folder pattern: migrations /Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) BEGIN; -- -- Add field url to article -- ALTER TABLE "mainsite_article" ADD COLUMN "url" text DEFAULT '' NOT NULL; ALTER TABLE "mainsite_article" ALTER COLUMN "url" DROP DEFAULT; COMMIT; Process finished with exit code 0 However, when I look at my database locally, I don't see the extra column added in there ... mainsite=> \d mainsite_article; Table "public.mainsite_article" Column | Type | Modifiers --------------+--------------------------+---------------------------------------------------------------- id | integer | not null default nextval('mainsite_article_id_seq'::regclass) path | character varying(100) | not null time … -
NoReverseMatch at /blah/blah/add though I thought my template if/else/endif would solve the error
I keep getting the error: Reverse for 'grouplocation_add' with arguments '('',)' not found. 1 pattern(s) tried: [u'ipaswdb/grouplocations/add/(?P<pk>[0-9]+)/$'] I am pretty sure it is my url 'ipaswdb:grouplocation_add group_id when group Id doesn't exist (it does if this is being called when an update is happening, but creating a new group, no id yet. The button this is on is to do more things for a group that has already been created. My If else was an attempt to say 'until the form has been submitted thusly the model saved thusly doing an update view with the model.... ' don't enable the button that lets you muck with the other parts of the model until it has been saved once. {% if group_id %} <td><a href=""><button disabled type="button" id="group_add_location" class="btn btn-primary">Add A Group Location</button></a> </td> {% else %} <td><a href="{% url 'ipaswdb:grouplocation_add' group_id %}"><button type="button" id="group_add_location" class="btn btn-primary">Add A Group {% endif %} Given the error clearly my approach is different. I want to also save and return to the update view not the create view. So does that mean in my class GroupCreateView(CreateView): ..do tons of stuf def get_context_data(self, **kwargs): ..do more stuf def post(self, request, *args, **kwargs): if self.request.POST.has_key('submit'): ..DO … -
how to do multiprocessing in django from the inside of views.py?
I am trying to employ parallel processing in my Django web app. I am writing the multiprocessing code inside of the views.py, now I know i cannot write if name == main inside django. I did some research and got to know that, you can follow the below structure to go about incorporating multiprocessing inside views.py: def my_func(args): ....code here.... def optimize(request): for i in range(0,process_list): p = process(target = my_func,args=(arg_list)) pros.append(p) p.start() for t in pros: t.join() When I try the above code, i get an error at the line p.start() where it says errno32 broken pipe error. So how do I go about fixing it? Or is there any other module that i can use for multiprocessing? -
error while adding "moderation" in INSTALLED_APPS
I want to use django-moderation in my django project,I have downloaded the app with pip3 ,issue is when I added the app in INSTALLED_APPS,I have the following exception,can you please advise how to get rid of this? python3 manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1024977b8> Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.7/site-packages/moderation/models.py", line 41, in <module> class ModeratedObject(models.Model): File "/usr/local/lib/python3.7/site-packages/moderation/models.py", line 43, in ModeratedObject editable=False) TypeError: __init__() missing 1 required positional argument: 'on_delete -
Checking if a form was saved from the form via django
I was wondering if there was a django way to know inside of a django form if it had been submitted. I want to basically enable a button if the form was submitted (and thus the record that the button will continue to act on exists), or keep the button disabled until the form was submitted elsewhere creating a record for the button above to act on. I know I can probably do this in javascript by having a hasBeenSubmitted var false on load, and then once submit (the right one) was clicked, set that to true and enabling the button. I think that would work, though wanted to know if there was a more 'Django' way with form helpers to do this or what not. -
Django- ListView returning a list of users with a given tag in a tag field
I'm trying to return a list of users with a particular skill and skills is a TagField (django taggit) in a CustomUser model. I'm struggling to get the queryset right in my ListView (skill_list.html). I want to be able to click on the skill listed on a user's profile (profile.html) and then have that return the skill list page with a list of all users that have that skill. models.py: class CustomUser(AbstractUser): objects = CustomUserManager() position = models.CharField(max_length =200, null=True, default='', blank=True) bio = models.CharField(max_length=400, null=True, default='', blank=True) skills = TaggableManager(help_text="A comma-separated list of tags.") views.py: class SkillView(ListView): model = CustomUser template = 'skill_list.html' queryset = CustomUser.objects.all() def get_queryset(self): queryset = CustomUser.objects.filter(skills__name__in= [self.kwargs['skill']]) return queryset profile.html: <div class="container-fluid" id="profile_container"> <div class="container skills"> {% for skill in user.skills.all %} <div class="skill_bubble"><p class="skill_bubble"><a href=" {% url 'skills' %}">{{ skill.name }}</a></p></div> {% endfor %} </div> </div> skill_list.html: <div class="container"> {% for user in object_list %} <div class="container user_name"> <p class="profile_name"><a href="{% url 'profile_with_pk' pk=user.pk %}">{{ user.first_name }}&nbsp{{ user.last_name }}</a></p> <p class="profile_text">{{user.position}}</p> </div> </div> I have the url set up on the profile page to return the 'skill_list.html', however I get an key error on the skill_list page: Exception value "skill." -
Conecting forms to admin page in django
I´m making my own portfolio and I wanna be able to see the messages that people sent me in the admin page but I don't seem to be able to make it so when someone submits the message it saves in the model and "broadcasts" in the admin page. Models.py from django.db import models # Create your models here. class Messages(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=50) website = models.CharField(max_length=50) text = models.CharField(max_length=500) Forms.py from django import forms from django.core import validators from django.forms import ModelForm from .models import Messages class Messages(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name'}), required=True, label='', max_length=100) email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email'}), required=True, label='', max_length=50) website = forms.CharField(widget=forms.TextInput(attrs={'class' : 'website'}),required=False, label='', max_length=50) text = forms.CharField(widget=forms.TextInput(attrs={'class' : 'text'}), required=True, label='', max_length=500) bot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) class Meta(): model = Messages fields = '__all__' Views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseNotFound from django.template import Template, Context from . import forms # Create your views here. def index(request): return render(request, 'index.html') def portfolio(request): return render(request, 'portfolio.html') def certificate(request): return render(request, 'certificate.html') def contact(request): form = forms.Messages() if request.method == 'post': form = Messages(request.post) if form.is_valid(): form.save(commit=True) return thankyou(request) else: print('CONTACT ERROR') return render(request, 'contact.html', {'form':form}) def … -
Django - add multiple instances of model with various ForeignKey via one form
I have following code: models.py class Tram(models.Model): number = models.CharField(max_length=3) manufactured_date = models.IntegerField(default=date.today().year, validators=[ MinValueValidator(2017), MaxValueValidator(date.today().year) ] ) objects = models.Manager class Meta: ordering = ('-number',) def __str__(self): return self.number class Gate(models.Model): GATE_TYPE = ( ('BJC', u'Bramka jakościowa - człon'), ('BJW', u'Bramka jakościowa - wózek'), ('IKS', u'Inspekcja końcowa - Solaris'), ('IKK', u'Inspekcja końcowa - klient') ) CAR_SYMBOLS = ( ('C1', u'C1'), ('C2', u'C2'), ('C3', u'C3'), ('C4', u'C4') ) BOGIE_TYPES = ( ('WN1', u'Wózek napędowy 1'), ('WN2', u'Wózek napędowy 2'), ('WT', u'Wózek toczny'), ('WN3', u'Wózek napędowy 3'), ('WN4', u'Wózek napędowy 4'), ) GATE_STATUSES = ( ('R', u'Realizacja'), ('O', u'Ocena DZJ'), ('P', u'Ponowna realizacja'), ('A', u'Archiwum') ) GATE_GRADES = ( ('OK', u'Zaakceptowany'), ('NOK', u'Odrzucony') ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(choices=GATE_TYPE, default='BJC', max_length=3) tram = models.ForeignKey(Tram, null=True, on_delete=models.CASCADE) bogie = models.ForeignKey(Bogie, null=True, on_delete=models.CASCADE) bogie_type = models.CharField(choices=BOGIE_TYPES, null=True, max_length=3) car = models.CharField(choices=CAR_SYMBOLS, max_length=2, null=True) area = models.ForeignKey(OperationArea, null=True, on_delete=models.CASCADE) operation_no = models.CharField(max_length=6, null=True) name = models.CharField(max_length=200) content = models.TextField() gate_status = models.CharField(choices=GATE_STATUSES, default='R', max_length=1) gate_rating = models.CharField(choices=GATE_GRADES, blank=True, max_length=3) reject_counter = models.IntegerField(default='0') author = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='author') creation_date = models.DateTimeField(default=datetime.now(), blank=True) modify_date = models.DateTimeField(default='', blank=True, null=True) objects = models.Manager class Meta: ordering = ('-tram',) permissions = ( ('can_change_gate_status', u'Może zmenić … -
In Django template built-in filter "date", what does the format "o" mean?
I'm looking the Django version 2.1. From the document, the date format template built-in filter has an o format which is described as the following: "ISO-8601 week-numbering year, corresponding to the ISO-8601 week number (W) which uses leap weeks. See Y for the more common year format." I don't quite understand this. I tried it with the date 2018-12-31, it outputs '2019'. The document is here: https://docs.djangoproject.com/zh-hans/2.1/ref/templates/builtins/#date Can anyone explain? Thanks in advance. -
Run uWSGI command in a Django docker container
I have a django project that works with web sockets, so my question is, can I run a uWSGI command inside my python container? Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip3 install -r requirements.txt ADD . /code/ CMD [ "uwsgi", "--http", "8081", \ "--gevent", "100", \ "--module", "websocket", \ "--gevent-monkey-patch", "--master", \ "--processes", "4" ] This CMD isn't running, I also tried running it from docker-compose, but it didn't work too. -
Visual C++ 14.0 error while installing mysqlclient on windows
I want to install mysqlclient for work with django, and when i run command pip install mysqlclient i get the following error: error : microsoft visual c++ 14.0 is required but i installed vc++ 2015. how can i install this library? -
Dynamic Namespaces SocketIO - Django - NodeJS - Redis
I am using NodeJS as a second backend to my Django project and I want the namespaces to be dynamic like nsp = io.of('/:namespace') In which the namespace comes from the Django template.