Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py startapp is not creating migrations directory
python manage.py startapp polls. I tried this command but it creates only python files and it does not create the migrations directory. And the django version that i am using is 1.6.11 here is the directory structure of polls directory created by above command __init__.py admin.py models.py test.py urls.py views.py -
Django create zip file and download/upload "correctly"
Which parts of Django should handle file download, upload and manipulation functionality? I have a Django app. I want implement the following functionality in the admin interface. Download Function: Take some model objects and write them to a file (json, pickle, shelve, whatever) Zip the file created in step 1, along with some image files The user downloads the zip file and temp files are deleted Upload Function: User upload the file described above The file is unzipped, the image files are written to the disk and new objects are created to load the data into the database Which parts of the my Django app are the "correct" parts for me to implement this functionality into? For example, I am guessing that it should not all go into in the view? -
should I use ArrayField or Foreignkey for tags
I am trying to add tags to a model for a postgres db in django and I found two solutions: using foreign keys: class Post(models.Model): tags = models.ManyToManyField('tags') ... class Tag(models.Model): name = models.CharField(max_length=140) using array field: from django.contrib.postgres.fields import ArrayField class Post(models.Model): tags = ArrayField(models.CharField(max_length=140) ... assuming that I don't care about supporting other databases in my code, what is a recommended solution? -
ValueError: The given username must be set
I'm trying register a user in my project, but when I try to do it I get next error: ValueError: The given username must be set In my project I'm using Django 1.11 and AngularJS 1.6 View.py def registrarCliente(request): if request.method=='POST': usuariosfinales=[] nombre=request.POST.get('nombre') email=request.POST.get('email') password=request.POST.get('password') user=User.objects.create_user(email, email, password) user.save() usermodelo=Usuario(usuario=user, nombre=nombre) usermodelo.save() userfinal=authenticate(username=email, password=password) login(request, userfinal) usuariosfinales.append(userfinal) data=serializers.serialize('json', usuariosfinales) return HttpResponse(data, content_type="application/json") return render (request, "login/login.html") login.html <div class="login-wrap" id="login" ng-app="appLogin" ng-controller="conLogin"> <div class="login-right striped-bg" ng-show="Registro"> <div class="login-form"> <div class="heading"> ¡Registrate! </div> <div class="input"> {% csrf_token %} <div class="login-input-group spacer-field"> <span class="login-input-group-addon"> <i class="fa fa-user fa-fw"></i> </span> <input type="text" class="form-control" name="nombre" placeholder="Nombre" ng-model="user.nombre"> </div> <div class="login-input-group spacer-field"> <span class="login-input-group-addon"> <i class="fa fa-at fa-fw"></i> </span> <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="user.email"> </div> <div class="login-input-group spacer-field"> <span class="login-input-group-addon"> <i class="fa fa-key fa-fw"></i> </span> <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="user.password"> </div> <div class="login-input-group"> <span class="login-input-group-addon"> <i class="fa fa-key fa-fw"></i> </span> <input type="password" class="form-control" name="password2" placeholder="Repetir contraseña"> </div> <button class="btn btn-default btn-lg submit" type="submit" ng-click="registrar()">Registrarme</button> </div> </div> </div> </div> appLogin.js (function(angular) { // body... angular .module('appLogin', []) .controller('conLogin', ['$scope', '$http', function($scope, $http){ //Registro de usuario $scope.user = {nombre:'', email:'', password:''}; $scope.registrar = function(email, password){ $http({method:'POST', url:'/registro/', data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password} }).then( … -
Django 1.10: Translation/Localization Not Switching Languages (Using Non-Default Language?)
I am working on a web-app and I want to be able to switch between specifically English and Filipino (Tagalog) using Django's i18n functionalities. Right now, my webpage is literally just "hello", but I want it to show the Filipino translation ("Kamusta"), and I tried to implement my view.py such that it happens. However, it still just says "hello", and doesn't switch. Here is what I have so far. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'example/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('en', _('English')), ('tl', _('Tagalog')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'example/locale'), ) views.py: from django.shortcuts import render from django.http import HttpResponse from django.utils.translation import LANGUAGE_SESSION_KEY from django.utils import translation # Create your views here. def index(request): translation.activate("tl") request.session[LANGUAGE_SESSION_KEY] = "tl" return render(request, "index.html") index.html: {% load i18n %} <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> {% trans "Hello world!" %} </body> </html> django.po: # SOME DESCRIPTIVE TITLE. … -
If database autocommit mode is enabled, why should I care about transaction.on_commit()?
I've read that Django > 1.9 introduces transaction.on_commit in order to avoid race conditions. I know that Django sets database autocommit to true by default, so each query becomes a transaction at db level. However, take this example, from django.db import transaction def some_view(request): obj = SomeModel.objects.create(field=value) transaction.on_commit(lambda: some_async_task(obj.pk)) Why should I wrap some_async_task(obj.pk) inside transaction.on_commit? I'm not sure how transactions work behind the scenes. All this time I've been thinking that as autocommit is enabled, create or save method should be a transaction itself, and then, in the next statement that object should exist in database. -
Uwsgi Nginx long urls are failed with out any error message
Configured the UWSGI configuration in supervisor and Nginx. The length of the URL is 5076 characters. It is working fine on sample port. The request is passed Nginx and then came to the supervisor. It returns the following message generated 0 bytes in 1 msecs (HTTP/1.1 302) 4 headers in 132 bytes (1 switches on core 58) -
Hide Django logo/name in header Django admin tool
I want to hide/change the name displayed in the header bar, the label that I want to change is "DJANGO" word as the next image shows" -
where are Jinja2 variables and files located and how do i find them?
noob here, so please bear with me. My question is where is the web_include_css file and where is the link or abs_url variable? How do i find them? {%- for link in web_include_css %} <link type="text/css" rel="stylesheet" href="{{ link|abs_url }}"> {%- endfor -%} -
Ajax call is not working in Django?
This is my ajax call: <script> $(document).ready(function(){ $("#butt2").click(function(){ $.ajax({ url:'{% url 'task:deletetask' %}', data:{'id':2 }, type:"GET", success:function(text){ $("#task2").hide(); alert(text); }}); }); }); </script> This is my view function: class DeleteTaskView(generic.View): def get(self,request): id=request.GET.get('id',None) Task.objects.get(id=id).delete() return JsonResponse("Task Removed") This is the url: url(r'user/task/delete/$',views.DeleteTaskView.as_view(),name='deletet ask'), If I remove the ajax call, and simply add alert function, then it is properly working, means jquery is working, there is some problem with ajax call only. Help ! -
How to run scripts in django context from pycharm
How to run an arbitrary script in the django context while using pycharm? -
Learning Django Class Based Views
I want to ask you where can I find resources about Django's Class Based Views and their methods that I can efficiently override and use. Most of resources I found are using and explaining FBV. I know the basics, I used many times List, Detail, Delete, Create Views but I'm not feeling comfortable using them. Thanks for any answers! -
Django/JSON: Finding Species in Range, Printing in JSON
I am working on a Species Recommendation tool that will find all of the trees in a GPS range, average out the trees of allowed species, and then return the results in a JSON dict that can be parsed and read out. I was working with folks from Code for SF who were using the K Nearest Neighbors algorithm, which was really nice, but kept crashing the application and was only pulling from a csv I uploaded, rather than the database of trees and planting sites I created. Is there a way to implement K Nearest Neighbors to search my database that's better than using latitude__range and longitude__range? This is my current view: def sg_species_guide_latlong_json(request, latitude=1, longitude=1): min_latitude = decimal.Decimal(latitude) min_latitude -= decimal.Decimal(0.01) max_latitude = decimal.Decimal(latitude) max_latitude += decimal.Decimal(0.01) min_longitude = decimal.Decimal(longitude) min_longitude -= decimal.Decimal(0.01) max_longitude = decimal.Decimal(longitude) max_longitude += decimal.Decimal(0.01) response = JsonResponse(dict(species_list=list(RecommendedSpecies.objects.values( "species__id_species", "species__trees_of_species__condition__score", "species__name_scientific", ).filter( Q(species__trees_of_species__planting_site__coord_lat__range=[min_latitude, max_latitude]), Q(species__trees_of_species__planting_site__coord_long__range=[min_longitude, max_longitude]), ).annotate(avg_condition=(Avg('species__trees_of_species__condition__score')), num_trees=(Count('species__trees_of_species'))).order_by('-avg_condition')))) return response It's VERY slow, especially for what should be an AJAX/JSON call. In addition, I want to print out the results in a format that contains the species name, number of trees, and average condition. Sorting that is easy in my view, but printing it … -
Upgrading Django Version: Best Practice
I've pretty big code base written on Django 1.5, it's about time to upgrade to the newest version (1.11.2) as many stuff don't work well. I'm wondering if it's best to upgrade step by step: 1.5->1.6->1.7... or just jump to 1.11.2 what method should be better and make the (hard) process easier? as my project has many dependencies? Also what are good practices to do? I'm using virtualenv and aware of this Django article about upgrading -
Adding css/js files to the home site in the admin's panel django
I am trying to add a simple script to my admin's panel in django. I am following this example from the doc, which works when I do this: class ArticleAdmin(admin.ModelAdmin): class Media: js = ("my_code.js",) admin.site.register(Article, ArticleAdmin) my_code.js (which lives in STATICFILES_DIRS) gets executed when I open the "Article" link in the admin's panel (so this would be the example url: localhost:8000/admin/news/article/) However, I want it to be executed in the home site, as in right after I login to the admin's panel (this would be the url:localhost:8000/admin/) . Where do I have to insert the class Media then? -
Django Rest Framework Post Nested Using Files with requests module example
Excuse me, i have a problem, can anyone help me. I have models like: from django.db import models from django.contrib.auth.models import User import uuid def uuid_generator(): return str(uuid.uuid4()) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_user') mobile = models.CharField(max_length=20) alamat = models.TextField(blank=True) phone = models.CharField(max_length=20, blank=True) foto = models.ImageField(upload_to='profile', blank=True) def __str__(self): return self.user.username class Rumah(models.Model): JENIS_CHOICES = ( ('rumah', 'Rumah besar'), ('petakan', 'Rumah petakan'), ('apartement', 'Apartement'), ('kost', 'Kost-Kostan') ) WAKTU_CHOICES = ( ('bulanan', 'Bulanan'), ('tahunan', 'Tahunan'), ) STATUS_CHOICES = ( ('tersedia', 'Tersedia'), ('terisi', 'Sudah Terisi'), ('ditutup', 'Di Tutup'), ) pemilik = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rumah_user') kode = models.CharField(unique=True, max_length=150) jenis = models.CharField(max_length=12, choices=JENIS_CHOICES, default='rumah') waktu = models.CharField(max_length=10, choices=WAKTU_CHOICES, default='bulanan') harga = models.PositiveIntegerField() alamat = models.TextField() status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='tersedia') keterangan = models.TextField(blank=True) def __str__(self): return self.kode def save(self, *args, **kwargs): self.kode = uuid_generator() super(Rumah, self).save(*args, **kwargs) class Foto(models.Model): rumah = models.ForeignKey(Rumah, on_delete=models.CASCADE, related_name='foto_rumah') penampakan = models.ImageField(upload_to='penampakan', blank=True) keterangan = models.TextField(blank=True) def __str__(self): return self.rumah.kode Note: Rumah like House in english and Foto like Picture in english. I have a views like: from django.contrib.auth.models import User from produk.models import Profile, Rumah, Foto from .serializers import UserSerializer, ProfileSerializer, RumahSerializer, FotoSerializer from .permissions import IsOwnerOrReadOnly, IsHasProfile, IsRumahOrReadOnly from rest_framework import mixins from rest_framework … -
Web Frameworks For Securely Distributing Web Based Application Software?
I'm looking at getting into web design, specifically for creating web based applications for businesses, and I've hit a roadblock. Ideally you could host your own web based application on your own servers, which I can comfortably achieve at this stage, however many companies may want to rather host the software on their own server for security reasons. Is there any web framework that exists that would allow me to create the web application and distribute it to the client, while not allowing the client direct access to the "source code" of the application? For example, one that is based on a language which compiles/obfuscates/encrypts the source files? Initially I was using Django, however Python isn't secure as it can easily be "decompiled" and so the client would have complete access to all the scripts and be able to do as they please. I realise every file can be decompiled with enough effort, however I'd feel safer knowing that there would need to be some effort to get the source code rather than handing it to them on a silver platter. Alternatively is there realistically no way to distribute the application securely, and either just host it ourselves or put … -
Django add images to sitemap xml file
I have searched a lot, but I didn't find any simple and high voted way to add images to sitemap xml file. Is there any modern way to add images to sitemap in Django? -
Customising error fields for Django log in templates
I'm semi-new to Django (but not new to Python or front end languages) - I'm just having a little trouble rendering required fields and error messages. forms.py: from django import forms from django.contrib.auth import authenticate, login, logout class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and not password: raise forms.ValidationError("Please enter a valid password...") elif not username and password: raise forms.ValidationError("I think you've forgotten to enter your username...") elif username and password: user = authenticate(username = username, password = password) if not user: raise forms.ValidationError("This user does not exist...") if not user.check_password(password): raise forms.ValidationError("Incorrect password...") if not user.is_active: raise forms.ValidationError("This user does not appear to be active.") return super(UserLoginForm, self).clean(*args, **kwargs) login_form.html: <form class="contact-form contact-form-two" name="contact-form" method="POST" action='' enctype='multipart/form-data'> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" required="required" placeholder="User ID"> <input type="password" class="form-control" required="required" placeholder="Password"> <button type="submit" class="btn btn-primary" value='{{ title }}'>Sign In</button> </div> </form> Ignore the classes - I'm just borrowing from the default contact form I have created (at some point I will reorganise into one master "form" class.) views.py: from django.shortcuts import render from django.contrib.auth import authenticate, get_user_model, login, logout from .forms import UserLoginForm # … -
using select_related and prefetch_related with many arguments
I am relatively new to django, and I am using select_related() and prefetch_related() in django to decrease my hits to the database. this is a part of my views.py file: topic = Topic.objects.filter(id=topic_id).select_related('followed_by') questions = Question.objects.filter(topics=topic).prefetch_related('answers','question_comments','answers__created_by__userprofile','answers__answer_comments') without the select_related and prefetch_related the view does 42 queries in 23.36MS, and with those added, it decreases to 10 queries in 7.91MS, looking at this data, I think those functions are really great. So my question is this: Is there any downside to using these two functions? Should I not join this many tables in one go? -
Sending JSON object to Django template
I have a simple page with a form. A form takes a name and a position, and it sends POST request to index() view. Index view is the only view in the app, it renders the initial map using d3.js, and after post it should reload with rendered position of person. The index view is defined as: def index(request, name='', position=(0, 0)): if request.method == 'POST': name = request.POST['name'] position = int(request.POST['position']) person = make_a_json(name, position) return render(request, 'app/index.html', { 'json_file' : person }) return render(request, 'app/index.html', { 'json_file' : None }) import json def make_a_json(name, age): # Implementation of this is not important, it sends query # to other server, that server returns json, a json is parsed # and transformed into less verbose version of original json # Returned values is in the form of # [ {'name' : 'John', 'longitude' : 30, 'latitude' : 12}] return json.dumps(...) My d3.js script is embeded in the template, the following part is used to plot circle on a map where a person is located: d3.json({{ json_file|escapejs }}, function(data) { g.selectAll("circle") .data(data) .enter() .append("svg:circle") .attr("cx", function(d) { return projection([d.longitude, d.latitude])[0]; }) .attr("cy", function(d) { return projection([d.longitude, d.latitude])[1]; }) .attr("r", 5) .style("fill", … -
Has django analog Rails gem spring?
When I am changing source code in my django project then server reload. Reloading take 2-3 seconds. Rais has gem spring for autoloadig code changing. Has django alternatives of gem spring? -
Django bootstrap files not found
I have set up Django with bootstrap following some tutorials but even when I am doing the same as in the tutorials Django doesn't find the static files. My Project has the following structure: webshop shop migrations templates ... static css bootstrap.min.css ... webshop ... db.sqlite3 manage.py In the data settings.py I have added STATIC_URL = '/static/' And in the Index.html I load the static files with following code: <head> <title>Webshop</title> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/> </head> But Django can't find the data bootstrap.min.css. -
Make a relation 3 django models and add filter
How do I make a relation 3 django models? I would like to be able to do the mysql query, but as I do with django, I want to relate 3 models and additionally I want to add a filter by user ID SQL Query SELECT * FROM hospetaje inner join usuario on (Usuario_idUsuario=idUsuario) inner join pago on (idHospetaje=Hospetaje_idHospetaje) where idUsuario = 5 My model is class Usuario(models.Model): idusuario = models.AutoField(db_column='idUsuario', primary_key=True) # Field name made lowercase. cc = models.CharField(unique=True, max_length=45) nombre = models.CharField(max_length=15) apellido = models.CharField(max_length=20) fecha_nacimiento = models.DateField() sexo = models.CharField(max_length=6) e_mail = models.CharField(db_column='e-mail', max_length=30) # Field renamed to remove unsuitable characters. telefono = models.CharField(max_length=10) usuario = models.CharField(max_length=30) contrasena = models.CharField(max_length=10) tipousuario_idtipousuario = models.ForeignKey(Tipousuario, models.DO_NOTHING, db_column='TipoUsuario_idTipoUsuario') # Field name made lowercase. class Pago(models.Model): idpago = models.AutoField(db_column='idPago', primary_key=True) # Field name made lowercase. fechapago = models.DateTimeField(db_column='fechaPago') # Field name made lowercase. fechapagada = models.DateField(db_column='fechaPagada') # Field name made lowercase. valor = models.FloatField() hospetaje_idhospetaje = models.ForeignKey(Hospetaje, models.DO_NOTHING, db_column='Hospetaje_idHospetaje') # Field name made lowercase. class Hospetaje(models.Model): idhospetaje = models.AutoField(db_column='idHospetaje', primary_key=True) # Field name made lowercase. usuario_idusuario = models.ForeignKey('Usuario', models.DO_NOTHING, db_column='Usuario_idUsuario') # Field name made lowercase. habitacion_idhabitacion = models.ForeignKey(Habitacion, models.DO_NOTHING, db_column='Habitacion_idHabitacion') # Field name made lowercase. fechainicio = models.DateField(db_column='fechaInicio') # Field name … -
Django runserver on all ports?
Why can't I run python manage.py runserver on all ports? I understand this is probably a newbie question, but what prevents me from achieving this? I would like to access my app without having to include the port, like a regular website