Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF token missing or incorrect on POST form with FILE Upload
When I submit the form I see this which shows that I submit file as well as csrfmiddlewaretoken However POST Handler shows error message "CSRF token missing or incorrect." Handler def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = DocumentForm() return render(request, 'backend/upload.html', { 'form': form, 'users': AppUser.objects.all() }) template {% extends "backend/base.html" %} {% block content %}{% load static %} <!-- Page Content Holder --> <h2 class="hline">Example Form With Progress Bar Uploader</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <div class="line"></div> <div class="row"> <div class="col-md-6"> <form name="documents" id="docs" data-toggle="validator" class="dropzone" role="form" enctype="multipart/form-data" action="" method="POST"> {% csrf_token %} <div class="form-group"> <label for="inputUser" class="control-label">User</label><br /> <select class="selectpicker" name="user" id="user" required> <option>Please select a user</option> {% for user in users %} <option value="{{ user.pk }}">{{ user.username }}</option> {% endfor %}} </select> <div class="help-block … -
Django Ajax and net::ERR_CONNECTION_RESET with jquery-file-uploader
I'm trying to integrate jquery-file-uploaded (https://github.com/blueimp/jQuery-File-Upload) into django app. Assembly of JS code is done with brunch. Sample of the request in the browser So the code sends the request, but I always get jquery.js:9570 POST http://localhost:8000/api/v1/upload/documents/ net::ERR_CONNECTION_RESET However, django server says 127.0.0.1 - - [19/Dec/2017 00:21:18] "GET /backend/dashboard/ HTTP/1.1" 200 - 127.0.0.1 - - [19/Dec/2017 00:21:18] "GET /static/js/backend.js HTTP/1.1" 304 - 127.0.0.1 - - [19/Dec/2017 00:21:18] "GET /static/js/vendor.js HTTP/1.1" 304 - 127.0.0.1 - - [19/Dec/2017 00:21:19] "GET /static/js/vendor.js.map HTTP/1.1" 304 - 127.0.0.1 - - [19/Dec/2017 00:21:19] "GET /static/js/backend.js.map HTTP/1.1" 304 - 127.0.0.1 - - [19/Dec/2017 00:21:22] "POST /api/v1/upload/documents/ HTTP/1.1" 200 - 127.0.0.1 - - [19/Dec/2017 00:23:51] "POST /api/v1/upload/documents/ HTTP/1.1" 200 - If I enable IPDB inside django POST handler, I can debug stuff, but I always get that ERR_CONNECTION_RESET back in the browser. This is my JS code // used for file upload //require('blueimp-file-upload/js/vendor/jquery.ui.widget.js'); //require('blueimp-file-upload/js/jquery.iframe-transport.js'); //require('blueimp-file-upload/js/jquery.fileupload.js'); require('blueimp-file-upload'); // prepare the file upload functionality $('.js-upload-btn').click(function() { $('#fileupload').click(); }); $('#fileupload').fileupload({ //url: '/backend/documents/upload/', url: '/api/v1/upload/documents/', dataType: 'json', //contentType:"application/json", sequentialUploads: true, beforeSend: function(xhr, data) { //debugger; xhr.setRequestHeader('X-XSRF-TOKEN', this.form.formParams().csrfmiddlewaretoken); xhr.setRequestHeader('X-CSRF-TOKEN', this.form.formParams().csrfmiddlewaretoken); xhr.setRequestHeader('X-CSRFToken', this.form.formParams().csrfmiddlewaretoken); xhr.setRequestHeader('x-csrftoken', this.form.formParams().csrfmiddlewaretoken); }, start: function(e) { $('#modal-progress').modal('show'); }, stop: function(e) { $('#modal-progress').modal('hide'); }, progressall: function(e, data) { var progress = parseInt(data.loaded … -
title not showing up in queryset when __str__ method was used (django ORM)
Inside this Django tutorial i'm learning to create a blog site. Right now, we are at the point where we are using the Django ORM to interact with the database. I was following every step and i hit a wall at queryset, where the item name isn't showing up, and this was after i did this: def __str__(self): return self.title the output that i get when i type Narticle.objects.all() is queryset Narticle:Narticle object(1) instead of <queryset [<Narticle: 'hello world']> my steps are below this model: my model for narticle is from django.db import models class Narticle(models.Model): title= models.CharField(max_length=100) slug= models.SlugField() body= models.TextField(max_length= 100) date=models.DateTimeField(auto_now_add= True) i entered the following on the command line: from narticle.model import Narticle i typed Narticle and i got <class 'narticle.models.Narticle' > i then entered the following Narticle.objects.all() and i got <queryset[]> i then typed narticle= Narticle() then narticle which gave me Narticle: Narticle object(none) i then typed narticle.title = "hello world" which was followed by Narticle.objects.all() Which gave me < queryset [<Narticle: Nartice object (1)>]> i typed narticle.save() i then exited command line,and then in models.py of narticle i typed def __str__(self): return self.title i then went back to command line and repeated the process … -
Django model class self-representation
Is there a handy way to create a json self-representation of a model Class in Django project? Say I have a model like this: class MyModel(models.Model): some_bool_field = models.BooleanField(default=True) some_char_field = models.CharField(max_length=20, blank=False) I need a serializer of some sort that will return me a json object representing model architecture of the class itself, something like: { 'model_class': 'MyModel', 'some_bool_field': {'type': 'BooleanField', 'default': 'true'}, 'some_char_field': {'type': 'CharField', 'max_length': '20', 'blank': 'false' } } I'm using Django-rest-framework for API creation, so maybe there is ready solution buried inside framework I'm not aware of? -
Android best practice to validate form that uses an API, app side or server side?
I'm here again with a new question about android and I hope that experts helps me with this question to keep improving my abilities. I'm using retrofit to make an app that connects to an API to add new content, I do that with a form in my app and this forms requires validations, at this moment I implemented the validators inside my app and displays the errors with setError() and requestFocus(), all this on app side. From my API backend I'm using Django with Django Rest Framework, and with that I'm making my forms and my serializers, the advantage of using this is that if I post not valid data it returns me as response a json with each field and it's errors on a list, something like this: { "errors": { "password": [ "Required field." ], "email": [ "Required field." ] }, "error": true } My question in this case is, What is the best practice to handle the validators of my form to post the information? Completely from the app(empty field or invalid format), or using that response from the API which contains the information of server side validation? I hope this is not a bad question, … -
Receiving <MultiValueDict: {}> for file upload sent from React-Redux front-end
So I have a React-Redux front-end and I'm working on a file upload section. I'm having difficulty getting it to work and pretty much all of the documentation and SO questions I see are related to using Django forms, which I am not. For example: Empty Request.FILES with Django Upload forms What I am ultimately trying to do is take the files submitted from the front-end and save them to a specific directory on the server: ./fileupload. But I haven't gotten that far. This is what I have so far: from django.views import View from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.http import HttpResponse @method_decorator(csrf_exempt, name='dispatch') class SaveDocumentView(View): def post(self, request): print(request.FILES) # Something goes here, not sure what return HttpResponse('result') The thing is is it seems like it is submitting the file successfully to the server as the server does respond with "result". However, I am getting a <MultiValueDict: {}> with the print(request.FILES). According to the documentation (again using Django forms), I would access the data with request.FILES['file']. There is no file, so it generates an error. https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/ So that is one part of it. The other part is how do I save the file to a … -
Django Count filter annotation not working
I have two models 'ModelParent' and 'ModelChild', where 'ModelParent' has many 'ModelChild', here is my models structure: class ModelParent(models.Model): ... some params ... class ModelChild(models.Model): TYPES = ( (1, 'First'), (2, 'Second'), ) parent = models.ForeignKey(ModelParent, on_delete=models.CASCADE, related_name='childs') type = models.SmallIntegerField(choices=TYPES, default=0) Currently, there's only one 'ModelChild' in the database who belongs to the only 'ModelParent' currently in the database, the 'type' value of the 'ModelChild' is equal to '1', I'm getting the 'ModelParent' object and I need to aggregate to it the count of his 'childs' where type is '1' and also the count of his 'childs' where type is '2', this is the way I'm trying to do so: queryset = ModelParent.objects \ .annotate(first_count=Count('childs', filter=Q(childs__type=1))) \ .annotate(second_count=Count('childs', filter=Q(childs__type=2))).get(pk=1) The query doesn't throw any errors but when looking at the response, the values for both annotations are '1', when it should be '1' only for 'first_count' and '0' for 'second_count'. I have also noticed that no matter what value I set to 'childs__type' within the filter "filter=Q(childs__type=1)", the result is always the same, I can set it like this for example: 'childs__type=10' and still the count is equal to '1'.. it is like the entire 'filter' param is being … -
Passing two arguments through URL
I have this link in my template: <a href="{% url 'listings:listing_detail' name_initials=university.name_initials l_slug=list.l_slug %}" class="btn btn-primary">See More</a> And here is my view associated with it: class UniversityHomePageView(ListView): model = Listing context_object_name = 'listing' template_name_suffix = '_university_homepage' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['university'] = University.objects.all() context['company'] = Company.objects.all() return context I want this link to go to the the listings page however it is giving me an error: NoReverseMatch at /tu/ Reverse for 'listing_detail' with keyword arguments '{'name_initials': '', 'l_slug': 'stafford-apartments'}' not found. 1 pattern(s) tried: ['(?P<name_initials>\\w+)/(?P<l_slug>[-\\w]+)$'] I am not really sure what to do. I think I need to be passing two variables to the view but if what I am doing isn't correct then I am a little lost on what to do, I have read the docs but don't quite no what to do still. Using Django 1.11. -
django orm not interactig with the database although the __str__ method was used
I'm entirely new to programming and i'm not all that good with every computer science term, anyway,inside this Django tutorial i'm learning to create a blog site. Right now, we are at the point where we are using the Django ORM to interact with the database. I was following every step and i hit a wall at queryset, where the item name isn't showing up, and this was after i did this: def __str__(self): return self.title the output that i get when i type Narticle.objects.all() is queryset Narticle:Narticle object(1) instead of <queryset [<Narticle: 'hello world']> my steps are below this model: my model for narticle is from django.db import models class Narticle(models.Model): title= models.CharField(max_length=100) slug= models.SlugField() body= models.TextField(max_length= 100) date=models.DateTimeField(auto_now_add= True) i entered the following on the command line: from narticle.model import Narticle i typed Narticle and i got <class 'narticle.models.Narticle' > i then entered the following Narticle.objects.all() and i got <queryset[]> i then typed narticle= Narticle() then narticle which gave me Narticle: Narticle object(none) i then typed narticle.title = "hello world" which was followed by Narticle.objects.all() Which gave me < queryset [<Narticle: Nartice object (1)>]> i typed narticle.save() i then exited command line,and then in models.py of narticle i … -
Obtain username in a form
I am trying to obtain the logged user name in a form, but I am having the following error message: AttributeError: 'NoneType' object has no attribute 'user' What am I doing wrong? I guess there is something wrong with self.request = kwargs.pop('request', None) self.user_name =self.request.user.username Here is my form class MyForm(forms.Form): List = forms.ChoiceField(choices=()) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.user_name =self.request.user.username super(MyForm, self).__init__(*args, **kwargs) self.fields['List'].choices = self.list_people() def list_people(self): u = User.objects.get(username=self.user_name).accesslevel.segmentation.split(',') v=(('---------','---------'),) for l in u: v=v+((l.lstrip(),l.lstrip()),) return v Views.py def list_table(request): form = ApartmentForm(request.POST,request=request) .... -
Django Model Design, Forms and Formsets, Am I doing it correctly?
I have taken it upon myself to bring my django understanding to a higher level. In doing so, I am happily running into new problems to work out. One thing that I cannot get a good feel of though, purely by research, is my model design. Take for example this model: """ Service Reports Service Report Form ADMIN • Reason for Report • Actions Taken """ class ServiceReportModel(models.Model): report_number = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(customers_models.SiteModel, on_delete=models.PROTECT, related_name='reports') request_number = models.ForeignKey(ServiceRequestModel, on_delete=models.PROTECT, null=True, blank=True, related_name='s_report_number' ) reported_by = models.ForeignKey( main_models.MyUser, related_name='reporter') reported_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey( main_models.MyUser, blank=True, null=True, related_name='updater') updated_date = models.DateTimeField(auto_now=True) equipment = models.ForeignKey( customers_models.EquipmentModel, on_delete=models.PROTECT) report_reason = models.CharField(max_length=255, null=True) actions_taken = models.TextField(null=False, blank=False) recommendations = models.TextField(null=True, blank=True) def get_absolute_url(self): return reverse('service-report', kwargs={'pk': self.pk}) def __str__(self): return '%s - %s, %s' % (self.site.company, self.reported_date.strftime('%d %B %Y'), self.equipment.name ) class Meta: ordering = ['reported_date'] verbose_name = 'Service Report' verbose_name_plural = 'Service Reports' class ReportPunchesModel(models.Model): report = models.ForeignKey(ServiceReportModel) time_in = models.DateTimeField(blank=True, null=True) time_out = models.DateTimeField(blank=True, null=True) Now, I have to ask myself, did I go crazy with foreignkeys here? My thought process when designing the model was pretty straight forward. If my model has x-item, and x-item is … -
Django Rest Framework create - refer to foregin key
So im trying to create a view with the Django rest framework. i have the serializer done to refer to the foreign keys. But i believe i have to pass into to view a user object? Take a simple example of book table. Each person has many books. So if this was a normal sql insert i would place the id of into the book table so the book table would be something like user:1 title:Learn Django price: 15 user table: id:1 name:john smith The Django View class is looking like this class BookViewSet(CreateAPIView): serializer_class = BookSerializer How can i get it so that when a user can pass in a user id, a title and price and insert into the db Thanks -
Django Quiz App, Measure Time Per View Render
I am using the quiz app which you can see here: https://github.com/tomwalker/django_quiz Basically I want to measure the time it takes to answer a question in the quiz. Now how would I do that ? Would this be possible to do in Django ? -
Ignore database file on remote git repo
I have a sqlite database file in my git repo. I make changes on it locally just for testing but I don't want it to get committed. But I want a copy of the database file on the remote bare repo (I want this file ignored by git). adding the file to .gitignore will delete it from the remote repo, I don't want that. So basically, I want the file both on local and remote repo but both should be ignored. Is it possible to git rm --cached db.sqlite3 on my remote bare repository? I have done this on my local repo but it deleted the file on remote repo and that's what I don't want. -
Hosting for Django CMS and python for site that can send orders with file attachments
Need to develop site for client that can send orders with file attachments. Looking to build it with django cms and python. What are my options for hosting that's not too expensive and supports these requirements and technologies? Would pythonanywhere work? What are other options? Not sure. -
Django 2.0 - Conditional Max() on QuerySet
I have Employee model and Invitation model. Every Employee has an one-to-many relation with Invitation. Invitation has a send_date and active column. What I want: I want to get Employee QuerySet with annotated highest send_date of related active only Invitations. What I Tried: query = Employee.objects.annotate( invitation_max_send_date=Max( Case( When( invitations__active=True, then=F('invitations__send_date') ), When( invitations__active=False, then=None ), output_field=models.DateField() ) ), ) Result: invitation_max_send_date of each Employee contains the highest send_date of related invitations, regardless if are active or not. Any ideas? -
Using annotate instead of model property
The annotate function is very useful to define computed fields for each row of the table. Model properties can also be used for defining computed fields, but are limited (can not be used for sorting, for instance). Can a model property be completely replaced by an annotated field? When is it adequate to use each? -
Django TypeError using TextField bounding the form
I want to create a simple wiki page, which is comprised of several entries. But have an error TypeError at /addentry __init__() got an unexpected keyword argument 'title' The main thing here is entry model. Here is part of my models.py: class wikies(models.Model): num = models.CharField(max_length=15) title = models.CharField(max_length=150) text = models.TextField() And here is part of my forms.py: class entryform(ModelForm): class Meta: model = wikies fields = ['num', 'title', 'text'] Part of my template: <form action="{% url 'addentry' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p> {{entryform.num}} </p> <p> {{entryform.title}} </p> <p> {{entryform.text}}</p> <p><input type="submit" value="Add Entry" /></p> This is part of my views.py, where I catch the error: def addentry(request): if request.method =='POST': form = entryform(num = request.POST['num'], title = request.POST['title'], text = request.POST['text'] ) I want to bound the form with values I just get, but have the following error: TypeError at /addentry init() got an unexpected keyword argument 'title' Here are POST values: num '1.2.3' text 'Water is very important resource.' title 'Importance of water' I've read the docs, I've searched through StackOverflow, but I have no idea what to do. Will appreciate any help. -
AttributeError: type object 'Mock' has no attribute 'MagicMock', testing django file field [on hold]
I'm trying to test a django model that contains a file field. I am using mock in order to create the file for testing. I need to use Mock.MagicMock so the I don't get the TypeError: 'Mock' object is not iterable error from django when it saves the file. from django.core.files import File as django_file from django.test import TestCase import lorem from unittest.mock import Mock from .models import ProfileUser class ProfileModelTests(TestCase): @classmethod def setUpTestData(cls): mock_resume = Mock.MagicMock(spec=django_file, name='resume') mock_resume.name = 'resume.pdf' for i in range(5): ProfileUser.objects.create( name='test name%s' % i, title='title', cell_phone='(555)555-5555', office_phone='(555)555-5555', email='testuser%s@test.com' % i, about_me=lorem.paragraph, resume=mock_resume, facebook_profile_link='https://www.facebook.com/testuser%s' % i, twitter_profile_link='https://www.twitter.com/testuser%s' % i, linkedin_profile_link='https://www.linkedin.com/testuser%s' % i, github_profile_link='https://www.github.com/testuser%s' % i, google_plus_profile_link='https://plus.google.com/+testuser%s' % i, stackoverflow_profile_link='https://stackoverflow.com/users/testuser%s' % i ) def test_model_creation(self): all_profiles = ProfileUser.objects.all() self.assertEqual(len(all_profiles), 5) -
Apps not loaded yet when using actstream django
So i'm trying to create an application for user interaction with stream_django. So far everything was going well until I got error: 'User model not registered. Please register model with actstream.registry'. So after searching for some time, I modified my apps.py to be like this: The project is called reviews # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reviews.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "reviews.settings" django.setup() from django.apps import AppConfig from django.contrib.auth.models import User class MyappConfig(AppConfig): name = 'myapp' def ready(self): from actstream import registry registry.register(User,self.get_model('Post'),self.get_model('UserProfile')) But now I'm getting error: 'AppRegistryNotReady("Apps aren't loaded yet")' I'm not sure what to do anymore, any help is appreciated. -
Django: Issue with cross-app ModelChoiceField returning an integrity error
Good afternoon -- I'm still feeling myself around Python and Django and I'm running into a question that I can't seem to figure out. I've created a Project with multiple apps in it and I'm trying to centralize repeated data. What I'm trying to is have a county that is in the Clients app work in the same capacity as what's in the Calllog app. Here's what I have: clients/models.py class County (models.Model): county = models.AutoField(primary_key=True) county_name = models.CharField(max_length=200, null=False) state = models.ForeignKey(State, default=26) avenues_support = models.BooleanField(default=0) def __str__(self): return self.county_name calllog/models.py from clients.models import County class CallLog(models.Model): county_of_incident = models.ForeignKey(County, null=False, related_name='call_log_county_of_incident') calllog/forms.py from clients.models import County class Call_Log_Create(forms.ModelForm): county_of_incident = forms.ModelChoiceField(queryset=County.objects.filter(avenues_support=1), required=True) In the form, the dropdown box for County of Incident populates with the counties in the database. After selecting the county and hitting submit, I get an IntegrityError (1048, "Column 'county_of_incident_id' cannot be null") I'm not sure what's causing this issue and have been stuck on it for a couple of days. Any help would be appreciated. -
Developing Django with Docker
I am trying to create myself a development environment for a Django web app using Docker. My question is how should I set it up for development? I've created a Dockerfile which uses the Django dev server and db, is that good? Or should I use separate container with dedicated web and db servers? How should I create new migrations? Let's say I'm mounting the code into the container using -v, changes to models requires creating new migrations, so, should I make the mount writable and use create migrations from within the container? What other options are there? I'm thinking about adding a RUN instruction to the Dockerfile which will apply the migrations in order to use cache when the migrations haven't changed. Is this a good practice? -
Language selection from dropdown
I could use this code: mytemplate.html: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} <option value='it' {% if 'it' == LANGUAGE_CODE %} selected{% endif %}> Italiano</option> <option value='en' {% if 'en' == LANGUAGE_CODE %} selected{% endif %}> English</option> </select> <input type="submit" value="Go" /> </form> It works translating my page without changing the url. But I don't like how it look, I prefer a dropdown menù (it look better in my toolbar, also I can add images). I tried many things until I found this: <a class='dropdown-toggle' data-toggle='dropdown' role='button' aria-expanded='false'>Lingua<span class='caret'></span></a> <ul class='dropdown-menu' role='menu'> <li><a href="/it{{ request.get_full_path }}" class='language' lang='it'><img width='16' height='12' src="{% static 'icons/italian.png' %}" alt='Italiano' /> Italiano</a></li> <li><a href="/en{{ request.get_full_path }}" class='language' lang='en'><img width='16' height='12' src="{% static 'icons/english.png' %}" alt='English' /> English</a></li> </ul> but this add a prefix to my url (it/ or en/) and my url haven't prefix, so it gives page not found 404. Is there a way to use the standard django view with a dropdown menù? -
Unsupported media type Django API
I'm new T Django and my project is in REST when i'm using postman to check URLs it's make this error "detail": "Unsupported media type \"multipart/form-data; boundary=----WebKitFormBoundaryAU1ShXHTHrfcQr61\" in request." please help me to undrestand what is the problem and say in details. -
If foreign key does not exist create it. Django framework
Imagine you have a table A which has a foreign key pointing to other table B, but in that B table there is no such key. What should you do if you want to achieve this functionality - add the key in the table B if the key does not exist? Are there any serious concerns about performance issues?