Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-chartit highcharts options object "chart" not displaying subtitle
I get different results in the displayed chart when I use the highcharts option "chart" in chart_options. Example 1 will display the subtitle but not the background color. Example 2 will show the background color but not the subtitle. Anyone else encountered this behavior? Python v2.7.5 Django v1.10 django-chartit v0.2.7 django-highcharts v0.1.7 Example 1: displays subtitle, not backgroundColor #Create the PivotChart object site_prod_pivotcht = PivotChart( datasource = site_prod_ds, series_options = [ {'options':{ 'type': 'column', 'stacking': False}, 'terms': [ 'prod_value', 'wx_adj_value']} ], chart_options = {'title': { 'text': 'Actual versus Wx Adjusted Production Data'}, 'subtitle': { 'text': report_range}, 'backgroundColor': '#7FFFD4', 'xAxis': { 'title': { 'text': 'Group:Sites'}} } Example 2: displays backgroundColor, not subtitle #Create the PivotChart object site_prod_pivotcht = PivotChart( datasource = site_prod_ds, series_options = [ {'options':{ 'type': 'column', 'stacking': False}, 'terms': [ 'prod_value', 'wx_adj_value']} ], chart_options = {'chart':{ 'title': { 'text': 'Actual versus Wx Adjusted Production Data'}, 'subtitle': { 'text': report_range}, 'backgroundColor': '#7FFFD4', 'xAxis': { 'title': { 'text': 'Group:Sites'}}} } -
Django - Return a response and then update the DB
Given a request, is there a way in django to first return a response and then keep doing some work like updating the DB? This is for performance reasons. I want the users to receive their response very fast, but DB updates take some time. Thanks. -
Django Compare Statement with field array
I am trying to add a datepicker to my form and I am having a bit of trouble. I had thought this bit of code would work but I can't seem to exclude the 'releasedate' tag within the field array. {% for field in form %} {% if field.label_tag != "releasedate" %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-2"> {{ field.label_tag }} </label> <div class="col-sm-10"> {{ field }} </div> </div> {% endif %} {% endfor %} My views.py: class AlbumCreate(CreateView): model = music_models.Album fields = ['artist', 'album_title', 'genre', 'releasedate', 'notes', 'album_logo', 'rating'] Why am I wrong here? Since I'm getting the discussion going, I suppose it doesn't hurt to ask a related question: https://docs.djangoproject.com/ja/1.9/topics/forms/modelforms/#selecting-the-fields-to-use According to this I can specify things like this if using the ModelForm class widgets = { 'name': Textarea(attrs={'cols': 80, 'rows': 20}), } Does the same apply when using any of the generic views? If so, how do you apply it? -
Can't access related object during cleaning on model level, Why?
My view.py def property_new(request,pk,uri): unit = get_object_or_404(Unit, pk=pk) title = 'property' uri = _get_redirect_url(request, uri) if request.method == "POST": form = PropertyForm(request.POST) form.unit = unit if form.is_valid(): properties = form.save(commit=False) properties.unit = unit try: properties.save() except ValidationError: messages.add_message(request, messages.ERROR, str(unit.id) + "-Failed to add Property since it already exists") return redirect(uri) messages.add_message(request, messages.SUCCESS, str(properties.unit) + "-SUCCESS Object created sucssefully") return redirect(uri) else: form = PropertyForm() return render(request, 'object_edit.html', {'form': form, 'title':title, 'extend': EXTEND}) My model.py class Property(CommonInfo): properties = models.CharField(max_length=140) is_true = models.BooleanField(default=False) propertytype = models.ForeignKey(Propertytype) unit = models.ForeignKey(Unit) date = models.DateTimeField(null=True, blank=True) followup_date = models.DateTimeField(null=True, blank=True) quantity = models.PositiveSmallIntegerField() def __str__(self): return self.properties def clean(self): model = self.__class__ if (self.unit ): raise ValidationError('Same property cant be assigned more then ones') def save(self, *args, **kwargs): self.full_clean() return super(Property, self).save(*args, **kwargs) Error I am getting when I try to save : RelatedObjectDoesNotExist at /unit/property/new/7/ Property has no unit. I am getting this error from clean method in my model triggered by validation. Why? I assign the form with unit value just before the validation. I have exactly same code for different models that works fine. -
Django channels times out with daphne and worker
I have a problem with django channels. My Django app was running perfectly with WSGI for HTTP requests. I tried to migrate to channels in order to allow websocket requests, and it turns out that after installing channels and running ASGI (daphne) and a worker, the server answers error 503 and the browser displays error 504 (time out) for the http requests that were previously working (admin page for example). I read all the tutorial I could find and I do not see what the problem can be. Moreover, if I run with "runserver", it works fine. I have an Nginx in front of the app (on a separate server), working as proxy and loadbalancer. I use Django 1.9.5 with asgi-redis>=0.10.0, channels>=0.17.0 and daphne>=0.15.0. The wsgi.py and asgi.py files are in the same folder. Redis is working. The command I was previously using with WSGI (and which still works if I switch back to it) is: uwsgi --http :8000 --master --enable-threads --module Cats.wsgi The command that works using runserver is: python manage.py runserver 0.0.0.0:8000 The commands that fail for the requests that work with the 2 other commands are: daphne -b 0.0.0.0 -p 8000 Cats.asgi:channel_layer python manage.py runworker Other info: … -
How do I organize the fields shown in the Django admin when using TabularInline?
I have a problem trying to control which fields are displayed in the tabular inline admin. These are the models: -------------------------------models.py---------------------- from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) def __str__(self): return self.person.name -------------------------------admin.py---------------------- from django.contrib import admin from .models import Group from .models import Person from .models import Membership class MembershipInline(admin.TabularInline): model = Membership extra = 0 readonly_fields = ('person', 'date_joined', 'group', 'invite_reason') fields = ('date_joined', 'group', 'invite_reason') class PersonAdmin(admin.ModelAdmin): inlines = (MembershipInline,) class GroupAdmin(admin.ModelAdmin): inlines = (MembershipInline,) admin.site.register(Person, PersonAdmin) admin.site.register(Group, GroupAdmin) -
Django queryset: filter DateTimeField if datetime.now() is greater than field - 24 hours
I can't understand how do this. I have an Event model with a start_datetime field. I want to select all events where datetime.now() >= start_datetime - 24 hours. I try with filter() but I can't understand how to tell 'start_datetime - 24h'. Can you help me please? -
Switched from virtualenv uwsgi to global uwsgi and site-packages seems not to be found
I followed this guide: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html Switching from a virtualenv uwsgi install to a global uwsgi produces this error: Traceback (most recent call last): File "/var/MyServer/lib/python3.4/site-packages/django/__init__.py", line 3, in <module> from django.utils.version import get_version File "/var/MyServer/lib/python3.4/site-packages/django/utils/version.py", line 3, in <module> import datetime File "/usr/lib/python3.4/datetime.py", line 7, in <module> import time as _time ImportError: No module named 'time' unable to load app 0 (mountpoint='') (callable not found or import error) Am I correct in understanding where my problem lies, and how can I resolve this issue? By the way, I am using Python 3.4 -
why does django authentication not recognize request.user variable?
I'm using Django 1.10. I have the following setup: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'IFTHQ', 'rest_framework' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Views.py: from django.shortcuts import render from IFTHQ import models from django.contrib.auth.decorators import login_required # Create your views here. def home(request): """A view of all bands.""" return render(request, 'IFTHQ/publicpages/front.html') @login_required(login_url="login/") def dashboard(request): member = models.Member.objects.get(id=request.user.id) data = {} data["profile"] = member return render(request, 'IFTHQ/dashboard/dashboard.html', {"data": data}) @login_required(login_url="login/") def membership(request): data = {} data["profile"] = member return render(request, 'IFTHQ/dashboard/membership.html', {"data": data}) I confirmed that there's a member in the member object, however, when I log in, I get this error: Environment: Request Method: GET Request URL: http://<<domain>>/ Django Version: 1.10.2 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'IFTHQ', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/arcee123/trekfed/env-trekfed/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/arcee123/trekfed/env-trekfed/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/arcee123/trekfed/env-trekfed/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/arcee123/trekfed/env-trekfed/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/arcee123/trekfed/trekfed/IFTHQ/views.py" in dashboard 14. member = models.Member.objects.get(id=request.user.id) File "/home/arcee123/trekfed/env-trekfed/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/arcee123/trekfed/env-trekfed/lib/python3.5/site-packages/django/db/models/query.py" in … -
Big data analytical tool using django
This is code to push the data into elasticsearch using django problem is when i run my code its throwing me an error like return outside function in return i.e in tis line of my code HttpResponse(json.dumps(res)) so anyone guide how to resolve this? for row in csv_reader: my_dict={} if row: row_str=row[0]; row_arr=row_str.split(','); my_dict['mfname']=row_arr[1]; my_dict['aum']=row_arr[2]; my_dict['ret_1yrs']=row_arr[3]; my_dict['ret_2yrs']=row_arr[4]; my_dict['ret_3yrs']=row_arr[4]; my_dict['ret_5yrs']=row_arr[4]; if row_arr[0] != 'id': my_list.append(my_dict) res['BDATInventory']=my_list csvfile.close() return HttpResponse(json.dumps(res)) def BDAT_db_inventory_api(request): my_list=[] res={} all_items=BDATDB.objects.all() -
Query search. Return a list of results instead of just the first. By prefix substring
I'm trying to get all objects which has the searchWord as a substring, in the column symbol. if the searchWord is G, and there's five stock objects that exist: GOOG APPL FLO.CO GARY OEGP Then I'd like to retrieve GOOG and GARY but not OEGP. Just the prefix substring Below is a scrap of code I've tried. But it'll just return one object. results = stock.objects.all().filter(symbol=searchWord) for x in results: print(x.symbol) -
Conditionally display image based on day of week
So i am trying to display a specific image based on the day of week. I am using the date template tag right now but it is just not working. What am I doing wrong here? {% if date.w == 1 %} <img class="ootd center-block" src='img1'> {% elif date.w == 2 %} <img class="ootd center-block" src='img2'> {% elif date.w == 3 %} <img class="ootd center-block" src='img3'> {% elif date.w == 4 %} <img class="ootd center-block" src='img4'> {% elif date.w == 5 %} <img class="ootd center-block" src='img5'> {% elif date.w == 6 %} <img class="ootd center-block" src='img6'> {% elif date.w == 0 %} <img class="ootd center-block" src='img7'> {% endif %} -
Django model "doesn't declare an explicit app_label"
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. -
How to upload images in batch in django admin
I am creating a django gallery and I want my admin to select multiple images instead of one at a time and upload it at the same time to different fields. Currently I have to select one, upload it and then wait for it to finish to upload another one. I want to upload a batch of images at the same time. Can anyone please help me with this? -
django-autocompletion-light simple foreign key completion shows not editable drop-down widget
I have a model for countries: class Country(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name That is referred by a foreign key in the UserDetails model: class UserDetails(models.Model): ... country = models.ForeignKey(Country,verbose_name='Country',null=True, blank=True, default = None) By using django-autocomplete-light I would light that when inserting the country I have a text widget that completes while writing the first letters. Thus, I have prepared: class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Country.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs With urls.py: app_name='shared' urlpatterns = [ url( r'^country-autocomplete/$', CountryAutocomplete.as_view(), name='country-autocomplete', ), ] And for the UserDetails form: class UserDetailsForm(forms.ModelForm): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2(url='shared:country-autocomplete') ) class Meta: model = UserDetails fields = [...,"country"] As a template I have used: {% load static %} {% block content %} <form method="post" action="."> {% csrf_token %} {{ user_form.as_p }} {{ user_details_form.as_p }} <input type="submit" value="Submit" /> </form> {% endblock %} {% block footer %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'autocomplete_light/select2.css' %}" /> <script type="text/javascript" src="{% static 'autocomplete_light/jquery.init.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/autocomplete.init.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/select2.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/vendor/select2/dist/css/select2.css' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/vendor/select2/dist/js/select2.full.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/forward.js' %}"></script> <script type="text/javascript" … -
Django valeurs uniques (distinct) d'une double relation Many2many
je souhaite obtenir la liste des valeurs uniques d'une relation multiple d'un objets ayant aussi une relation multiple avec mon objet principal. Explication : j'ai trois objets , formation, contenu et acquis une formation à plusieurs contenu qui on chacun plusieurs acquis. Dans le template de ma liste de formation j'ai besoin de voir la liste des contenu + les acquis de chacun des contenus. j'y arrive mais j'obtient des doublons (du fait que de mêmes acquis sont obtenus dans différents contenu...) J'imagine qu'il faille que je crée une méthode dans mon objet formation, mais je ne sais pas comment réaliser le queryset sur double variable many2many imbriqué. -
how do I exit dbshell (sqlite3) in command line when using django?
How do I exit dbshell (sqlite3) in command line when using django? It's my first time to use the command.I watch book and practicing django at the same time.After I run this command,I have no idea how to leave the environment since i have never learned sql before. -
Django media files not loading from cache in server
I am using sorl thumbnail to fetch and display my media file and it is working perfectly in my local. But when I deployed my project to a Heroku free account my media files are returning a 404 error. The Images a displayed correctly at the moment when I upload it but after some time when I check again it gives me 404. I think 404 happens when the images are fetched from cache. When I inspect this is from where the files are fetched "/media/cache/de/3c/de3cebdc4d0655a1c8f20865058daa8e.jpg" and it returns me a 404 I have given url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.STATIC_ROOT, }), in my app's url.py file and not in my sites url.py file. -
if request.method == "POST" end of statement expected
So I am watching django 1.9 tutorials on https://www.youtube.com/watch?v=KbOei4IRinc and on the minute 6:30 . the guy wrote this code: def post_create(request): form = PostForm() if request.method == "POST": print request.POST context = { "form": form, } return render(request, "post_form.html", context) and it seemed to work with him. but it didn't work with me and underlines the space between print and request (end of statement expected) note : I am using django 1.10 -
Django: loop over query and return newest related object
I have Unit in my app that creating Orders and Reports each week, I want view that results as table containing name of Units in first column and 3 newest Orders and Reports in next 6 column. so i need query of Units and 3 of related Order and Report to each Unit. I try to use prefetch_related in this way but don't know how to limit it (and even make it work) Unit.objects.filter(parent__name__contains="x").prefetch_related('order_set', 'reportfrom_set').order_by('order__date','reportfrom__submit_datetime') Thanks in advance -
How pass variable from parent to child template in Django?
catalog.html extends cabinet.html cabinet.html include menu.html catalog is contain other templates and have variable {{MyVariable}} how i can access this variable in menu template? -
Confusing ValueError with "must be x instance" where the passed instance is the correct one
An app called Project has a ManyToMany field called contributors, where users can be stored. I'm trying to allow users to assign other users to this project. This part of the code works. To make it even more user friendly I also try to exclude users from query that are already assigned to the project but this is where an error occurs. What is confusing about this is that I get ValueError that says "Must be "Project" instance.", even though the passed instance IS a project instance. models.py class Project(models.Model): ... contributors = models.ManyToManyField(User, blank=True, related_name='contributors') ... forms.py class ContributorForm(forms.Form): contributors = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: fields = [ "contributors", ] views.py # Add user to a project @login_required() def projects_user_add(request, id): # Fetch the project if it exists instance = get_object_or_404(Project, id=id) # Form for adding users to contributors list form = ContributorForm(request.POST or None) form.fields["contributors"].queryset = User.objects.exclude(project=instance).order_by("username") # Get search query if applicable query = request.GET.get("q") if query: form.fields["contributors"].queryset = form.fields["contributors"].queryset.filter(Q(username__icontains=query)).distinct().order_by("username") # Validate the form if form.is_valid(): user = form.cleaned_data.get("contributors") instance.contributors.add(user) messages.success(request, "User successfully added to project!") return HttpResponseRedirect(instance.get_edit_url()) # Context dict to return for template context = { "title": "Add user to project: " + instance.title, "form": form, … -
Django 1.10 AdminDateWidget() Use in ModelForm
The Django docs aren't clear on using ModelForm. First, how do I set up my urls.py? I simply do this: from . import views as music_views url(r'album/add/$', music_views.AlbumCreate(), name='album-add'), In my views I'm trying to use the AdminDateWidget: from . import models as music_models from django import forms from django.contrib.admin.widgets import AdminDateWidget class AlbumCreate(forms.ModelForm): class Meta: releasedate = forms.DateField(widget=AdminDateWidget()) model = music_models.Album fields = ['artist', 'album_title', 'genre', releasedate, 'notes', 'album_logo', 'rating'] My template is: {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-2"> {{ field.label_tag }} </label> <div class="col-sm-10"> {{ field }} </div> </div> {% endfor %} My struggle here is that I am getting this error when rendering the page: Exception Value: sequence item 0: expected str instance, DateField found But according to the https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/ docs, DateField is one of the allowable datatypes. So I am obviously doing it wrong somehow, but don't know how to do it right. Can someone help me out on this? I tend to prefer ground up examples to study from, if possible. -
Django - logging configuration
my logging is not working on the dev server, instead locally is working. here is the configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'log_file':{ 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/django/my_project.log', 'maxBytes': '16777216', # 16 MB 'formatter': 'simple' }, 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'null': { 'class': 'logging.NullHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'my_project': { 'handlers': ['log_file', 'console'], 'level': 'INFO', 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, } } then, if I create a logger instance: logger = logging.getLogger('my_project') and I try to log something: logger.info('something') logger.debug('something else') it doesn't work (nothing written on /var/log/django/my_project.log), while locally it works. Am I missing something? -
Programming a fall-back for in-memory python object retrieval
In a Django website of mine, there's a newsfeed made up of text and photos that everyone is able to view. The newsfeed is made up of 2000 latest user submissions, globally viewed by everyone. I've been using redis to store and retrieve these user submissions. However, to speed things up, I'm now going to look up the latest 2000 submissions directly from memory. I'll do this via pushing IDs of new entries into a python list, and saving the submitted data in a corresponding python dictionary. Moreover, I'll trim the list if it's len is above 2000, and call the clear() method on the corresponding dictionaries that have to be removed. This way my memory wouldn't overflow. My question is about handling persistence. An edge case occurs where memory is wiped (e.g. a restart). How should I handle this case? One way I can think of is keeping copies of user submissions in redis once. Upon restart, I retrieve the data from redis. From then on, I again keep retrieving everything from memory (and a copy in redis). The scheme above looks like the right way to handle the need for persistence, whilst employing the speed of in-memory retrieval …