Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically load "subtemplate" within template in django
New to web dev. Is there a way to dynamically load a django template within another template (based on user actions) and still be able to use the context object from the view that loaded the overall template? Eg. I have a template that loads a series of (semantic UI) cards. Would like to be able to click on a card and (without "switching screens") load a sub-template to replace the set of cards that remembers the value of some of the text on the card (or maybe the card's name= attribute) (which is based on some context variables brought in by the view that loaded the template) which would then be used in the newly loaded subtempate. ** If there a more django-ish way to do this kind of behavior, please let me know. -
best approach for send data to manytomany field in django
I'm noob python developer and I'm wonder what is the best approach to send data to my django UpdateView I have this form and I'm using jstree to create a nested many to many form but I don't know if I send the data from this jstree using ajax or if I have another way that I can do it without send data using ajax, I wonder if I can hide my many to many field and when I select the node from my jstree I redirect it to my field form that was hide, I don't know if it is possible. thanks in advance. -
Complex django query including one-to-one models
I have an user object which has a one-to-relationship with a profile object. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=False, unique=True, max_length=255) is_online = models.BooleanField(default=False) class UserProfile(models.Model): user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE, ) badge = models.ImageField(upload_to='media/badges/', null=True) reputation = models.IntegerField(default=0) status = models.CharField(max_length=255, null=True, blank=True) Now I'm trying to fetch all users who're online and order them by reputation(which is in the profile object) and exclude the ones that have a reputation less than 200. This is my query which doesn't work, User.objects.filter(is_online=True).order_by('reputation').exclude('reputation' < 200) Can someone help with the correct format of this query? -
query foreign key table for list view in django
I am very new to django. I have a django installation and am trying to create a UI in django for a few of the database tables. In my database there are two tables - Articles and Author. The Articles table has a foreign key to Author table with field name as author_id. I have managed to create a ListView class that lists articles. The code is like this: from .models import Article class ArticleListView(ListView): template_name = "article.html" context_object_name = 'articles' paginate_by = 25 def get_queryset(self): queryset = Article.objects.all().order_by('-created_at') return queryset Then in the view I loop the Article queryset and prints its attributes, and this works fine. However I am not sure how to query the corresponding Author table in order to get the author name and details. Can anyone please help me understand how this can be done? I read a lot of documentation/tutorials about this but I am unable to wrap my head around how to do this. Any help is very much appreciated. Please note: The Article class was written by earlier django programmer. -
How to fill fields base on another field in django
I have one template with 2 forms: Entregaform and EnderecoEntregaForm. When Entrega is equal "Entregar na Empresa" I have to fill the fields from EnderecoEntregaForm. When Entrega is equal to "Retirar no Cartório(Centro/Barra) - Gratuito, I don´t have to fill the fields from EnderecoEntregaForm. How can i do that in django ? -
Serve local Django app in HTML File
I want to see how some changes in my Django app will interact with an HTML page, but I don't want to deploy them until I test. Here's my naive attempt, which doesn't render anything inside the iframe, even though that link works in its own tab. HTML file: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="stylesheet.css"> <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"> </script> <div class="frame"> <img id="logo" src="images/Logo.png"/> <iframe id="primaryVideo" src="http://127.0.0.1:8000/app/1/"> <p> Your browser does not support iframes. </p> </iframe> </body> </html> -
Django app cannot share name of folder?
Something I've had a really bad problem with in Django 2.0 is that I'll go to create an app but I want it in the folder above the project. I'm also using PyCharm 2017.1 so not sure if that's causing issues but I tend to get the same error messages if I do things in the cmd prompt too. My working folder is called 'DjangoTest' and is empty. I'll walk you through all the steps and include the command prompt output stream. Start a project: django-admin startproject mysite Result: DjangoTest/ |-----> mysite/ |-----> mysite/ | |-----> __init__.py | |-----> settings.py | |-----> urls.py | |-----> wsgi.py |-----> manage.py Navigate into the 'mysite' subdirectory: cd mysite Create a subdirectory to hold the app files: <I created a folder named 'myapp' in the current directory>: Folder structure now: DjangoTest/ |-----> mysite/ |-----> myapp/ | |-----> mysite/ | |-----> __init__.py | |-----> settings.py | |-----> urls.py | |-----> wsgi.py |-----> manage.py Create the app python manage.py startapp myapp ./myapp/ CommandError: 'myapp' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. It seems like Django doesn't want to create the app because … -
How to specify date range in django
I am currently struggling to get a part of my code working. I'm trying to build three sections on a page: Each entity in my db has a "chunk arrival time" and I want to group them into three areas: "Current timers", entities where chunk_arrival_time was in the last 48 hours "Future timers", entities where chunk_arrival_time is in the future "Past timers", entities where chunk_arrival_time was longer than 48 hours ago. currently I have this: render_items = {'moonextractions': base_query.all(), 'current_timers': base_query.filter( chunk_arrival_time__lte = timezone.now() + timezone.timedelta(days=-1)), 'future_timers': base_query.filter( chunk_arrival_time__gte=timezone.now()), 'past_timers': base_query.filter( chunk_arrival_time__lt=timezone.now()).order_by('-chunk_arrival_time')} The top block, "current timers" is the one i'm struggling with. How do I need to format this so that it sorts things as described above? -
How to set a specific queryset on a ObjectSerializerModel
I'm developing a web system using Django 1.11 and the current version of Django Rest Framework which is 3.8.2. I'm having a problem while serving a JSON of my models in this project. I need to pass a JSON that contains a specific attribute. I'm gonna exemplify my serializers.py to make an easier understanding of my problem. class LikertSerializerModel(serializers.ModelSerializer): class Meta: model = Likert fields = ('id', 'escala') class RespostaSerializerModel(serializers.ModelSerializer): likerts = LikertSerializerModel(many = True, read_only = True) class Meta: model = Resposta fields = ('id', 'resposta','tipo', 'foto', 'pergunta', 'qtd_escolhida', 'classificacao_escala', 'data', 'likerts') class PerguntaSerializerModel(serializers.ModelSerializer): respostas = RespostaSerializerModel(read_only=True ,many=True) class Meta: model = Pergunta fields = ('id', 'pergunta', 'tipo_questao', 'questionario', 'respondida', 'data_inicial', 'data_final', 'obrigatoria', 'outros', 'ordem', 'qtd_max_caracteres', 'respostas') class QuestionarioSerializerModel(serializers.ModelSerializer): entrevistadores = UsuarioSerializer(many = True, read_only = True) sub_administrador = UsuarioSerializer(read_only= True) perguntas = PerguntaSerializerModel(many = True, read_only = True) class Meta: model = Questionario fields = ('id', 'titulo', 'descricao', 'data', 'duracao', 'localizacao', 'sub_administrador', 'entrevistadores', 'perguntas') THE PROBLEM: See, in the PerguntaSerializerModel I have this field "respostas". And the thing is, I only want to pass to that Pergunta Object, Resposta Objects that have a "tipo" attribute with a value of "alt" and are linked with that Pergunta Object. PS: … -
In Django CBV, get_context_data() is called twice. How can I make it called only once?
Before explaining the detail, here is my codes in views.py views.py class StoreListView(ListView): model = Store template_name = 'boutique/index.html' paginate_by = 10 queryset = Store.objects.filter(status='active').order_by('-popularity') def __init__(self): self.temp = None def get_template_names(self): if self.request.is_ajax(): return ['boutique/slider_index.html'] return ['boutique/index.html'] def post(self, request, *args, **kwargs): tab_keyword = request.POST.get('tab_keyword') if self.request.is_ajax(): if tab_keyword == '#': tab_keyword = None else: tab_keyword = None self.temp = tab_keyword print('-----post-----') print(self.temp) print('-----post-----') return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['keyword'] = self.temp print('-----get_context_data-----') print(context['keyword']) print('-----get_context_data-----') return context I'm currently having an issue that get_context_data() is called twice. What I'm trying to do here is I use Ajax to send data in a javascript variable to to Django views. When I use Ajax in the template level, it calls post(). In the console, it prints out the following: -----post----- #Modest -----post----- -----get_context_data----- None -----get_context_data----- -----get_context_data----- #Modest -----get_context_data----- Like you see it, get_context_data() prints things twice and I don't know why. Does anyone have any idea about this? -
Django | how can I let users edit thier own qustions
Well let's say that some user asked a question like me right now, how can I show only the question creator the option to edit and how to let him edit -
jqXHR doesn't give me XMLHttpRequest object
Hi I all i am building an application and currently using jquery ajax call. My ajax call looks like as following: $.ajax({ type: 'POST', xhr:function(){ var _xhr = new window.XMLHttpRequest() _xhr.upload.addEventListener('progress',function(event){ progressHandler(event); },false); console.log(_xhr) // this give me the exact XMLHttpRequest return _xhr }, url: window.location.href, data: formdata, processData:false, contentType:false, success:function(data,textstatus,jqXHR){ console.log(jqXHR) // This give me a normal object }, error:function(jqXHR,errortype,errorobj){ } }); The success function return me a normal object instead of XMLHttpRequest, but the xhr function return me the exact output which i need. Can anyone help me how to override the success jqXHR with the xhr function return value -
Forbidden (403) CSRF verification failed. Request aborted. Django + AngularJS
I'm running a Django v1.10.8 project. I have a form that's processed with AngularJS v1.5.6. I've put the project on a remote server that uses SSL, runs on HTTPS. When I try submitting my custom login form, I get this error: Forbidden (403) CSRF verification failed. Request aborted.. login_register.html login form here: <div ng-app="app" ng-controller="Ctrl"> <form method="post" name="loginForm" ng-submit="login()"> <fieldset ng-disabled="submittingForm"> <p> <input id="{{ login_form.username.id_for_label }}" type="email" name="{{ login_form.username.html_name }}" placeholder="Email" ng-model="login.email" required> </p> <p> <input class="form-control" id="{{ login_form.password.id_for_label }}" name="{{ login_form.password.html_name }}" placeholder="{% trans 'Password (8+ characters)' %}" type="[[[ login.showPW ? 'text' : 'password' ]]]" ng-minlength="{{ min_pw_length }}" ng-maxlength="{{ max_pw_length }}" ng-model="login.pw" required > </p> <button class="btn btn-primary" type="submit" ng-disabled="!login.email || !login.pw">{% trans "Log in" %}</button> </fieldset> </form> </div> login-register.js: var app= angular.module("app",[]); app.config(function($interpolateProvider, $httpProvider){ $interpolateProvider.startSymbol("[[["); $interpolateProvider.endSymbol("]]]"); $httpProvider.defaults.xsrfCookieName= "csrftoken"; $httpProvider.defaults.xsrfHeaderName= "X-CSRFToken"; }); app.controller("Ctrl", function($scope, $http, $window){ $scope.loginError= ''; $scope.login= function(){ $scope.submittingForm= true; $scope.loginError= ''; var formData= { "username": $scope.login.email, "password": $scope.login.pw }; $http.post( "login", JSON.stringify(formData) ).success(function(response){ if (response.success === false){ $scope.loginError= response.err_msg; $scope.submittingForm=false; return; } $window.location.href= GLOBAL_paths.home; }); }; }); Here's an excerpt my local_settings.py: SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = "DENY" SECURE_HSTS_SECONDS = 60 SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True … -
Handle parallel request in Django
I have created an API in DRF which accepts POST request with some data, It checks a value in Student table and creates data in DB if value is False and set the value to True(after creating the data). But when someone hits the API multiple time in parallel(let 20 requests in parallel), It creates multiple objects for user (Not 20 but more than 1) because multiple requests read the same value at same time and create the data. I want to process only one API call on same endpoint and same IP at a time. How can I achieve it? -
Attempting to connect to LDAP using django-python3-ldap but the target machine is actively refusing it
I am working on a django app and attempting to use django_python3_ldap to connect to my company's LDAP and AD. I followed the docs basic settings in my settings.py but when I try doing python manage.py ldap_sync_users I get this error LDAP connect failed: ('unable to open socket', [(datetime.datetime(2018, 5, 25, 12, 25, 36, 77877), <class 'ldap3.core.exceptions.LDAPSocketOpenError'>, LDAPSocketOpenError('socket connection error while opening: [WinError 10061] No connection could be made bec ause the target machine actively refused it',), ('::1', 389, 0, 0)), (datetime.datetime(2018, 5, 25, 12, 25, 37, 78809), <class 'ldap3.core.exceptions.LDAPSocketOpenError'>, LDAPSocketOpenError('socket connection error while opening: [WinError 10061] No connect ion could be made because the target machine actively refused it',), ('127.0.0.1', 389))]) CommandError: Could not connect to LDAP server Here is my settings.py file import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, NestedActiveDirectoryGroupType # Baseline configuration. AUTH_LDAP_SERVER_URI = "ldap://***.**.***.**" LDAP_AUTH_CONNECTION_USERNAME = 'usr@ab.com' LDAP_AUTH_CONNECTION_PASSWORD = '*******' # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "ou=people,dc=example,dc=com" # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = "user" # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) DEBUG = True LDAP_AUTH_USE_TLS = False # User model fields mapped to … -
how to display checkboxes depending on loaded entry of a model
I have a model named Publication that has several fields among them a field called tags, and I'm using for it django-taggit. I have a page that I display in it some entries of Publication model, I want to display (as checkboxes) on sidebar tags that used only in these entries. This is a portion of my code: class TagsForm(forms.ModelForm): tags = forms.ModelMultipleChoiceField( queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Publication fields = ['tags'] def __init__(self, *args, **kwargs): super(TagsForm, self).__init__(*args, **kwargs) if self.instance: entries = Tag.objects.all() self.fields['tags'].queryset = entries -
How to add constraint on model/serializers in django
I want to create a model to store information when a person's face shows up. The model is as below: class Face(models.Model):person = models.ForeignKey(Person, on_delete=models.CASCADE) class Log(models.Model):host=models.ForeignKey(Person, on_delete=models.CASCADE) face = models.ForeignKey(Face, on_delete=models.CASCADE) When I create a log, it can create a wrong one with a person having the face that does not belong to him. How can I fix that? Or how to put constraints in the model/serializer that let the face only link to the Face of the host -
Django/Jquery GET Request to download csv file
I am searching for python/jquery related answer but I havn't been lucky so far! I am trying to download csv file sent by a server via AJAX GET call. I am able to download it successfully via blocking-get request but I want to achive the same via ajax. Python/Django View header = None rows = [] for student in students: if not header: header = get_header() rows.append(header) rows.append([student.id, student.name, student.marks]) buf = StringIO() writer = csv.writer(buf) for row in rows: writer.writerow(row) response = HttpResponse(buf.getvalue(), content_type='text/csv') response['Content-Disposition'] = 'attachment' return response AJAX GET Request <script> $(document).ready(function () { $('#download-grades').on('click', function (event) { event.preventDefault(); var grades_csv_url = $(event.target).data().url $.ajax({ url: grades_csv_url, type: 'GET', // dataType: 'text/csv; charset=utf-8', success: function (response, status, xhr) { console.log('-') }, error: function (jqXHR) { console.log(jqXHR.responseText); // the response is always received in error not in success. } }); }); }) </script> Whats Next? I want to start downloading the file when the csv response is received. -
Django Inline form validation ignored partly filled form
I have got the code from https://github.com/adandan01/mybook, the code is working fine, even when I have updated it to Django 2. It's very simple project for adding a person in a form, and his/her relatives in the inline form. Everything works but when I add a relative name and forget to add his relationship, and submitted the form, unfortunately, that record will not pass the validation but will give no error messages as well. Django will ignore the entire record. For example, the record for Hawra in the image, will not be saved and Django will remove it. For this simple App there are only two fields to be filled (name and relationship), but I'm working on app with 8 fields, and it will be difficult to lose the data. is there any way to make django do the validation in the formset/subform as long as any fields have data and will ask the user to fill all required fields? models.py: class Profile(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('profile-update', kwargs={'pk': self.pk}) def __unicode__(self): return "%s %s" % (self.first_name, self.last_name) class FamilyMember(models.Model): profile = models.ForeignKey(Profile, on_delete=models.PROTECT) name = models.CharField(max_length=100) relationship = models.CharField(max_length=100) form.py class … -
Complex Django permissions
I'm working with the following models in a django project. The effective relationship is that a District can have multiple Schools, a School can have multiple Students, and a Student may have multiple Cases. class District(models.Model): name = models.CharField(max_length=50) ... class Meta: permissions = ( ('view_district', 'Can view district') ... ) class School(models.Model): name = models.CharField(max_length=50) ... district = models.ForeignKey( District, on_delete=models.PROTECT, related_name='schools', related_query_name='school', ) class Meta: permissions = ( ('view_school', 'Can view school') ... ) class Student(models.Model): name = models.CharField(max_length=50) ... school = models.ForeignKey( School, on_delete=models.PROTECT, related_name='students', related_query_name='student', ) class Meta: permissions = ( ('view_student', 'Can view student') ... ) class Case(models.Model): name = models.CharField(max_length=50) ... student = models.ForeignKey( Student, on_delete=models.PROTECT related_name='cases', related_query_name='case', ) class Meta: permissions = ( ('view_case', 'Can view case') ... ) A user may be assigned: a specific case a specific student (which would include all cases for that student) a specific school (which would include all students for that school, and thus all cases for the students at that school) a specific district (which would include all schools for that district, all students that attend those schools within that district, and all cases for students that attend those schools within that district) Users (other … -
Django + Activemq and long running connections in the Webserver
I have been using stomp.py and stompest for years now to communicate with activemq to great effect, but this has mostly been with standalone python Daemons. I would like to use these two libraries from the webserver to communicate with the backend, but I am having trouble finding out how to do this without creating a new connection every request. Is there a standard approach to safely handling TCP connections in the webserver? In other languages, some sort of global object at that level would be used for connection pooling. -
Adding field to form only if the model field is blank
I want to have a form that populates fields to edit only if they are left blank. For example: class UserEditConcert(forms.ModelForm): class Meta: model = models.Concert fields = ( 'genres', ) if not model.time: fields += ('time',) if model.age == "Unknown": fields += ('age',) Neither of my if statements are working. Is my syntax wrong or is this not working for some other reason? -
Django/Bootstrap template rendring
I'm currently coding a website using Django and Bootstrap. I created the templates and models first, and now, I'm implementing the controllers. All is not implemented yet, but I needed some help on this. I was wondering how to render a Django authentication form with the Boostrap grid system. I'm using Boostrap 4 and Django 2.0.4. My older form was like this : <div class="jumbotron"> <form class="form-horizontal" method="post" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> <div class="col-lg-4 offset-lg-4"> <label class="control-label" for="usernameInput">{{ form.username.label_tag }}</label> <input id="usernameInput" type="text" name="{{ form.field.html_name }}" value="{{ form.username }}" class="form-control" placeholder="Username"> </div> </div> <div class="form-group"> <div class="col-lg-4 offset-lg-4"> <label class="control-label" for="passwordInput">{{ form.password.label_tag }}</label> <input id="passwordInput" type="password" name="{{ form.field.html_name }}" value="{{ form.field.value }}" class="form-control" placeholder="Password"> </div> </div> <div class="container" id="btn_login"> <button type="submit" class="btn btn-primary btn-md" value="login" role="button">Log in</button> <input type="hidden" name="next" value="{{ next }}"/> </div> </form> <span class="container" id="forgotten_password"> <a href="">Forgot your password ?</a> </span> </div> And here is the new one : <div class="jumbotron"> {% load widget_tweaks %} <form class="form-horizontal" method="post" action="{% url 'login' %}"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ … -
How To Add Session Variables with Built-In login view
I used the built-in login view that django makes but now I don't know how to set sessions when a user logs in. I was thinking of redirecting a user to a new view that would add these session variables but I don't see that as an ideal fix. Another question I have is: Can I use these session variables in my templates? If not, how would I get that data to the templates? -
Angular resetting csrf token
I'm using Angular 6 and having a hard time integrating Django's csrf with Angular's. I found in this thread that Django changes the token on login which, since I can both register and login using post requests with the same new session but not post anything after login seems to make sense. The question becomes how I go about resetting the csrf token on login. The way the csrf is handled now in my Angular app is shown in the below code for my app module: import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http' import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { RegisterComponent } from './register/register.component'; import { LoginComponent } from './login/login.component'; import { AlertComponent } from './_directives/alert.component'; import { ProfileComponent } from './profile/profile.component'; import { AuthGuardService } from './_guards/auth-guard.service'; import { AlertService } from './_services/alert.service'; import { AuthService } from './_services/auth.service'; import { UserService } from './_services/User.service'; @NgModule({ declarations: [ AppComponent, RegisterComponent, LoginComponent, AlertComponent, ProfileComponent, ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, AppRoutingModule, HttpClientModule, HttpModule ], providers: [ { …