Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Wagtail CMS Explorer Menu Not Showing Child Pages
I upgraded Django project Wagtail CMS version and am now running latest Wagtail version 1.11.1 and Django version 1.11.3. In other projects I've updated, I noticed the new explorer menu in Wagtail Admin that shows recent child pages. But, it this project, it just shows a top link Pages then a server error where the page titles should go. In the console I am getting an error Failed to load resource: the server responded with a status of 401 (Unauthorized) on :8001/admin/api/v2beta/pages/?child_of=1 - I am not sure how to debug this and could use a little guidance. Other than this, everything works flawlessly. Thank you. -
Google App Engine Django App Admin login causes 502 every time
I've been dealing with an issue that's driving me nuts - help!? App works great locally. I'm using my google cloud postgres sql server for this. SAME ONE i reference for my app on AppEngine. I can deploy to appengine. I can get to GET routes just fine. I can get to the Django Login screen JUST fine. I enter the SAME superuser I login with locally and it spins out and throws a 502. There are a number of errors... I'm not sure where to look next and I spent last night trying to "fix" it and making matters worse I'm sure. I rebuilt the whole friggin app using the template, got it up again, STILL having the admin issue. I've included some helper files below with redacted items in [] - some with info as to what is in the field in case I'm not sre I'm correct. Let me know what else is helpful? Is this where I just start drinking? (kidding, sort of) But really... I don't fully understand what could have gone wrong here as I don't really "get" the GAE environment... any help is GREATLY appreciated. settings.py # mysite/settings.py # Build paths inside the … -
django autocomplete light not rendering in admin
I've been tryingn to implement autocomplete on a add/update page for a model called KeywordInContext, and even though I've gone through with most of the steps I'm not seeing any changes on my admin page. Nothing's getting rendered. My fields aren't being altered at all by my form and I'm not really sure what's going wrong. models.py @python_2_unicode_compatible class KeywordInContext(models.Model): main_keyword = models.ForeignKey(Keyword) context = models.ForeignKey(Keyword, related_name='keyword_context', blank=True, null=True) @python_2_unicode_compatible class Keyword(models.Model): word = models.CharField(max=200) views.py: class KeywordInContextAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return KeywordInContext.objects.none() qs = Keyword.objects.all() if self.q: qs = qs.filter(word__istartswith=self.q) return qs forms.py: class KeywordInContextForm(forms.ModelForm): main_keyword = forms.ModelChoiceField( queryset = Keyword.objects.all(), widget = autocomplete.ModelSelect2(url='keywordincontext-autocomplete'), ) context = forms.ModelMultipleChoiceField( queryset = Keyword.objects.all(), widget = autocomplete.ModelSelect2Multiple(url='keywordincontext-autocomplete'), ) class Meta: model = KeywordInContext fields = ('__all__') So far, nothing changes on the admin page for KeywordInContext at all. No error messages for me to see either. I'm not sure what's going wrong here? -
Using django tags inside angular 4 templates?
I have a web server in Django and Angular 4 frontend, but my problem is that I can't use tags Django in templates angular. E.g. I have this index.html like root in /templates (django) {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>TrackerFrontend</title> <base href="{% static %}"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Fontin"> Not work --> </head> <body> <app-root>Loading...</app-root> <script type="text/javascript" src="{% static 'inline.bundle.js' %}"></script> <script type="text/javascript" src="{% static 'polyfills.bundle.js' %}"></script> <script type="text/javascript" src="{% static 'styles.bundle.js' %}"></script> <script type="text/javascript" src="{% static 'vendor.bundle.js' %}"></script> <script type="text/javascript" src="{% static 'main.bundle.js' %}"></script> </body> </html> If I try call a media file from my server I can see this <img src="{% get_media_prefix %}/images/2017-08-12-19-28-20st1folio1.png"> But when I copy and paste the same img tag, do npm run build in my project angular and run again my server, I receive errors in terminal Template parse errors: Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) this index.html is a copy of the real in frontend app, but I add {% load static %} and others tags to call bundle.js files. It's possible replicate that call … -
Upgraded Django Wagtail CMS, Now No Admin JS Assets Found
I just upgraded my project to Wagtail 1.11.1 in my local environment then performed a migration and everything worked great. I pushed my changes to repo, then pulled into live project and performed exact same steps. The site still works and is live and when I login it doesn't alert me to upgrade. But, my admin submenus don't work and when I check the console, it shows nearly all admin js files as not found. I cleared the browser cache but no luck. And before I do something drastic as do a database restore, I was hoping someone here could provide some guidance. I attached a screen shot of my console. I am also using Django==1.11.4 -
Creating an object with a field based on the last one in django
Consider the following Model: class Tickets(models.Model): number = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) and the following method that creates a ticket: @transaction.atomic() def create_ticket(self): last = Tickets.objects.order_by('created_at').last() next_number = 1 if last is None else last.number + 1 new_ticket = Tickets.objects.create(number=next_number) return new_ticket This fails if create_ticket is called concurrently, as the transaction won't have a reason to abort (no same record has been updated by multiple calls) but last will return repeated results on some runs. I'm aware of auto incrementing fields and they're not an option in this case, as there is extra logic in place that may cause next_number to reset to 0. I'm leaning towards finding a way to acquire a table lock but was hoping to find an easier way. -
Celery tasks using specific sentry logger not working
Following sentry example for celery integration and using specific logger is not working as sentry is receiving any error or any logger. Anyway to control loggers to send to sentry? import logging import celery import raven from raven.contrib.celery import register_signal, register_logger_signal sentry_logger = logging.getLogger("logger_for_sentry") class Celery(celery.Celery): def on_configure(self): client = raven.Client('https://<key>:<secret>@sentry.io/<project>') # register a custom filter to filter out duplicate logs register_logger_signal(client, logger=sentry_logger) # hook into the Celery error handler register_signal(client) app = Celery(__name__) app.config_from_object('django.conf:settings') -
How to implement forms for sets and supersets of objects with Django
Imagine the following two Django models: class Item(models.Model): ''' A single Item of something. ''' name = models.CharField(unique = True) sets = model.ManyToManyField('Set', blank = True) def get_supersets(self): ''' Returns the list of all the supersets the item belongs to EXCLUDING the directly linked sets. ''' res = [] for set in self.sets: res = res + set.get_all_supersets() return res class Set(models.Model): ''' A set of items wich can either contain items or not (empty set allowed). Sets can be grouped in supersets. Supersets will contain all items of the related subsets. ''' name = models.CharField(unique = True) superset = models.ForeignKey('self', on_delete = models.SET_NULL, null = True, blank = True) # Note: Self-reference to the same object is avoided by excluding it from the forms queryset for the superset field. def get_all_spersets(self): ''' Returns all supersets of the set. ''' if self.superset: return [self.superset] + self.superset.get_all_supersets() else: return [] I found two options for implementing the connection between supersets and the corresponding items of the sets in a given superset: On saving a set or an item update the item_set of the supersets. With this, all relations will be stored in the database. This also needs to include some logic … -
django value error need more than one value to unpack
Please before my answer is marked as duplicate, I would appreciate if someone went through it first. I'm trying to access a products page in an ecommerce project but when I try to access the page I get a value error as below: Internal Server Error: /product_view/1/ Traceback (most recent call last): File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/agozie/shoppingmall/shop/views.py", line 15, in product_view p = get_object_or_404(Product, product_slug) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/shortcuts.py", line 85, in get_object_or_404 return queryset.get(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/db/models/query.py", line 371, in get clone = self.filter(*args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/db/models/query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/home/agozie/anaconda3/envs/env1/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1151, in build_filter arg, value = filter_expr ValueError: need more than 1 value to unpack [13/Aug/2017 19:07:23] "GET /product_view/1/ HTTP/1.1" 500 104231 I have gone through all other questions relating to mine but they all have something to do with splitting a code. Here is my models.py: class Product(models.Model): … -
How to filter duplicate values?
I have table like this in Django + postgres: ____________________ | room_id | user_id | |-------------------- | 1 | 100 | | 1 | 101 | | 2 | 100 | | 2 | 102 | | 3 | 103 | ... Each room_id can be duplicated only 1 time. I need to figure out room_id where to users are. Simple way: user_id_1 = 100 user_id_2 = 101 rooms = Room.objects.filter(users__in=[user_id_1, user_id_2]) temp = [] for room in rooms: if room.id in temp: room_id = room.id break else: temp.append(room.id) But is there any sql filter way? -
Unable to extend django template properly?
I have a base.html template which contains basic html definitions .The other templates are defined below // pages/dashboard.html {% extends 'base.html' %} {% block body %} {% include 'components/nav.html' %} {% include 'components/dashboard.html' %} {% endblock %} // components/dashboard.html <div class="page-container"> <div class="main-page"> {% block dashboard %} {% endblock %} </div> </div> // mailer/new.html {% extends 'pages/dashboard.html' %} {% block dashboard %} <h1>hello</h1> {% endblock %} The view renders mailer/new.html the problem is that the block containing <h1>hello</h1> is not working. Where am i going wrong with that ? -
Cannot assign a user in Django
i have a simple chat application where i've customize the Authentication back end to use only the name. So far it is working and the users is logged in using Django login(). Now i have a problem with assign a user where this Error came up and cus the rest of the app to stop: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f7db7b71e80>>": "PChat.user" must be a "User" instance. View.py from chatbot import settings from django.shortcuts import render from django.http import HttpResponse, JsonResponse,HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate, login from Pchat.models import PChat from django.contrib.auth.models import User @csrf_exempt def P_home(request): context= locals() template= 'P_home.html' return render(request,template,context) @csrf_exempt def P_chat(request): context= locals() template= 'P_chat.html' return render(request,template,context) @csrf_exempt def LogIIn(request): if request.method == "POST": name = request.POST.get('param1') user = authenticate(username=name) login(request, user) return HttpResponse("OK") @csrf_exempt def Post(request): if request.method == "POST": msg = request.POST.get('param1', None) c = PChat(user=request.user, message=msg) c.save() return JsonResponse({ 'msg': msg, 'user': c.user.username }) models.py from django.db import models from django.db import models from django.contrib.auth.models import User class PChat(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User) message = models.CharField(max_length=200) def __unicode__(self): return self.message auth_backend.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class PasswordlessAuthBackend(ModelBackend): """Log in to … -
Access JSON data from page with authentication using Python 3 and requests. [on hold]
I'm trying to download JSON data from the page I've made recently. Everything works fine until I try to download data from 'login required' part of the page. I've tried many solutions (requests, robobrowser, urllib etc.), but nothing works. I suppose it's something very basic or stupid. Probably the best way is to use Python Requests, so I focus on that. My code for downloading the data by Python Requests: import sys import requests URL = #my url to login page URL_to_data = #my url to data accesible only to loged users client = requests.session() client.get(URL) csrftoken = client.get(URL).cookies['csrftoken'] login_data = dict(username='user', password='pass', csfrmiddlewaretoken=csrftoken, next='/') r=clinet.post(URL, data=login_data, headers=dict(Referer=URL)) response = r.get(URL_to_data) data = response.json() Error message: response = r.get(...) 'Response' has no attribute 'get' And the relevant code from Django (1.9.1) project: from django.contrib.auth.decorators import login_required [...] urlpatterns = [ ... url(r'testsj/',login_required(views.TestList.as_view()), ] Other details: I'm using Raspbian with Python 3.4 as a test server. I have newest version of requests library. Any ideas, what I'm doing wrong? -
Beginner Questions about django-viewflow
I am working on my first django-viewflow project, and I have some very basic questions. I have looked at the docs and the cookbook examples. My question is which fields go into the "normal" django models (models.Model) and which fields go into the Process models? For example, I am building a publishing model, so a document that is uploaded starts in a private state, then goes into a pending state after some processing, and then an editor can update the documents state to publish, and the document is available through the front facing web site. I would assume the state field (private, pending, publish) are part of a process model, but what about the other fields related to the document (author, date, source, topic, etc.)? Do they go into the process model or the models.Model model? Does it matter? What are the considerations in building the models and flows for separation of data between the two types of models? Another example - why in the Hello World example is the text field in the Process model and not a model.Models model? This field does not seem to have anything to do with the process, but I am probably not understanding … -
How do you enforce password complexity at user registration with Django authentication?
I'm using the built in Django authentication application. By default it has no password complexity so I'm trying to enable that. I did find this documentation: https://docs.djangoproject.com/en/1.11/topics/auth/passwords/#module-django.contrib.auth.password_validation But it specifically calls out that validators aren't applied when a user is created so it's no help to me. I would really love to see a github project that uses this authentication app so I can see how to properly use this in a project. Here are my forms.py and views.py files: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth import password_validation class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField(label="Repeat Password", widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] class UserEditForm(forms.ModelForm): class Meta: model = User fields = {'first_name', 'last_name', 'email'} views.py from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from .forms import LoginForm, UserRegistrationForm, UserEditForm from django.contrib.auth.decorators import login_required from django.contrib import messages def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) … -
Can't test django autocomplete light view
Just following the tutorial for django autocomplete and I'm a little worried because I already can't seem to figure out how to see the view for autocomplete despite writing the view and url for it. I'm trying to use autocomplete-light on admin for a model called KeywordInContext urls.py: url(r'^keywordincontext-autocomplete/$', views.KeywordInContextAutocomplete.as_view(), name='keywordincontext-autocomplete',), views.py: class KeywordInContextAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.user.is_authenticated(): return KeywordInContext.objects.none() qs = KeywordInContext.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs So I'm trying to just perform the "test view" part of the tutorial where I can see my autocomplete view and either I didn't configure something correctly or I didn't type in the url. the url I attempt to use for the test is /admin/gtr_site/keywordincontext/?q=7 the only part of tht url that I actually type in is ?q=7 for a random primary key... but any variant of this just loads the "KeywordsInContext" admin page. What am I missing? -
Create TabularInline for model that has FK relationship to parent of the registered model
Disclaimer: I'm new to Django, so I'm still learning the Django way of doing things. The project I'm working on has a uUser model and a Student model. Previously, the UserAdmin was doing double duty for both models, but now the time has come to create an independent StudentAdmin that allows admins to easily edit/create/etc students. User contains base info for Student (i.e. first and last name, email, phone, etc.) and Student contains more info (i.e. parent phone, class, todos, etc.). Related models like 'Class', 'Grade', etc. have FK relationships to User, which at first didn't strike me as an issue. But when I went to reuse the inline classes created for UserAdmin in the new StudentAdmin, I've run into this error: <class 'my_project.admin.TodoInline'>: (admin.E202) 'my_project.Todo' has no ForeignKey to 'my_project.Student. This isn't surprising, so I thought I could merely override the _init_ method on TodoInline to use parent_model.user, but then I ran into errors relating to ForwardOneToOneDescriptor and missing _meta fields. Given this use case, I believe there has to be a solution to this, but I'm currently at a loss for Django-related vocabulary for researching this issue further. class TodoInline(admin.TabularInline): model = Todo fields = ['content', 'completed', 'category', … -
How to pass more than one argument to a function in views.py, also using only one of the arguments in the regex expression?
HTML: <button class="btn btn-lg btn-primary btn-block" type="submit"><a href="{% url 'record_and_play' nameOnly no_of_frames %}" style="color: white;">GO!</a></button> Function definition in Views.py: def record_and_play(request, nameOnly, no_of_frames): # ... return render(request, 'processing/start.html', soundFile) And relevant code in urls.py file: urlpatterns = [ url('^process/$', views.create, name='process-page'), url('^process/start/(?P<nameOnly>\w+)/', views.parseData, name='start'), url('^process/start/(?P<nameOnly>\w+)/', views.record_and_play, name='record_and_play'), url('^process/start/(?P<nameOnly>\w+)/new/', views.parseData, name='start-new'), ] -
count no. of views in django blog post
i want to count no of views for a specific post. this is my model class Post(models.Model): user=models.ForeignKey(User,blank=True,null=True) title=models.CharField(max_length=50) content=models.TextField() count = models.PositiveSmallIntegerField(default=1, blank=True, null=True) pic=models.FileField(upload_to='pic',null=True,blank=True) category = models.ForeignKey(Category, blank=True) tags = TaggableManager(blank=True) date_created=models.DateTimeField(default=timezone.now) def __unicode__(self): return self.title -
I would like to generate 4 levels dropdown form using django model forms
I would like to build a multilevel dropdown hierarchy in Django using Models.And informations should be updates dynamicaly without reloading the page.I know that i should use Ajax,but is it possible to generate a template from the following models: class Pays(models.Model): nom_pays=models.CharField(max_length=45) def__str__(self): return self.nom_pays class Province(models.Model): nom_province=models.CharField(max_length=100) pays=models.ForeignKey(Pays,on_delete=models.CASCADE) def__str__(self): return self.nom_province class Ville(models.Model): nom_ville=models.CharField(max_length=100) province=models.ForeignKey(Province,on_delete=models.CASCADE) def__str__(self): return self.nom_ville class Commune(models.Model): nom_commune=models.CharField(max_length=100) ville=models.ForeignKey(Ville,on_delete=models.CASCADE) def__str__(self): return self.nom_commune It it possible to generate that model from django model forms or I should create manualy forms with HTML? -
Django Graphos show empty graphs
In my django app I'm using graphos with google charts to create different graphs like line, pie and column charts for different data queries. The problem I'm facing is that when the queryset returns empty handed. There are no items in the database matching the query. What is the best thing to do to show an empty graph with a message like "No Data Available"? Because when I leave it like this I get in the place of the graph "Data column(s) for axis #0 cannot be of type string" error message. I tried creating a list of dummy empty objects with zero values for the line charts. And it worked but some other graphs have more complicated queries and it will be a very troublesome job to create "fake" zeroed data for the chart to appear empty especially if it is a pie chart. -
How to show results from database splited on the columns in django
I have a question about how to show list of records from db splitted on for example 3 columns. I tried to wrote this : {% for wpis in wpisy_kat %} <a href="{% url 'detale_kat' slug_kat=wpis.slug_kat %}">{{ wpis|slice:"1:5" }} </a> ({{ wpis.cnt_witryna }}) <br /> {% endfor %} but on the end I still have full list (in my case 56 records). -
How to print ascii banner on start of Django server?
How to print an ASCII art banner on the console when I run python manage.py runserver Something similar to the below one: Reference: Ajin Abraham MobSF https://github.com/MobSF/Mobile-Security-Framework-MobSF/wiki/1.-Documentation Is there a way to hook to the runserver command? -
How do you annotate Django admin's filter_horizontal with associated filed of the M2M field?
How do you annotate Django admin's filter_horizontal? That is put information about other fields for an entry in the multi select. For example, class A(models.Model): aa = models.CharField() bb - models.ManyToManyField('self') class AAdmin(admin.ModelAdmin): filter_horizontal = ['bb'] So bb will show in the multiselect but how do you also show the associated aa field with the bb field? filter_horizontal will not accept aa as argument. -
Django API request is empty using React
So I am using axios in order to send a JSON request to Django API. axios({ method: 'post', url: 'http://127.0.0.1:8000/' + this.state.dataRequestEndPoint, data: (reqData) }); Just before the axios call I can see the request: Object {nvm: "", a: Array(1), b: Array(1), c: Array(1), d: Array(1)} However, when it gets to Django: class TargetClass(APIView): def get(self, request): Here request is empty: (Pdb) request.data <QueryDict: {}> (Pdb) request.body b'' def post(self): pass What am I doing wrong? P.S. Tried to send the request with fetch as well: fetch('http://127.0.0.1:8000/' + this.state.dataRequestEndPoint, { method: 'POST', body: reqData, }) None of it works.