Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
rest_framework NOT NULL constraint failed: tasks_tasks.assigner_id
I am making an app where assigner can assign tasks to assignee when i run the server and try to add a task i get this error: NOT NULL constraint failed: tasks_tasks.assigner_id here is my views: from rest_framework import viewsets, permissions from .models import Tasks from .serializers import TasksSerializer, UserSerializer from django.contrib.auth.models import User class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class TasksViewSet(viewsets.ModelViewSet): queryset = Tasks.objects.all() serializer_class = TasksSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def prefrom_create(self, serializer): serializer.save(self, assigner=self.request.user) here is my serializers.py from rest_framework import serializers from .models import Tasks from django.contrib.auth.models import User class TasksSerializer(serializers.ModelSerializer): assigner = serializers.ReadOnlyField(source='assigner.username') class Meta: model = Tasks fields = ('id', 'url', 'title', 'description', 'assigner', 'assignee') class UserSerializer(serializers.ModelSerializer): tasks = serializers.HyperlinkedIdentityField(many=True, view_name='tasks_details', read_only=True) class Meta: model = User fields = ('id', 'url', 'username', 'tasks') and finally my models.py: from django.db import models class Tasks(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100) description = models.TextField() assigner = models.ForeignKey('auth.User', related_name='tasks', on_delete=models.CASCADE) assignee = models.ForeignKey('auth.User', related_name='assigned', on_delete=models.CASCADE) class Meta: ordering = ('created',) -
Why is the variable set using the django 'with' tag broken into individual strings when using it in a template provided by the include tag?
I am using the with tag to declare a variable my_var. I am using my_var as a placeholder in my input box. Only the first word of my_var is recognized as part of the variable. How do I get the whole string to be recognized? I have explicitly put in "placeholder='this is a test'" and all of the words show up as a place holder which leads me to believe it has something to do with using django templatetags and not the placeholder itself. This picture shows only the word "Must" being displayed. <input type="text" class="form-control" id="username" placeholder="Must" be="" at="" least="" 4="" characters="" long="" (underscore="" period).=""> The above shows my_var being broken into pieces, what is wrong? Here is the code that declares my_var {% with form.username as field %} {% with "Must be at least 4 characters long." as my_var%} {% include "emp/regfield.html" %} {% endwith %} {% endwith %} regfield.html looks like this <div id="div_{{ field.name }}" class="form-group"> <label for="id_{{ field.name }}">{{ field.label }}</label> <input type="text" class="form-control" id="{{ field.name }}" placeholder={{ my_var }}> <div id="{{ field.name }}_error" class="error_div"> {{ field.errors }} </div> </div> -
Django hangs on applying huge migration
I have a table in Postgres 9.5 with about 7KK rows. Django version is 1.10.5. Database and App are different servers with Ubuntu 16.04.2 within one local network. Django's gunicorn server is stopped, so no other operations are being executed. I'm going to add one field there: migrations.AlterField( model_name='balanceentry', name='reason', field=models.CharField( choices=[(b'default', b'Default'), (b'referral', b'Referral'), (b'referrer', b'Referrer'), (b'random', b'Random'), (b'android_offer', b'Android Offer'), (b'ios_offer', b'iOS Offer'), (b'offerwall', b'Offerwall'), (b'withdrawal', b'Withdrawal')], default=b'default', db_index=True, max_length=32), ), And then I'm applying it: $ ./manage.py migrate users 0026_auto_20170419_1758 Operations to perform: Target specific migration: 0026_auto_20170419_1758, from users Running migrations: Applying users.0026_auto_20170419_1758... And monitoring Postgres with pg_top. It's doing ALTER for about 15 minutes, then I see this: 34567 postgres 20 0 401M 39M sleep 2:17 0.10% 0.00% postgres: *** *** ip(45200) idle in transaction This does not change for about 10 minutes (only WCPU is changing from 0% to about 0.1% and back). Then this record disappears (I think this means that client is disconnected), but ./manage.py migrate ... does not change its status at all, it just stays "running" with no changes (I've waited for about 2 hours). I tried to restart postgres service, if I do this, it rolls back transaction (I think), … -
loading a file with variables, sending with context to get parsed
I have a txt file I load in views.py and do some work on (right now it's just splitting by paragraph, but later there will be more work done). Within this document, I have some of Django template tags {{ user.firstName }}, etc. I send this document to the template to get its HTML added, etc. But it won't render the tags. I do know that Django loads the template once and stores it all within a tree for speed. I just can't find a workaround. Can I pre-load the document, then have the parser run? Could I add the HTML tags within the view.py and send it to the template before parsing? Any ideas or thoughts would be great. Here is what I have for code: View.py class DocumentReview(TemplateView): template_name = 'paperwork\document.html' def get_context_data(self, **kwargs): context = super(DocumentReview, self).get_context_data(**kwargs) context['user'] = {'firstName': 'x', 'lastName': 'y'} context['document'] = self.get_document() return context def get_document(self): module_dir = os.path.dirname(__file__) # get current directory file_path = os.path.join(module_dir, 'documents\sample.txt') document = {} with open(file_path, 'r') as fp: data = fp.read() document = data.split("\n\n") return document Here is sample.txt: Hello {{ user.firstName }} {{ user.lastName }}, This is a sample txt file. And this is the … -
Django audio file form validation
I'm trying to add file validation to my Django project. Before I try and add a python library that will parse the file, I want to make sure I can check the file size, extension and content type. For my model form in forms.py I have: class PostForm(forms.ModelForm): def clean_audio_file(self, form): file = self.cleaned_data.get('sound') if file: if file._size > 4*1024*1024: raise ValidationError("Audio file too large ( > 4mb )") if not file.content-type in ["audio/mpeg","audio/wav"]: raise ValidationError("Content-Type is not mpeg") if not os.path.splitext(file.name)[1] in [".mp3",".wav"]: raise ValidationError("Doesn't have proper extension") return file else: raise ValidationError("Couldn't read uploaded file") class Meta: model = Places fields = [ 'title', 'longitude', 'latitude', 'sound', ] for my view, I have: def post_create(request): form= PostForm(request.POST or None, request.FILES or None) form_class = PostForm() if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, 'Successfully Created') return HttpResponseRedirect('/') context= { 'form': form, } return render(request, 'location/post_form.html',context) I've gone through the Docs a few times, and looked for examples of similar file validation, but for some reason the files I upload are not getting validated. The form works as expected, but it still allows files that are too large and incorrect file types without raising the validation error. Any hints on … -
Debug from Django admin
I'm trying to have a print statement appear on the console every time I add data into my Postgres Database (For example "Post succeeded") from the Django admin but no matter where I put print statements (in admin.py or the models) nothing is appearing. I know the data is going through as there is a POST statement goes through and the data is in the database. -
Django limit_choices_to with python Index
I want to limit a Django relationship using limit_choices_by like this. device = models.ForeignKey('Device', limit_choices_to=Q(address[0]='S'),) But this doesn't work. Basically my related address field contains values like 'TA', 'SA', 'CA', 'SB', 'CB' etc and I only want the relationship to show the values beginning with 'S'. Using a standard python command address[0] == 0 I can get it working using limit_choices_to=Q(address='SA') Any thoughts? Thanks -
500 Server Error on Django Website - ImportError: No module named django.core.wsgi
I am uploading a Django website to an Apache 2.4 server on Ubuntu 16.04. My server is running mod_wsgi. I am getting an ImportError: No module named django.core.wsgi. I have read through many other solutions, but none seem to work. I am thinking that my error has something to do with my Python installation (Python 2.7), but I am not sure. My wsgi.py, server conf, and error messages from the Apache logs are below: Apache Error Log: [Thu Apr 13 15:51:06.891778 2017] [authz_core:debug] [pid 27832:tid 140404955539200] mod_authz_core.c(809): [client 134.53.122.114:63670] AH01626: authorization result of Require all granted: granted, referer: http://173.255.204.6/ [Thu Apr 13 15:51:06.891833 2017] [authz_core:debug] [pid 27832:tid 140404955539200] mod_authz_core.c(809): [client 134.53.122.114:63670] AH01626: authorization result of <RequireAny>: granted, referer: http://173.255.204.6/ [Thu Apr 13 15:51:06.891884 2017] [authz_core:debug] [pid 27832:tid 140404955539200] mod_authz_core.c(809): [client 134.53.122.114:63670] AH01626: authorization result of Require all granted: granted, referer: http://173.255.204.6/ [Thu Apr 13 15:51:06.891891 2017] [authz_core:debug] [pid 27832:tid 140404955539200] mod_authz_core.c(809): [client 134.53.122.114:63670] AH01626: authorization result of <RequireAny>: granted, referer: http://173.255.204.6/ [Thu Apr 13 15:51:06.892105 2017] [wsgi:info] [pid 27831:tid 140404925069056] [remote 134.53.122.114:11921] mod_wsgi (pid=27831, process='site', application='site.com|'): Loading WSGI script '/var/www/site/site/wsgi.py'. [Thu Apr 13 15:51:06.892490 2017] [wsgi:error] [pid 27831:tid 140404925069056] [remote 134.53.122.114:11921] mod_wsgi (pid=27831): Target WSGI script '/var/www/site/site/wsgi.py' cannot be loaded … -
Deploy a simple VS2017 Django app to Azure - server error
I've been trying to create a Django web app using VS2017 Preview (which includes Python tools for Visual Studio), and deploy the resulting app to Azure (I'm currently on the 30-day trial period to evaluate Azure). I've done the following: Start VS2017, create a new project with the "Django Web Project" template. This creates a Django webpage with the bootstrap template - simple, and everything works well locally. In VS, go to Connected Services => Publish, select "Microsft Azure App Service", create a new App Service an an App Plan. The instances are created successfully. Click "Publish" to publish via VS WebDeploy. Everything looks good in the console and it says Publish: 1 succeeded, 0 failed, 0 skipped at the end. This results in the standard Azure Welcome-start-page hostingstart.html showing, not the Django page. Once I remove that html file, there's only a The page cannot be displayed because an internal server error has occurred.. I've tried various things: Going to portal.azure.com "Application Settings", setting Python version from "Off" to "3.4" (I'd like 3.5 in fact, which one of MS's tutorial uses - but any will do for now) - then there's just a hostingstart-python.html showing, still no Django. I've … -
How to change the text of a button to an svg element?
I have the following button: and when it is clicked I want to disable, and change the text "Pledge $5.00" to an svg element as the following image. I am using Django and JQuery to achieve this, and so far this is what I have, but it is not working: {% load svg %} {% block js %} <script> $("#pledge-button").click(function(e) { $.ajax( { type: "GET", contentType: "application/json; charset=utf-8", url: {% url 'pledges:home' %}, success: function (msg) { console.log('Succeeded!'); $('#pledge-button').prop('disabled', true).text('').append( {% svg 'pledges/e-icon' %} ); console.log('Button was disabled!'); }, error: function (err) { console.log('Error!') } }); console.log('Hello world') }); </script> {% endblock %} pledges/e-icon is the name of my svg element. I hope somebody could help me since I have not too much experience with web development. -
Django Static Files No module named <app_name>
I'm writing a Django app and I deployed it online but I am running into some problems with the static files. When I run the collectstatic command it says 'There is no module named '. I have looked at the questions on here and none of them answer my question. My static files were stupidly put into the apps specific directory, however I moved them out and tried to run it when they are in the right directory but still no luck. It is really strange: Settings.py: """ Django settings for django_project project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ticketr', # App name ) MIDDLEWARE_CLASSES = ( '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', ) … -
how to get multiple values for onw key and save them to manytomany field in django
I have the multiselect list I will show in the image... models.py class CameraSets(models.Model): user_ids = models.ManyToManyField(settings.AUTH_USER_MODEL, null=True, blank=True) views.py form.user_ids = request.POST['user_ids'] instance = CameraSets() instance.save() print(form.user_ids) I need to send all the selected values from this list to save them in manytomany fields in my model, but it prints the last one selected only, not all of them, as you will see , the number '2' in the end is the id I am getting but not the other one that should come in the querydict... what am I missing here ? -
Django Template - If item == return field from model object
Django 1.10, python 3.5 Hi All! I have a model, in models.py called "Building_type": class Building_type(models.Model): buildingType = models.CharField(max_length=40) def __str__(self): return self.buildingType and a list of buildings that is sent to the django HTML template, called "buildingList", that looks like so: [ {'name': 'building1', 'type': <Building_type: Blacksmith>}, {'name': 'building2', 'type': <Building_type: Inn>}, {'name': 'building3', 'type': <Building_type: Chemist>}, ] I would like to do this: {% for building in buildingList %} {% if building.type == "Inn" %} <p> this is an Inn </p> {% endif %} {% endfor %} However the IF statement never completes as true. I have tried the following, all have failed: {% if building.type == building.type.Inn %} {% if building.type == Inn %} {% if building.type == "Inn" %} If it helps, the following correctly returns "Blacksmith", "Inn", and "Chemist" to HTML: {% for building in buildingList %} {% if building.type %} {{building.type}} {% endif %} {% endfor %} Many thanks if you all can help -
Django: For Loop in Views.py?
I want to keep my templates free of any logic - just html. I'm using a "for" loop in index.html to cycle through a list of posts. Here is the loop: {% for recent in latest %} <h1>{{ recent.title }}</h1> <h2>{{ recent.category }}</h2> {% endfor %} What I want to do is in my Posts class, grab all the posts, checking that they match certain criterion, then place them in variables which could be sent to the template. Here is the view (the logic of which I want to eventually move to models.py): def index(request): # Get latest five posts latest_posts = Post.objects.order_by('-published_date')[:5] # Get a single "top" category post. top_post = Post.objects.get(category = 1)[:1] # set up some contexts top = {'front_post': top_post} context = {'latest': latest_posts} return render(request, 'home/index.html', context, top) Any suggestions? -
Add Create in Version 2 of Django REST API Method
I have a an API built in the Django rest-framework. The first version of a model didn't support post/create. I am now adding v2 of my API using the URL path method described here. Here is my main URL router: from django.conf.urls import include, url from rest_framework.authtoken.views import obtain_auth_token from board.urls import router urlpatterns = [ url(r'^api/token/', obtain_auth_token, name='api-token'), url(r'^api/', include(router.urls)), url(r'^api/(?P<version>(1.0|2.0))/', include(router.urls)), ] Here is my project-specific URL router: from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'sprints', views.SprintViewSet) router.register(r'tasks', views.TaskViewSet) router.register(r'users', views.UserViewSet) Here is my view: class SprintViewSet(DefaultsMixin, viewsets.ReadOnlyModelViewSet): def get_serializer_class(self): if self.request.version == '2.0': return SprintSerializer2 return SprintSerializer queryset = Sprint.objects.order_by('end') My question is: how can I change from this read-only view to an update-able view based on the version? I've thought about two approaches but I'm not sure how to do either... One would be to route to a different view, but I'm not sure how to get the version from the included router. The second would be to somehow tell Django that post/create is supported dynamically, based on the version. [Note: this code is taken from an over-simplified tutorial, but expresses the problem I have in a more sophisticated application] -
Uploading files to S3 with django app on Heroku
I have read similar SO question about this, but those situations seem to differ from what I am experiencing. I have a django app (django-oscar webshop) which uploads media files to Amazon S3. This app is deployed on Heroku and has had no issues until recently. But now when I (or any other user) try to upload a file which is larger than about 1Mb, Heroku displays and application error. I check my logs and there are H18 Server Request Interrupted critical errors for every failed attempt. This is not due to a timeout, because the request gets aborted immediately after firing. The Heroku documentation does not state much information about this H18 error, so I was hoping someone here knows how to help me. Thank you! PS: the application is not running the free hobby-dev program, nor a free hobby-dev database. -
Django method update_or_create troubles to increment value
I've got a Django models: class Item_received_log(models.Model): name = models.CharField(max_length=250) quantity = models.FloatField(default=1) class Inventory (models.Model): name = models.CharField(max_length=250) quantity = models.FloatField(default=1) I would like to update Inventory.quantity each time new item to Item_received_log is posted with matching name. I am not sure if it is right but I've decided to override save method of Item_received_log class so it updates Inventory list upon saving: def save(self, *args, **kwargs): obj, created = Inventory.objects.update_or_create( name=self.name, defaults = {'quantity':(quantity + self.quantity)}) super(Item_received_log, self).save(*args, **kwargs) And in returns: NameError at /admin/accountable_persons/item_received_log/17/change/ global name 'quantity' is not defined How can I resolve my issue or come up with better solution? -
FilePathField is working without path being set
I am extending Django's django.db.models.FilePathField. I do not give it a path. Instead I am setting self.path in my subclasses formfield() method. I am under no illusion that this is good design. I am just curious as to why this is working. The docs state that the path field is required. Is this not enforced in the init method? The reason I set the path in formfield is so that I can have a reference to the model the field is defined on. In the field's init method the model is 'None'. If there is a better way to get a hold of the model I would love to know how. -
django AttributeError: 'str' object has no attribute 'field'
I am getting this error while submitting an ajax request using django. The funny thing is if I execute these commands by hand when the debugger hits it works. Here is the views.py def lhr_search_custodians(request): print request print request.GET print "blah" # pdb.set_trace() if request.method == 'GET': search_text = request.GET.get('search_text') else: search_text = '' custodians = Person.objects.filter(last_name__contains=search_text) context = {'custodians': custodians} return render(request, 'corpsec/legalholdrequests/create.html', context) Here is the javascript query.js $(function () { $('#custodian_search').keyup(function (){ console.log("search fired!!!"); $.ajax({ url: "new/search_custodians", type: "GET", data: { 'search_text' : $('#custodian_search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success : searchSuccess, dataType: 'html', error: function(xhr, errmsg, err) { $('#results'); } }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('$search_results').html(data); } this is the template create.html {% extends "blackbox/show.html" %} {% load static from staticfiles %} {% load formtags %} {% block title %} New Legal Hold Request | {{ block.super }} {% endblock title %} {% block javascript %} {{ block.super }} {% endblock javascript %} {% block show_header_title %} <h4> New Legal Hold Request </h4> {% endblock show_header_title %} {% block tab_menu %} <li class="tab"> <a id="id_modal_matter" href="#matter"> Matter </a> </li> <li class="tab"> <a id="id_modal_custodians" href="#custodians"> Custodians </a> </li> <li class="tab"> <a id="id_modal_electronic_databases" href="#databases"> Electronic Databases … -
How can I run a python program as an admin on a website and display the ouput to the users? Can I use Django?
I am currently doing a project based on sentiment analysis. So I have the python code for sentiment analysis, I want to store the output and display the output on a website. Do I need to have a database???. Should I run the program on a server? Please Help! -
Difference between formset and formset.forms in django template tags
I'm trying to loop through forms in a formset on my template. And I have seen two different ways of doing this and it doesn't seem to make a difference to my code which one I use. {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} And... {{ formset.management_form }} {% for form in formset.forms %} {{ form }} {% endfor %} Does this make any difference? Why put .forms on the end? -
Django Add list generated from the text of one field to many to many field
Having a bit of trouble trying to bulk add a list of items to a many to many field and though having tried various things have no clue on how to approach this. I've looked at the Django documentation and cant seem to find what i'm looking for. He is the code for my models. class Subject(models.Model): noun = models.CharField(max_length=30, null=True, blank=True) class Knowledge(models.Model): item_text = models.TextField() item_subjects = models.ManyToManyField(Subject, null=True, blank=True) def add_subjects(sender, instance, *args, **kwargs): if instance.item_info: item_subjects = classifier.predict_subjects(instance.item_info) if item_subjects: .... post_save.connect(add_subjects, sender=Knowledge) The list is being generated by the classifer.predict_subjects function. I have tried using the m2m_changed connector and the pre_save and post_save connect. Im not even sure the many to many field is the right option would it be better to do make a foreign key relationship. in place of the '...' I have tried this but it doesn't create the relationship between and only saves the last one. for sub in item_subjects: subject = Subject(id=instance.id, noun=sub) subject.save() Ive tried also just tried instance.item_subjects = item_subjects also a load more things that i can't really remember, i don't really think im in the right ballpark to be honest, Any suggestions? -
making a Django chatbot application interact with multiple users
i have a django chatbot application on web faction shard hot. the idea that the application simulate the customer service in chatting with the customers. basically the conversation will exchanged through the API using GET and POST, where it first POST the input then GET calls the python file to SELECT the input form the DB and process it then update the database with the retrieved out put.finally a GET is used to fetch the out put and display it. so far it it working if there is one user at a time, what i am considering now is that i want it to chat with multiple customer at the same time an isolating the each user. Do i have to use Redis just for the chatting part, if yes how i can Merge it in my project? other there are other solution out there? i have developed it using: python3: for the chatbot code. Django: for the website. Mysql: for the data base, that hold the knowledge based for the chatbot such as a table that include number of input and it correspond output. Thank you, -
Django nested relation data
I'm using Django and Django-rest-framework, and I have the next Model and Serializer: class Category(models.Model): id_category = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) name = models.TextField(null=False) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id_category', 'name', 'parent') Now, I want to make a query like Category.objects.filter(parent=None) that returns something like this: [ { "id_category": "UUID", "name": "Father", "childrens": [ { "id_category": "UUID", "name": "Son", "childrens": [ { "id_category": "UUID", "name": "Grandson" } ] } ] }, { "id_category": "UUID", "name": "Other" } ] As you see, a Category could have one father and many children. Need help to make this query, because I don't know how do that. -
how to write urls.py in django 1.10
urls.py file which is in 1.1 version of Django :- urlpatterns = patterns('ecomstore.catalog.views', (r'^category/(?P<category_slug>[-\w]+)/$','show_category', {'template_name':'catalog/category.html'},'catalog_category'), ) which I understood that first argument id prefix to all views. next argument is url which has four argument one is url string(regex),second is view , third is dict passing template name and fourth is location of category. How to write it in Django 1.10 is following it correct way:- from django.conf.urls import url from ecommstore.catalog.views import * urlpatterns = [ url(r'^category/(?P<category_slug>[-\w]+)/$','show_category', {'template_name':'catalog/category.html'},'catalog_category'), ]