Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin ForeignKey field widget options and inconsistent defaults
I have a model that has foreign keys, and in the admin those FKs render as drop-down lists. However, some of them show buttons for 'add', 'edit', and 'delete' of the elements in the related table, and others do not. I cannot figure out what is different between the fields such that some render one way and some render a different way. My ideal situation is that those buttons do not render for any foreign keys, that editing one model is restricted to just changes on that entity itself. I see that Django ultimately selects the RelatedFieldWidgetWrapper for these fields. I can set can_add_related, can_change_related, and can_delete_related on this widget, but I don't see how to easily pass these as options for these fields so that they are all consistent. How do I manage turning these options on and off in the admin? -
Finding difference of two time objects in django
I want to know about the best way to find the difference between two time objects in Django. I want to know whether the time of a particular object is in a difference of 4 hours or not. I have my models.py as class Task(models.Model): time = models.TimeField() In the shell, I tried something like from django.utils.timzone import datetime, timedelta obj_time = Task.objects.first().time obj_time - datetime.now().time() < timedelta(hours=4) But I get the following error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' How should I go about solving this? -
Custom LoginView in Django 2
I am trying to customise the authentication and view in Django 2 but the problem is that if the user is already authenticated the login form is still shown and it is not redirected to the appropriate URL. To get over this I have done the following: class CustomLoginView(LoginView): form_class = LoginForm template_name = 'login.html' def get_initial(self): if self.request.user.is_authenticated and self.request.user.is_staff and has_2fa(self.request.user): return HttpResponseRedirect(reverse('{}'.format(self.request.GET.get('next', 'portal_home')))) else: return self.initial.copy() def form_valid(self, form): if self.request.user.is_staff and not has_2fa(self.request.user): logger.info('is staff but does not have 2FA, redirecting to Authy account creator') auth_login(self.request, form.get_user()) return redirect('2fa_register') return HttpResponseRedirect(self.get_success_url()) But the HttpResponseRedirect in get_initial() does not redirect to the /portal/ page. I have also tried redirect('portal_home') but nothing happens or do I need to write a custom dispatch? Any help would be much appreciated. -
Heroku free dyno working hours are not working properly
I have only one Django app with PostgreSQL running on heroku and I have 801.59 free dyno hours (80.16%) used this month. Can anyone explain me how it is possible? 801.59:24=33,39 Today is the nineteenth of December, so where 14 days disappeared? -
Django TimePicker Does Not Work, How To Integrate TimePicker
I am trying to get TimePicker to work for my Time selection in the form. I tried to do this based on this very old blog http://bradmontgomery.blogspot.my/2008/11/selecttimewidget-custom-django-widget.html In forms.py from django.forms.extras.widget import SelectTimeWidget ... class CompanyWorkingHoursSettingsForm(forms.ModelForm): mon_start = forms.TimeField(widget=SelectTimeWidget()) mon_end = forms.TimeField() tue_start = forms.TimeField() tue_end = forms.TimeField() class Meta: model = Workinghours fields = ("mon_start","mon_end","tue_start","tue_end") However it cause this problem: from django.forms.extras.widget import SelectTimeWidget ModuleNotFoundError: No module named 'django.forms.extras.widget' Im using Django==1.11.7. So Im not sure whats the best way to do TimePicker for the TimeField ? Do show me the right way to implement TimePicker (in bootstrap) for TimeField. -
Django: Dynamically add CharField to form
I am working on a voting app in Django and I want to be able to add new choices with an "add" button. I currently have this: https://i.stack.imgur.com/kcpyR.png View: def newPollView(request): if request.method == 'GET': form = submitPollForm() else: form = submitPollForm(request.POST, extra=request.POST.get('extra_field_count')) # Bind data from request.POST into a PostForm if form.is_valid(): usedChoices = [] question = form.cleaned_data['question'] choice_1 = form.cleaned_data['choice_1'] q = Question.objects.create(question_text=question, pub_date=timezone.now()) c1 = q.choice_set.create(choice_text=choice_1, votes=0) usedChoices.append(choice_1) choiceList = [choice for choice in form.cleaned_data if choice is not 'question' and choice is not 'choice_1' and choice is not 'extra_field_count'] for choiceName in choiceList: c = form.cleaned_data[choiceName] if c != "" and c not in usedChoices: usedChoices.append(c) q.choice_set.create(choice_text = c,votes=0) return HttpResponseRedirect(reverse('vote:index')) return render(request, 'vote/newPoll.html', {'form': form,}) Forms: class submitPollForm(forms.Form): question = forms.CharField(max_length=250) choice_1 = forms.CharField(max_length=250,required=True) extra_field_count = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): extra_fields = kwargs.pop('extra', 0) super(submitPollForm, self).__init__(*args, **kwargs) self.fields['extra_field_count'].initial = extra_fields print(extra_fields) for index in range(2,int(extra_fields)+4): self.fields['choice_{index}'.format(index=index)] = forms.CharField(max_length=250,required=False) Template: <script> function showMessage(){ form_count = Number($("[name=extra_field_count]").val()); window.alert(form_count); form_count ++; element = $('<input type="text"/>'); element.attr('name', 'choice_' + form_count); $("#forms").append(element); $("[name=choice_count]").val(form_count); } </script> <form action="/vote/newPoll.html" method='post'> {% csrf_token %} <h1>Create a new Poll</h1> <label>Enter name of the poll:</label> {{ form.as_p }} <Button type = 'button' onclick="showMessage()">add another</Button> … -
Why can't I see running django migration saves in postgress
I'm migrating over from mongo to postgres, however I can't see the intermediate results in the postgres table. Why is this the case? I know it works because I've tested the migrations locally on the smaller database, but with a larger testing database it takes ages and I see nothing. -
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.