Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare fields within relationship on Django ORM
I have two models, route and stop. A route can have several stop, each stop have a name and a number. On same route, stop.number are unique. The problem: I need to search which route has two different stops and one stop.number is less than the other stop.number Consider the following models: class Route(models.Model): name = models.CharField(max_length=20) class Stop(models.Model): route = models.ForeignKey(Route) number = models.PositiveSmallIntegerField() location = models.CharField(max_length=45) And the following data: Stop table | id | route_id | number | location | |----|----------|--------|----------| | 1 | 1 | 1 | 'A' | | 2 | 1 | 2 | 'B' | | 3 | 1 | 3 | 'C' | | 4 | 2 | 1 | 'C' | | 5 | 2 | 2 | 'B' | | 6 | 2 | 3 | 'A' | In example: Given two locations 'A' and 'B', search which routes have both location and A.number is less than B.number With the previous data, it should match route id 1 and not route id 2 On raw SQL, this works with a single query: SELECT `route`.id FROM `route` LEFT JOIN `stop` stop_from ON stop_from.`route_id` = `route`.`id` LEFT JOIN `stop` stop_to ON stop_to.`route_id` … -
"File not found" using manage.py with pytest-django
I have a Django project in which certain environment variables are set in manage.py which later serve as the values defined in settings.py. Therefore, in order to run pytest-django, I'd like to run manage.py first. I'm trying to follow the instructions in https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django, but I'm running into an unexpected error. I have the following directory structure: . ├── lucy │ ├── settings │ ├── base.py │ ├── development.py │ ├── production.py │ └── staging.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── lucy_web │ ├── __init__.py │ ├── actions.py │ ├── admin │ ├── apps.py │ ├── fixtures │ ├── forms │ ├── lib │ ├── management │ ├── migrations │ ├── models │ ├── runner.py │ ├── serializers.py │ ├── static │ ├── templates │ ├── templatetags │ ├── tests │ ├── urls.py │ └── views ├── manage.py ├── pytest.ini The contents of runner.py are taken exactly from the FAQ: class PytestTestRunner(object): """Runs pytest to discover and run tests.""" def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb def run_tests(self, test_labels): """Run pytest and return the exitcode. It translates some of Django's test command option to pytest's. """ import pytest argv … -
why do I bind to ip 0 failed?
I know if I use IP 0, I will bind to all public IP in my local network.But actually when I run python manage.py runserver 0:8000, it says: [Errno 11004],get addrinfo failed. But in the past, I can ran it successfully. I don't know how to solve it. -
Django - query filtering - Finding IP's equal to or between to IP's
I'm trying to find an IP in a table. My table has two columns, a startIp and and endIp. Sometimes just the start Ip is given (in this case only an IP matching that IP is the valid one). Other times, a range is given. In that case any IP between the start and the end is valid. Is it possible to create that query in one line using Django filters or do I need to query for the ones with a null endIP matching the exact startIp then join those results with the ones equal to and greater than the startIP and less then to equal to the endIP? -
Django + sass styling
So I'm integrating sass/scss into an existing django project, and am currently facing an issue with using django syntax in sass, and it's preventing watching/compiling of the .scss into .css. This is the line/django method that's causing trouble: background-image: url("{% static "onepage/img/bglight.png" &}"); Any help would be appreciated! Gonzo -
Error running server django
I have moved my django project to another new machine driven by virtualBox. I have installed everything I need to run my project. Unfortunately, when I try to run it I got an error saying something that is not possible to find all project required paths. my path project is: path: C:\users\Dev\Documents\GitHub\Python\django\local_sites --local_sites --manage.py ----local_sites ------forms ------models ------urls ------etc. When, I run in the local_sites where is located the manage.py the runserver I got the error below: I when thru the file urls.py to check out the line 17 , but I dont understand really how to figure it out I appreciate the help you can give me. thanks so much -
Django - Trouble adding User to User Group with custom User Model
Previously, I have been using the default Django user model and have been adding users to specific user groups when they register with no problem using this code in my views.py: user.save() user.groups.add(Group.objects.get(name='customers')) However, I have now changed to a custom user model so I can remove the 'username' field in my register form and now this code no longer works. This error message is being thrown when new users try to register: 'User' object has no attribute 'groups' I have searched but can't find an answer to this question. I am very new to working on the backend with Django so please be very descriptive in your answers (i.e where I need to put the code you suggest, models.py/views.py/forms.py etc). Any help would be much appreciated! -
Can't Import Django using Python3 on macOS Sierra
Have both versions of Python (Legacy 2.7.10 and 3.6.2) installed on macOS Sierra. Installed pip using the following steps. Downloaded it using curl: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py Installed pip it by running the installer script: sudo python get-pip.py Checked for any upgrades / updates for pip: sudo pip install -U pip Installed django 1.11: sudo pip install django==1.11 When I run python (legacy): python Python 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print(django.get_version()) 1.11 However, when trying it using python3: python3 Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' Note: I followed a different tutorial and got python3 working with django 1.11 using virtualenv - please don't suggest this as I am new to the python world and just want to use python3 / django 1.11 in a non-virtual environment - I just want have it working like the legacy python interpreter … -
django-taggit - display all tags based on date vlog published
Using django-taggit, I can display all the tags associated for a test vlog. I have vlogs stored in the db that are not yet released to the public (only displayed after a certain date), so that I can store numerous vlog details in the db and then release each individual vlog on a certain day (say Tuesday of each week). This means that the display all tags will include tags for vlog entries that are not yet displayed in the vlog. How can I only display the tags and the count for vlog entries where the vlog_date_published is greater than now? Here is my models code: from taggit.managers import TaggableManager class VlogDetails(models.Model): .... vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.') vlog_tags = TaggableManager(blank=True, help_text='To make a new tag, add a comma after the new tag name.') .... Here is the display all tags template code: {% get_taglist as vlog_tags %} {% for tag in vlog_tags %} {% if tag.num_times > 0 %} <a class='u-tags-v1 g-color-grey g-bg-grey-opacity-0_1 g-bg-grey--hover g-color-white--hover g-rounded-50 g-py-4 g-px-15' href="{% url 'vlog_tag' tag %}" hreflang="en" rel="tooltip" title="{% blocktrans %}Display all vlog entries containing this tag.{% endblocktrans %}"><i class="fa fa-tag icon_padding"></i> {{tag}} … -
Django model validate two ArrayFields have the same length
Given two ArrayField's, how you can validate the length of both are always the same? from django.contrib.postgres.fields import ArrayField class MyModel(models.Model): x = ArrayField(models.FloatField()) y = ArrayField(models.FloatField()) I know you can specific the ArrayField parameter to be the same on both, but what if I want the size to be variable for each record? -
Django - Creating a Custom Template Tag to show Model Name
I have a model: class Survey(models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name And in my template I want to show the name of the current Survey model: <h1> {{survey.name |name}} </h1> I'm using a custom template tag/filter to display that name; however, it is showing as 'str' instead of the name of the current Survey model. Here is the filter code: from django import template register = template.Library() @register.filter def name(value): return value.__class__.__name__ What am I doing wrong here? -
Windows 10 VS Code running Virtualenv. I am getting No module named django.__main__ when I checked the Django version
Running Windows 10 VS Code. I installed python 2.7 I also Installed virtualenv. I am running a virtual environment and pip install Django version 1.4 I ran the following command in my terminal python -m django version I get the following error: C:\Proyectos\virtual\webapp\Scripts\python.exe: No module named django.main; 'django' is a package and cannot be directly executed I cannot start any Django projects. Pip freeze shows it is installed PS C:\Proyectos\virtual\webapp> pip freeze Django==1.4 ./lib/site-packages shows the module directory -
How to run django-pytest on a project which imports settings from environment variables defined in manage.py
I'm working on a Django project in which settings such as SECRET_KEY are defined in a .env file, and manage.py sets the environment variable using python-dotenv as follows: from dotenv import load_dotenv, find_dotenv if __name__ == "__main__": load_dotenv(find_dotenv()) # usual manage.py code Then settings.py simply defines module-level settings from environment variables, for example, SECRET_KEY = os.environ['SECRET_KEY'] I'm now in the process of switching to pytest-django for unit testing. The problem, however, is that without running python manage.py first, the environment variables don't get set, so I end up with E KeyError: 'SECRET_KEY' The way I'm now thinking of working around this is to define a custom action to register with manage.py to run pytest (following https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/). This seems a bit like using a sledgehammer to crack a nut, though. Any suggestions of more elegant ways to go about this problem? -
include() got an unexpected keyword argument 'app_name'
i am making a blog application for my website with django-2.0 when i run server i see the following error File "C:\Users\User\Desktop\djite\djite\djite\urls.py", line 7, in <module> url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), TypeError: include() got an unexpected keyword argument 'app_name' here is my main urls.py from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] and here's my blog/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>d{2})/(?P<post> [-/w]+)/$', views.post_detail, name='post_detail'), ] my views.py: from django.shortcuts import render, HttpResponse, get_object_or_404 from blog.models import Post def post_list(request): #list posts=Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post =get_object_or_404(post, slog=post, status='published', publush__year=year, publish__month=month, publish__day=day) return render (request, 'blog/post/detail.html', {'post':post}) models.py: # -*- coding:utf-8 -*- from django.db import models from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=255,verbose_name=_('title'),help_text=_('add title')) content = models.TextField(verbose_name=_('content'),help_text=_('write here')) publish = models.DateTimeField(default=timezone.now) createtime = models.DateTimeField(_('create time'),auto_now_add=True, auto_now=False,help_text=_('create time')) updatetime = models.DateTimeField(_('update time'),auto_now_add=False, auto_now=True,help_text=_('update time')) author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('author'), on_delete=models.DO_NOTHING,help_text=_('choose author')) … -
Django request.GET Recieves Dict of Arrays
I am using Django's Restful Api 'APIView'. When I do a request.GET I get the following: {'param_A': ['things_A'], 'param_B': ['things_B']} However, I was wondering if there was a way to get the parameters not in form of an array so like this: {'param_A': 'things_A', 'param_B': 'things_B'} -
How to limit the selectable date range on UI for Crispy Form - forms.DateField?
In my form declaration, I have this field: effective_date = forms.DateField(required=False, label='Effective Date', widget=forms.TextInput(attrs={'class': 'datepicker'})) I want to limit the selectable date range on the datepicker to be [today - 30, today]. Is there a way to do it in Django crispy form? I'm using Django 1.9 with crispy form. FYI I tried the SelectDateWidget but it is not the UI I want. I'm looking for a component which can render this UI and support date range restriction: -
Django get unique manytomany
class Word(Model): word = CharField() categories = ManyToManyField('Category') class Category(Model): name = CharField() What is the best way to fetch all unique list of categories? For example, if I have apple -> General, Garden pear -> General, Garden computer -> IT I want to get the following list of lists (General, Garden) (IT, ) -
Why and how do params in annotate affect each other?
I've been reading https://docs.djangoproject.com/en/1.11/topics/db/aggregation/ a lot, but I'm still missing something. Using Django 1.11, say I have the following models: class School(models.Model): pass class Classroom(models.Model): school = models.ForeignKey(School, on_delete=models.PROTECT) active = models.BooleanField() busy = models.BooleanField() class Chalkboard(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.PROTECT) class Whiteboard(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.PROTECT) And I create a school, with a classroom, which has 2 whiteboards and 2 chalkboards: s = School() s.save() c = Classroom(school=s, active=True, busy=False) c.save() Chalkboard(classroom=c).save() Chalkboard(classroom=c).save() Whiteboard(classroom=c).save() Whiteboard(classroom=c).save() Whiteboard(classroom=c).save() I want a summary of how many chalkboards there are at each school that is active but not busy. q = School.objects.filter( Q(classroom__active=True) & Q(classroom__busy=False) ).annotate( chalkboard_count=Count('classroom__chalkboard'), ) q[0].chalkboard_count 2 # as expected Now I want to know about chalkboards and whiteboards. q = School.objects.filter( Q(classroom__active=True) & Q(classroom__busy=False) ).annotate( chalkboard_count=Count('classroom__chalkboard'), whiteboard_count=Count('classroom__whiteboard'), # added this line ) q[0].chalkboard_count 6 # expected 2 q[0].whiteboard_count 6 # expected 3 If I chain the calls to annotate, I get the same result. q = School.objects.filter( Q(classroom__active=True) & Q(classroom__busy=False) ).annotate( chalkboard_count=Count('classroom__chalkboard') ).annotate( whiteboard_count=Count('classroom__whiteboard') ) q[0].chalkboard_count 6 # expected 2 q[0].whiteboard_count 6 # expected 3 All the while, the counts are what I expect Chalkboard.objects.count() 2 Whiteboard.objects.count() 3 What am I doing wrong here? -
Showing child properties on main database object in Django admin site
i am asking a similar question to this here but the solutions presented in that question did not make sense my situation. Basically i have 3 different models set up. One for portfolio which holds a number of transactions, one for coins which is just a model holding some info on a coin and a transaction model which holds info on a purchase of a coin and is tied to a portfolio: models.py from django.db import models class Portfolio(models.Model): name = models.CharField(max_length=250) @property def coins(self): return Transaction.objects.filter(portfolio=self) def __str__(self): return self.name class Coin(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=5) price = models.DecimalField(max_digits=20, decimal_places=9) info = models.TextField() website = models.TextField() rank = models.IntegerField() def __str__(self): return self.name + " - " + self.symbol class Transaction(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE) coin = models.ForeignKey(Coin, on_delete=models.PROTECT) purchaseDate = models.DateTimeField() soldDate = models.DateTimeField(default=None, null=True, blank=True) amount = models.DecimalField(max_digits=20, decimal_places=3) price = models.DecimalField(max_digits=20, decimal_places=9) Now my problem is I want to see a list of transactions when I click on a portfolio however currently all I see is this: without the coins property showing up and inside it its transactions. I also can see the individual coin and transaction objects but that aren't all tied together … -
How do you save a single space (" ") in a field in a django Model?
My model definition looks like this: class MyModel(models.Model): tag_separator = models.CharField(max_length=1, null=True, blank=True) The tag_separator is a single character, and it can be a single space: " ". I need to select null=True in order to get it to work, but when I POST data through my REST API, it saves the tag_separator as an empty string: "tag_separator": "". Is there a simple way to stop django from assuming that my single space string is an empty string? I am using: Django==1.11 and djangorestframework==3.7.7 -
Django 1.10 media (FileField) 404
My first question ever, so go easy. I'll give as much detail as possible. My setup django 1.10 (I know, I need to upgrade) python 3.5.[something] postgres DB gunicorn nginx The problem and what I've tried The problem is that I pulled a recent commit that was working fine locally and suddenly none of a model's images, which previously rendered fine, are working - I'm getting 404s for all of them. I've tried the following: Checking out previous commits Restarting gunicorn (sudo systemctl restart gunicorn) Restarting nginx Restarting postgresql Using python manage.py shell to access objects and check that they're still associating with a URL to the file My code works when run locally - none of the uploaded images/files are causing 404s. As with my production environment, the logos folder sits in the main directory of my project, rather than being appended to a media folder (which other answers and the django docs suggested would be the case - this could be a red herring though). My browser console shows the 404s and that it's trying to fetch from <domain.com>/media/logos/<filename>, even though they're stored (I've checked the file structure) in <project_folder>/logos/<filename> (i.e. without the media folder), but this was … -
what is the documentation to make a excellent regex in django?
i need do match path to validate my email in django: path() path('validate_email/<slug:username>/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/<slug:token>', views.validate_email, name="validate_email") I want to catch the username, email and generate a token to validate a email step by step from django 2.0.1. -
Django: path doesn't find the right primary key in url path
I'm using django2 and I get an error when I access this url: http://127.0.0.1:8000/hotes/12/access/7/update I get an error 404 "None access object was found" To make a long story short: I want to update an object linked to another. To do so, I have to send through the link, both primary keys (12 and 7 in the url). Also, I use the generic view "UpdateView" given by Django. This is the path concerned in my project.urls: urlpatterns = [ path('hotes/<int:pk>/access/<int:access_pk>/update',views.AccessUpdateView.as_view(), name='access_update'), ] I want the second primary key to be used in my view "AccessUpdateView". This is a part of my models.py: class Host(models.Model): name = models.CharField(max_length=30, unique=True) usage = models.CharField(max_length=30, blank=True) function = models.CharField(max_length=30, blank=True) production = models.NullBooleanField(blank=True, null=True) place = models.CharField(max_length=30, blank=True) type = models.CharField(max_length=30, blank=True) processor = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) storage = models.CharField(max_length=10, blank=True) memory = models.CharField(max_length=10, blank=True) dns_inner = models.CharField(max_length=50, blank=True) dns_extern = models.CharField(max_length=50, blank=True) os = models.ForeignKey(Os, null=True, related_name='hosts', on_delete=models.SET_NULL, blank=True) class Access(models.Model): service = models.CharField(max_length=20) client_access = models.NullBooleanField(blank=True, null=True) ip = models.GenericIPAddressField() login = models.CharField(max_length=30, blank=True) password = models.CharField(max_length=50, blank=True) host = models.ForeignKey(Host, related_name='access', on_delete=models.CASCADE) As you can see on host can have multiple access but an access in linked to only one … -
Django admin, ManyToManyField -> ForeignKey relation
Suppose I have these models (with some properties omitted obviously): class Product(Model): name = CharField(max_length=100) class Variety(Model): product = ForeignKey(Product) class ProductMerge(Model): parent_product = ForeignKey(Product) products = ManyToManyField(Product, related_name='merge_proposals') How can I show all the Varieties of all Products of a ProductMerge on an inline inside of the admin panel? I've tried settings a custom get_queryset on a TabularInline: def get_queryset(self, request): return Variety.objects.filter( product__in=self.instance.parent.child_products.all()) But I get the following exception: ValueError: 'marketplace.Variety' has no ForeignKey to 'marketplace.ProductMergeProposal'. -
nginx doesn't serve static files
I've configured a conda virtual environment for Python 3.6 under OS X and installed everything necessary to test the deployment: Nginx, django, gunicorn, celery. My app runs perfectly well on a Django test server, so I've tried serving it via Nginx. The site works (all pages open and submissions carry on), but Nginx serves no static files. Here are the relevant lines from my project's setting.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(BASE_DIR, 'config.json')) as conf: CONFIGS = json.loads(conf.read()) ALLOWED_HOSTS = ['localhost'] DEBUG = CONFIGS["DEBUG"] STATIC_URL = '/static/' STATIC_ROOT = CONFIGS['STATIC_ROOT'] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Now config.json (I removed irrelevant lines): { "DEBUG": false, "STATIC_ROOT": "/Users/user/static/" } Here is how the files are referenced in the base of my templates: {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title></title> <!-- Bootstrap Core CSS --> <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet"> <!-- Style customisation --> <link href="{% static 'css/custom.css' %}" rel="stylesheet"> <!-- jQuery --> <script src="{% static 'js/jquery.js' %}"></script> <!-- Bootstrap Core JavaScript --> <script src="{% static 'js/bootstrap.bundle.js' %}"></script> </head> I've added the include sites-enabled/*.conf; line to the <conda_env_dir>/etc/nginx/nginx.conf: ... include conf.d/*.conf; include sites-enabled/*.conf; } (END) as it was …