Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updated django models can't update
So I recently made some minor changes to my Django models (added a field). Something I've done plenty of times in the past. Now when I got to makemigrations on the server I get the following errors. I have no idea what they mean or where to start diagnosing the problem. Everything works fine on my local machine. Exception in thread Thread-1 (most likely raised during interpreter shutdown):Ex ception in thread Thread-2 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner File "/usr/lib/python2.7/threading.py", line 1082, in run File "/home/pentaqueue/.local/lib/python2.7/site-packages/cassiopeia/type/api/ rates.py", line 82, in _reset : 'NoneType' object is not callable Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner File "/usr/lib/python2.7/threading.py", line 1082, in run File "/home/pentaqueue/.local/lib/python2.7/site-packages/cassiopeia/type/api/ rates.py", line 82, in _reset : 'NoneType' object is not callable -
Django - NoReverseMatch after simple changes in code
So,long story short,I started learning Django basics this week and followed a simple poll creating tutorial,which worked fine,but then I started trying to make a few changes to the code,and due to my inexperience in Django(and to be honest,also in HTML),I ended up getting this NoReverseMatch error. What I basically did was try to change the name of a class and it's uses in the app,and it's objects along the project(class TText). Then the errors started showing up at both the /polls/* ( * being respective id number for a TText) and /polls/*/results in the localhost web page. The first one gives the following error at detail.html,line 5: Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<text_id>[0-9]+)/vote/$'] And the second at results.html,line 9: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$'] And here's my setup of this django app: /mysite urls.py /polls models.py urls.py views.py /templates /polls detail.html index.html results.html Where: /mysite/urls.py is: from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] also - /polls/models.py : from __future__ import unicode_literals import datetime from django.db import models from django.utils … -
Celery error NotRegistered('...')
I'm trying to get a project going with django and stream-framework with cassandra as backhand. Stream-framework uses celery and rabbitmq to queue and process the tasks. I'm on Mac OSX Yosemite, version: 10.10.5. This my celery.py from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cassaStage.settings') from django.conf import settings app = Celery('cassaStage') #app = Celery('cassaStage', namespace='CELERY') also tried like this # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: 'stream_framework.tasks') And the shared tasks that i am trying to run are in https://github.com/tschellenbach/Stream-Framework/blob/master/stream_framework/tasks.py here I start the worker like this celery multi start cassaStage In flower, I can see the task but it immediately fails giving the error NotRegistered('stream_framework.tasks.fanout_operation_hi_priority') I have been going around everywhere in the web, trying to find a solution. Nothing worked so far. My django settings have these for celery CELERY_IMPORTS = ['stream_framework.tasks'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_ACCEPT_CONTENT = {'pickle'} -
Django - Make query to another table from count result
This is a question on the most effective way to make a 2-step query, where the output on the first one is the input on the second one... I have this Model. class Payment(models.Model): timestamp = models.DateTimeField(auto_now_add=True) service_request = models.ForeignKey(ServiceRequest, null=True) split_request = models.ForeignKey(SplitRequest, null=True) amount = models.FloatField() user = models.ForeignKey(User, null=True) lesson_fee = models.ForeignKey(LessonFee, null=True) stripe_token = models.CharField(max_length=150, null=True) class ServiceRequest(models.Model): timestamp = models.DateTimeField(auto_now_add=True) start_at = models.DateTimeField(blank=True) .... hours = models.SmallIntegerField(blank=True, null=True) Currently, i have the following queryset in views.py: payments = Payment.objects.values('service_request').annotate(dsum=Sum('amount')).annotate(dcount=Count('service_request')).order_by('dcount') Which gives something like the following result: service_request dcount dsum ... 177 1 31.2 202 1 31.2 205 1 31.2 197 1 31.2 187 1 62.1 174 2 6.24 155 3 74.52 209 4 46.4 As you can see, i get 5 rows having 1 as the count value. I want to do some aggregations to this resultset, like summing the dsum column for repeated dcount rows, and also summing the 'hours' field that can be found on the ServiceRequest table on a new column. I thought of looping through each row of the resultset, querying for each service_request_pk, but that would be super inefficient. Any ideas? -
Django queryset update method removes objects from queryset
This is not expected behaviour: items = Item.objects.filter(sent=False) items.count() # 3 items.update(sent=True) items.count() # 0 How to update objects without loosing them in queryset? -
Does Django support RESTful API calls?
This is what I need to get done: Frontend makes an AJAX request Backend ,built with Django, makes a call to a REST API that brings back data Backend returns that data to frontend The reason I'm not calling the API directly from the frontend is because it uses an access key that I don't want to be public. My main questions are: Is it possible to do this without having to install another framework? How does Django manage the delay of the API call to "wait" for the answer before sending the data back? -
Debug a Guacamole Java
I have created a program using the Guacamole API. When running locally, I can debug the python using Pycharm debugging, but I want to debug the Java portion of the Guacamole API. Is there a way to debug Java in a django/python program? I have Intellij IDEA but so far can't figure out a way to debug the Java section on the localhost:8000. Thanks -
Django trying to update a specific item that has an id but then also edit other items if need be
I can't figure out why it won't update/edit an item and then add it back to list with the edits. If someone can help me out thanks! If I find my answer before I get a response I will post it.. I posted my views.py, urls.py and the html for the edit page confirm_edit.html just so you can see all of what I am dealing with. thanks for the help! from django.shortcuts import render, redirect, HttpResponse from .models import Course def index(request): context = { 'course' : Course.objects.all() } return render(request, 'chp1/index.html', context) def create(request): if request.method == "POST": Course.objects.create(SLA_TYPE_CD=request.POST['Name'], SLA_TS=request.POST['description'], ACTUAL_COMPLETION_TS=request.POST['description'], TICKET_NUM=request.POST['description'], NOTE_TXT=request.POST['description']) return redirect('/') def edit(request, id): course_to_edit = Course.objects.get(id=id) if request.method == "GET": return render(request, 'chp1/confirm_edit.html', {'course' : course_to_edit}) def update(request, id): if request.method == "POST": course_to_edit.update(SLA_TYPE_CD=request.POST['Name'], SLA_TS=request.POST['description'], ACTUAL_COMPLETION_TS=request.POST['description'], TICKET_NUM=request.POST['description'], NOTE_TXT=request.POST['description']) return redirect('/') def destroy(request, id): course_to_delete = Course.objects.get(id=id) if request.method == "GET": return render(request, 'chp1/confirm_delete.html', {'course' : course_to_delete}) course_to_delete.delete() return redirect('/') from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^create$', views.create), url(r'^(?P<id>\d+)/destroy$', views.destroy), url(r'^(?P<id>\d+)/edit$', views.edit), ] {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit SLA_VARIANCE_NOTE</title> <link rel="stylesheet" href="{% static 'chp1/css/styles.css' %}"> </head> <body> <div id="addcourse"> <h2>Are you … -
Creating a workflow for models in Django app
Building an app that generates different documents required in any one given work-order. Document generation is working fine as I have created modelform to obtain data which is written to each document, 8 views in total. Challenge now is how to encompass all these views into one story of sorts because for any one given job, all 8 documents are to be filled in a certain order , not necessarily one sitting. I have looked into state machines though that seems too complex, then sessions which seem like a temporary solution. Am a django newbie. will be very grateful for any insights. -
Add model relation to ModelForm before saving
models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=32) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True) content = models.TextField() forms.py from django import forms from .models import Article class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['content'] In my web application, the author logs in and writes an article. So clearly, when the author is presented with an ArticleForm, he/she does not need to fill in the author field in the ArticleForm because the application already knows who the author is through the use of session variables. This is the way I tried to add the author: views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Article from .forms import ArticleForm @login_required def new_article(request): author_name = request.session['author_name'] author = Author.objects.get(name=author_name) if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): form.save(commit=False) form.author = author # I suspect the mistake is here # I also tried form.author = author.id form.save() return redirect('success') else: form = ArticleForm() return render(request, 'writings/new_article.html', {'form': form}) When I look at the database table, the author_id column is always NULL. What is wrong with my approach? How do I add a model relation before saving a ModelForm? -
Django 1.10 super-easy filters
I am looking for an easy way to implement a filter for my objects. A basic one. And all I could find was Django+Haystack+Solr or Elasticsearch. And I do not have an experience to use Java apps. Plus ... I want to keep it simple. The closest I could get was django_filter, but the docs for it are ... well not for the noob like me. Plus cant I do the same with plain Django ?? I was able to get simple search to work with no solr :) And I am able to get it to work in admin. If anyone could guide me step, bu step how to set up filter for and status from my model. Model class Contact(models.Model): name = models.CharField(max_length=2000 phone = models.CharField(max_length=10) url = models.URLField(max_length=200, default="https://") email = models.EmailField(max_length=25, verbose_name="Email", default="adress@email.com") STATUS = ( ('A','Active'), ('U','Unactive') ) status = models.CharField(max_length=1, choices=TYPE, default="A") def _unicode_(self): return self.name def _str_(self): return self.name My views with search working: def index(request): #full list queryset_list = Contact.objects.all() #search query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(name__icontains=query)| Q(phone__icontains=query)| Q(url__icontains=query)| Q(email__icontains=query)| #pagination paginator = Paginator(queryset_list, 10) page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: queryset = … -
Django - Change date/time format within HTML tag
I have a Django model that records when a new object from that model is created by a user. This date is printed within my view with the format like... March 20, 2017, 1:49 p.m. Models.py: class Model(models.Model): title = models.CharField(max_length=50, verbose_name='Title') dt_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') dt_updated = models.DateTimeField(auto_now=True, verbose_name='Date Updated') However, I want the date to be printed in the format DD/MM/YYYY or MM/DD/YYYY like 20/03/2017 or 03/20/2017 for example. This is in my HTML as <h5 class='dt-class'>Created <span class='dt-timestamp'>{{ model.dt_created }}</span></h5> Is there any way to convert the format of the date/time from within the {{ model.dt_created }} tag? Or must I go into the view to change how this is printed? Thanks. -
how to get multiple results using same query params django
Is there a way to get two results from using the same query params in django. I find the second value overwrites the first For example: http://localhost:8000/?id=3&id=4 the result returns the value with id=4 but i want result for id=3 and id=4 -
Signaling server in production for WebRTC
Good day my fellow experts, I'm pretty new into this javascript framework thing and I have been asked to implement a WebRTC video chat using django and reactJS. Can anyone guide me into the right direction to accomplish this task? Currently I'm using simpleWebRTC and it's working out of the box but I need to implement a signaling server and I really can't find a noob-proof tutorial to deploy a signaling server in production. -
django include block partal view
I have this 1.html view: {% extends "base.html" %} {% block content %} <h1>this is h1</h1> {% endblock %} And I want to have another partial view: For example I have file somefile.html in this file I have following html: <p>Text in somefile.html</p> How do I include somefile.html in 1.html view ? -
How can I pass user id into a serializer with request data?
I have a project that autenticate by oauth2_provider.ext.rest_framework.OAuth2Authentication. There is a token in the request headers for authenticating and identifying. I think I should not include user id in the request data explicitly when process a create action. But serializer need user info to create a new instance. So I include a user_id field in serializer, and put the value into the request.data dict after authenticating. Is it good? Is there any better way? serializers.py class serializer(serializers.Serializer): user = UserSerializer(read_only=True) user_id = serializers.UUIDField(write_only=True) content = serializers.CharField() views.py class CommentList(generics.ListCreateAPIView): def create(self, request, *args, **kwargs): request.data['user_id'] = request.user.id return super(CommentList, self).create(request) -
how to create new horizontal row for each field in django form?
Very new to django. I would like to have each field in a modelform in a new row on the html page. I've tried to use but that doesn't work. How can I do this? Here is the html I have for the page that displays my form for capturing data: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <table> <thead><th>{{title}}</th> {% for record in record_list%} <tr><td>{{record.county}}</td></tr> <tr><td>{{record.route}}</td></tr> <tr><td>{{record.pmb}}</td></tr> <tr><td>{{record.pme}}</td></tr> <tr><td>{{record.map_sheet_desc}}</td></tr> <tr><td>{{record.drawingdate}}</td></tr> <tr><td>{{record.index_map_filepath}}</td></tr> <tr><td>{{record.grantor_box_filepath}}</td></tr> <tr><td>{{record.control_map_filepath}}</td></tr> <tr><td>{{record.info_sheet_filepath}}</td></tr> <tr><td>{{record.mapdatum}}</td></tr> {% endfor %} </table> <form method="POST" action="/update/"> <fieldset> <legend>Create Map Index Record</legend> {% csrf_token %} {{form_mapindex}} <br><button type="submit">Create Record</button> </fieldset> </form> </body> </html> -
Is it possible to login user during session without email confirmation in allauth?
If it possible to allow user to sign in via allauth without email confirmation for the first session? Once the session expires, then they have to confirm their email in order to log in? If so, is there a way to manage the time to when the session key expires? -
How to generate a response from a POST, with Django REST Framework Bulk
I would like to know what is the way for the Response of a POST with rest_framework_bulk to be modifiable since, by default, I always return the same object or object array sent to it by the service. model: class employee(): name = models.CharField(max_length=4, verbose_name='name') profession = models.CharField(max_length=4, verbose_name='profession') userCreation = models.ForeignKey(userCreation, verbose_name='user') class Meta: verbose_name='employee' def __unicode__(self): return self.name serializers: from django.forms import widgets from .models import employee from rest_framework import serializers from rest_framework_bulk import (BulkListSerializer, BulkSerializerMixin, ListBulkCreateUpdateDestroyAPIView,) class employeeSerializer(BulkSerializerMixin, serializers.ModelSerializer): class Meta(object): relation_user = serializers.ReadOnlyField(source='user.username') model = employee fields = ('id', 'name', 'profession', 'relation_user') view: from django.shortcuts import render from .models import employee from .serializers import employeeSerializer from rest_framework import generics from rest_framework_bulk import ListBulkCreateAPIView class createEmployee(ListBulkCreateAPIView): queryset = employee.objects.all() serializer_class = employeeSerializer url: from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from employee import views urlpatterns = [url(r'^api/createEmployee/$', views.createEmployee.as_view())] urlpatterns = format_suffix_patterns(urlpatterns) def perform_create(self, serializer): serializer.save(relation_user=self.request.user) This works very well and creates the employee without problems, Json that I send to the rest service { name: 'Jhon', profession: 'Medic' } And this is the answer: { name: 'Jhon', profession: 'Medic' } I would like the Response to be able to put something different as a sum, a … -
Appending DB object string to dynamic urls in Django
I need to append a string stored in DB. e.g ?linkappend which is stored in my my DB as a DB object link_append to all ebay links that will be displayed in a page. I think I should use template tags but not sure how to go about it. -
Django - not getting the value from database to show in dropdown list
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar and need to fill the form. Association-dropdown-list won't show any data from database. I only want it to show association name of the current admins-association. Is there something i'm missing? Still a newbie so appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py def event_add_edit(request): if request.method == 'POST': form = CalForm(request.user, request.POST) res = {'success': False} if paramMissing(request.POST, 'name', res) \ or paramMissing(request.POST, 'location', res) \ or paramMissing(request.POST, 'start', res) \ or paramMissing(request.POST, 'end', res) \ or paramMissing(request.POST, 'allday', res) \ or paramMissing(request.POST, 'description', res) \ or paramMissing(request.POST, 'action', res) \ or paramMissing(request.POST, 'association', res) \ or paramMissing(request.POST, 'synced', res): return JsonResponse(res) action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' asoc_id = form.request.POST['association'] association = Association.objects.get(pk=asoc_id.pk) if action == 'add': Event.objects.create( name=name, location=location, start=start, end=end, allday=allday, description=description, synced=synced, association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] … -
Redirecting from generic IndexView to DetailView
There are times in my application where I want to use a DetailView when an IndexView was called. For instance, the user sets the search criteria and the view is an IndexView for the results. If the result only has one row, I want to display a DetailView for the object. Can you redirect from the inside of the IndexView class' get_queryset method? If not, where would you do this redirect? I have not seen any examples on the net to do this. -
Coming up with single filter function for both querysets and objects
I have a Django 1.10 project. Let's say I have a model like this: class Student(models.Model): university = models.ForeignKey(University, ...) objects = CustomQuerySetManager() class QuerySet(QuerySet): def university_rating(self, level): return self.filter(university__rating = level) class University(models.Model): rating = IntegerField(...) So, if we want to filter students by their university rating, we hide model logic from the view code by using Student.objects.univesity_rating(5) instead of Student.objects.filter(university__rating = level. This approach is very DRY in that if I decide to change my model structure so that it affects the way we filter students by their university rating, we will have to make amendments in one place only, instead of tearing hair on our heads replacing snippets across the whole project. But! This code above works only for QUERYSETS, and does not work for MODELS INSTANCES. That is, let's say that (no matter how innatural that is, just let's imagine that as illustrative example), student surname and his university level uniquely defines the student - if there is such student. So I want to do something like: try: student = Stundent.objects.get(surname = ..., university__rating = level) except Student.DoesNotExist: ... The problem is that my custom filter did not help me in this case, and I had … -
Reverse for 'post_edit' with arguments '()' and keyword arguments '{'pk': 6}' not found. 0 pattern(s) tried: []
I've been following djangogirls' tutorial to create a blog with django with little to no trouble, but now I'm going on with their extensions tutorial which works on the web application created on the first one, and I'm coming to the error in the title when I try to get to the detail of a given post, which worked alright before. Here's the error message in full detail Environment: Request Method: GET Request URL: http://127.0.0.1:8000/post/6/ Django Version: 1.10.6 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', 'blog'] 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'] Template error: In template /home/frank/Desarrollo/python/devdjango/djangogirlstut/blog/templates/blog/post_detail.html, error at line 14 Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 4 : 5 : {% if post.published_date %} 6 : 7 : {{ post.published_date }} 8 : 9 : {% else %} 10 : Publish 11 : {% endif %} 12 : {% if user.is_authenticated %} 13 : 14 : 15 : {% endif %} 16 : {{ post.title }} 17 : {{ post.text|linebreaksbr }} 18 : 19 : {% endblock %} 20 : Traceback: File "/home/frank/Desarrollo/python/devdjango/djangogirlstut/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/frank/Desarrollo/python/devdjango/djangogirlstut/lib/python3.5/site-packages/django/core/handlers/base.py" in … -
django rest api FieldError: Cannot resolve keyword 'i' into field
i am facing this weird issue in django "FieldError: Cannot resolve keyword 'i' into field". i am tying to find the problems for hour . below is my model from django.db import models # Create your models here. def code_generate(): while 1: from django.conf import settings import random, string code = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6)) try: Users.objects.get(id=code) except: return code class Users(models.Model): class Meta: db_table='users' id = models.CharField(primary_key=True, default=code_generate, max_length=100) name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=100) creation_timestamp = models.DateTimeField(auto_now=True) email = models.EmailField(max_length=150) mobile = models.CharField(max_length=25) class Login(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=100) i received this error upon calling serializer.is_valid "Choices are: %s" % (name, ", ".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword 'i' into field. Choice s are: creation_timestamp, email, id, mobile, name, password, username