Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: do SQL join for getting row count
In Django, I have a User model and a Following model: class User(): uid = models.UUIDField(primary_key=True) class Following(): follower_uid = models.ForeignKey(USER_MODEL, related_name="followers") followed_uid = models.ForeignKey(USER_MODEL, related_name="following") with corresponding database tables for both object types. When Django loads a User object, I want to also load the number of followers of that user in the same database query, i.e. using a join. What I don't want to do is load the user first and then do a second query to get the number of followers. Is this possible using the Django object model or do I have to write raw sql? I also want to load a second-degree count; that is, the number of followers of the followers of the user. As before, I want this count to be loaded in the same database query as the user itself. Appreciate specific syntax and examples, I have read a ton of Django documentation and nothing seems to answer this. Thanks! -
django generic relation delete performance
I'm working on a project with two genericrelation in a model. I discover that the relations are useless and moreover therea 3 million records that we don't need anymore. Is there any way do delete it fast? Remove the field on migrations has no effect because is generic. So I tried import time from django.contrib.contenttypes.models import ContentType from app.core import models as m # UserInformation has a GenericRelation with Address c = m.UserInformation.objects.first() c_type = ContentType.objects.get_for_model(c) # get all the models records generic related with UserInformation query = m.Address.objects.filter(content_type_id=c_type.id) start = time.time() i=0 stop_iteration = 10 for user in query: i += 1 user.delete() if i == stop_iteration: break end = time.time() seconds = end - start print('Execution of %s deletes: %3d seconds' % (stop_iteration, seconds)) The result: Execution of 10 deletes: 34 seconds This means that it will takes 37 days to delete ~1million records Is there any way to do that quicker? -
Should I recompile .po files to .mo on the server in deployment, or deploy .mo?
I have a .po file containing translations for my app, and used django-admin compilemessages to create .mo files locally which work fine. In deployment, should I recompile po to mo on the server (Elastic Beanstalk), or just track the compiled mo files in version control and upload them? This .gitignore template has .mo files ignored which would suggest they should be compiled on the server, but I'm not sure why. Are the compiled files specific to each server somehow? -
python: weird "AttributeError: 'NoneType' object has no attribute 'FrontEndTestingStart'"
utils/frontend/urls.py from utils.frontend import views #more stuff views.FrontEndTestingStart.as_view() utils/frontend/views.py class FrontEndTestingStart(APIView): python reports AttributeError: 'NoneType' object has no attribute 'FrontEndestingStart' As if views.py would return None when importing. Why is that? I have a __init__.py in the directory -
how to find django fields / variables? python
I am new to python and django. I have searched a bit how to find the fields such as php using var_dump or js using console.log. There are threads using imports and / use commands through the command line. But is there a way like php or js that we can enter it into the html directly and see what's in the variable? Hopefully this question makes sense. Thanks in advance. -
Django - Rewriting an application, is this slow transition method a bad idea?
I'm looking at rewriting a large web application from scratch. I want to transition to this new version slowly, bringing sections of it online as they are completed instead of transitioning to the new version all at once. The problem is that while there are logical sections that can be re-written in chunks, many of the sections are inter-dependant. Records in one section need to be referenced in the other sections. For example, the Accounting section needs to know the PK and details of all the Customer records. Accounting doesn't need to write to any of these records, just read. The other issue is that the old version is on Django 1.4 and the new one I'd like to write in 1.10 so they don't 'play nice' together. Here's what I'm thinking as a strategy: Create URLs on the old app that spit out JSON data The new app will make calls to the old app when it needs to know the details of the records from the old app, and consume that JSON data As new sections of the new web app become functionally complete, those same sections of the old app can simple stop being used. Does this … -
How to use django smart-selects with modelform?
I'm using smart-selects. models.py : class ChoixTangente(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class ChoixModele(models.Model): name = models.CharField(max_length=255) tangentes = models.ManyToManyField('Choixtangente', blank=True) def __str__(self): return self.name class Modele(models.Model): tangente = models.ForeignKey(ChoixTangente, blank=True, null=True) modele = ChainedManyToManyField( ChoixModele, chained_field="tangente", chained_model_field="tangentes", auto_choose=True, ) def __unicode__(self): return str(self.pk) I have it working fine in admin : I create ChoixTangente instances I create ChoixModele instances and select ChoixTangentes instances in the list I can create Modele" instances by selecting "tangente" in a list of ChoixTangente and "modele" in the list of corresponding ChoixModele choices resulting from the steps 1) and 2) see Admin form screenshot I whish to have my users do the same through a form. But I can't have it working. the field "Tangente" is populated with the list of ChoixTangente but when I choose a value the field "modele" stays empty instead of displaying a list of corresponding choices. see form screenshot for the users Here is my form.py : from django import forms from .models import Appareil class AppareilForm(forms.ModelForm): class Meta: model = Appareil fields =('tangente', 'modele') -
Django: Reverse for 'consultation_pdf' with arguments '()' and keyword arguments '{'pk': 1}' not found
i have 2 models Patient and Consultation , the later has patient as foreignkey. #models.py class Consultation(models.Model): # données générales et symptomatologie patient = models.ForeignKey(Patient, on_delete=models.CASCADE) consultation_date = models.DateField("date de consultation") medecin = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True) emergency = models.BooleanField("urgence", default=False) ... def __str__(self): return '%s %s' % (self.patient, self.consultation_date) def get_absolute_url(self): return reverse('detail_consultation', kwargs={'pk':self.pk}) class Patient(models.Model): name = models.CharField(verbose_name="nom et prénoms", max_length=50) birth = models.DateField(verbose_name="date de naissance") GENDER_CHOICES = ( ('M', 'Masculin'), ('F', 'Féminin'), ) gender = models.CharField(verbose_name="sexe", max_length=1, choices=GENDER_CHOICES) ... class Meta: ordering = ['name'] def get_absolute_url(self): return reverse('detail_patient', kwargs={'pk': self.pk}) def __str__(self): return(self.name) views Besides "classic" CBV i have function based view that renders pdf reports using a LaTex template #views.py def consultation_pdf(request, pk1, pk2): entry = Consultation.objects.get(pk=pk1) source = Patient.objects.get(pk=pk2) context = Context({ 'consultation': entry, 'patient': source }) # buffer = BytesIO() template = get_template('clinique/consultation.tex') rendered_tpl = template.render(context, request).encode('utf-8') # Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() … -
Email logging with Python Django
Django does support email log handlers. But this way, if some error is repeated often, we risk to be mail-bombed by ERROR emails. How to send us emails on errors but not too often? Any other solutions? -
Auto upload youtube thumbnail using embed address?
I had this working at one point but I've managed to break it somehow I'm hoping someone can be a second pair of eyes and pinpoint my issue. I'm embedding youtube videos and trying to download a thumbnail at the same time. the video_thumbnail function was working but when I save now the thumbnail field is blank, I have no idea what I did to break it. here's an edited version of my model: class Video(models.Model): video_embed = models.CharField(blank=False, max_length=255, help_text="Enter a youtube embed code") thumbnail = models.ImageField( upload_to="img/site/measures/images/thumbnails/", max_length=100, null=True, blank=True, ) def video_thumbnail(self): if self.video_embed: import re from django.core.files import File from django.core.files.temp import NamedTemporaryFile import urllib2 from urllib2 import urlopen thumbnail1 = self.video_embed thumbnail2 = re.sub(r'^<iframe width="560" height="315" src="https://www.youtube.com/embed/', "https://img.youtube.com/vi/", thumbnail1) thumbnail3 = re.sub(r'" frameborder="0" allowfullscreen></iframe>', "/1.jpg", thumbnail2) img_temp = NamedTemporaryFile(delete=True) img_temp.write(urllib2.urlopen(thumbnail3).read()) img_temp.flush() self.thumbnail.save(thumbnail3, File(img_temp)) -
Can't access models from seperate: ImportError: no module named "HealthNet.ActivityLog"
I've been working on a way to log the activity of a system for a school project in Python 3.4 and Django 1.9. I am currently trying to import a models.py file from my ActivityLog app into other applications in my HealthNet project to save the activity. The IDE I'm using (Pycharm), is telling me that my code is correct but I get the this error whenever I try to makemigrations/migrate/runserver: ImportError: No module named 'HealthNet.ActivityLog' Here is my file setup: HealthNet ActivityLog Migrations __init__.py admin.py apps.py models.py tests.py views.py Appointments Migrations __init__.py admin.py apps.py models.py tests.py views.py HealthNet __init__.py settings.py urls.py wsgi.py I'm trying to import models.py from ActivityLog into views.py from Appointments. Here's my code from models.py from django.db import models class Log(models.Model): logTime = models.DateTimeField() logEvent = models.CharField(max_length=500) def __str__(self): return self.logEvent This is the import statement from views.py in the Appointment package, which is the line that the error is tracing back to: from HealthNet.ActivityLog.models import Log And here is my list of installed apps in my settings.py file: INSTALLED_APPS = [ 'Appointment.apps.AppointmentConfig', 'User.apps.UserConfig', 'ActivityLog.apps.ActivitylogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Thank you! -
Trying to use views in django like I use to used in python
why it does not work ? It suppose to work, in python I can use this like this function, can any one explain me please ? views: class MiVista(View): def get(self, request, var): self.var = 'Hello' # return HttpResponse(self.var) one = MiVista() one.get(222222) urls: url(r'^indice/', MiVista.as_view()), So the functions does not work like function in python using POO ? Thank you guys! -
Django throwing error when loading permission fixture
I have a Django fixture describing groups and their permissions, all using natural keys, like: [ { "pk": 1, "model": "auth.group", "fields": { "name": "General Users", "permissions": [ [ "view_client", "myapp", "client" ], [ "view_project", "myapp", "project" ], [ "view_notes", "myapp", "notes" ], ... ] } } ] But when I load this using manage.py loaddata myfixture.json --verbosity 3, it throws: DeserializationError: Problem installing fixture '/myproject/src/myapp/fixtures/myfixture.json': Permission matching query does not exist. Presumably, one of the permission records referenced in the permissions list doesn't exist, and is throwing a DoesNotExist error. How do I figure out which record it is without manually trying going through a process of elimination? I'm using Django 1.7. -
PyCharm not pushing (or git not receiving) changes
I'm new to git and I thought I understood what was going on, but apparently not. I have a git repository set up on an Ubuntu Server 16 VM. I'm working Django Dev on it and I've configured PyCharm to use it. In PyCharm I have successfully cloned the project and I made changes. Now here's where I'm baffled. I made a couple of changes and pushed them and everything worked fine. Now I've made a change to a file called detail.html, I committed it to my local master, and then pushed it to the git repository. Everything said green to go, the repository took the change, pycharm told me the push worked. However, when I look at that file on the repository, it hasn't actually updated! Not really sure what's going on and I have no idea if it's a problem with git, pycharm, or the most likely answer: me - though no matter how you answer I will find a way to blame it on something else because I, the programmer, am clearly perfect. -
How is a page instance's slug defined in Mezzanine CMS?
From the docs: By default the template pages/page.html is used, but if a custom template exists it will be used instead. The check for a custom template will first check for a template with the same name as the Page instance’s slug, and if not then a template with a name derived from the subclass model’s name is checked for. So given the above example the templates pages/dr-seuss.html and pages/author.html would be checked for respectively. The question is where does Mezzanine CMS gets the slug for an instance of a page? Is it from the title attribute? -
How to serialize a single model instance AND include the primary key
I have a single model instance obj. I want to serialize it, and for the primary key to be included in the serialized data. django.core.serializers.serializer wants a queryset (throws an error that ojb isn't iterable). I simply cannot coerce django.forms.model_to_dict into including the primary key in the serialized object, even explicitly calling: model_to_dict(obj, fields=['pk']) or model_to_dict(obj, fields=['id']) How do I do this? -
How to get html page path in a django project?
My role is to reconstruct html & css in a django project which contains 10 apps. each app has a urls.py file. And the urls to the .html is written in a very complicated way like this: url(r'^\w+/.*list/(?P<objtype>[\.\w-]+)/(?P<parent_str>(((\w+)/)*))$', utilreqs.listview) Is there a way to know the path to which html page I'm viewing in the browser? ex: projectname/appname/templates/name.html -
No such table during Django unittest
When I run manage.py test in a Django 1.7 project, it throws the exception: django.db.utils.OperationalError: Problem installing fixture '/myproject/myapp/fixtures/initial_data.json': Could not load sites.Site(pk=1): no such table: django_site My INSTALLED_APPS contains django.contrib.sites. I also just upgraded from a Django 1.6 install, but I'm not sure why that would cause this error, and there's no in the Django 1.7 release notes that explain it. How do I fix this. -
How can i improve my website response time when using https(ssl)
My website is on Django with Apache and mod_wsgi. My website responsive times are around 500ms when I use http. But when I installed ssl certificate on server for https. My server responsive times are going up to 1300ms. So what should do to improve my website response time when I use https(ssl). -
Pycharm show a python file like a text file, how to fix?
I have Pycharm.2016.2.3, I use Django 1.9.4 and Python 3.5.1. The problem: Pycharm works good until today, but today he show only forms.py like a file text. Note: forms.py is a Python File with extention *.py but rest of Python File it's shows good. The code works good, the imports works, but when I try to import something from forms.py pycharm don't autocmplete. PS I have this problem in all pycharm project, and the default files from Django with forms is shows like text file. -
form data is storing in database when using jquery
i was trying to use jquery to load form when value of drop down change .it loading the form but after submitting data is not storing in database . it just refreshes the page. forms.py class accountForm(forms.ModelForm): choice = ( ('payment type','payment type'), ('paypal', 'paypal'), ('payeer', 'payeer'), ('payza', 'payza'), ('bitcoin', 'bitcoin'), ) payment_type = forms.ChoiceField(choices = choice, widget = forms.Select(attrs = {'class':'forms-control'})) email = forms.EmailField(widget = forms.EmailInput(attrs={'class':'form-control'})) bitcoin = forms.CharField(widget = forms.TextInput(attrs = {'class':'form-control'})) amount = forms.IntegerField(widget = forms.NumberInput(attrs = {'class':'form-control'})) class Meta: model = payments fields = [ "payment_type", "email", "bitcoin", "amount", ] views.py def payment(request, username): form = accountForm(request.POST or None) if form.is_valid(): print(form) form.save(commit = False) form.save() return HttpResponseRedirect('/accounts/profile/') context = {'form':form} return render(request, 'payment.html', context) payment.html <div class="panel-body"> <div class="tab-content"> <div class="tab-pane active" id="home"> <div class="panel-body" id="panel"> <div class="form-group"> <h4 class="text-primary">Select Withdrawal Type</h4> {{ form.payment_type }} </div> </div> <div class="panel-body"> <form method="POST" id="form" enctype='multipart/form-data'> {% csrf_token %} </form> </div> </div> </div> </div> jquery <script type="text/javascript"> $('select').on('change', function (e) { var Selected = $("option:selected", this); var valueSelected = this.value; console.log(valueSelected); if (valueSelected == 'paypal') { $("#panel").change(function (e) { $("#panel").empty(); // $('#form').append('{% csrf_token %}'); $('#form').append('<label>email</label>'); $('#form').append('{{ form.email }}'); $('#form').append('{{ form.amount }}'); $('#form').append('<button class="btn btn-primary btn-default">submit</button>'); }) } }); … -
connect() failed (111: Connection refused) while connecting to upstream, client
I am trying to deploy a django instance to ec2 . I am using a combination of nginx and gunicorn to achieve that. I got the nginx isntance and gunicorn to start correctly and I am able to get my instance running. But when i try to upload an image to the database on my application I run into this error in my gunicorn error.log : connect-failed-111-connection-refused-while-connecting-to-upstream Also all my api calls from the front end to the database return a 500 internal server in the console. My nginx.conf looks like default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; include /etc/nginx/sites-available/*; index index.html index.htm; server { listen 127.0.0.1:80; listen [::]:80 default_server; server_name 127.0.0.1; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } # redir And my sites-enabled/default file as upstream app_server_djangoapp { server 127.0.0.1:8000 fail_timeout=0; } server { #EC2 instance security group must be configured to accept http connections over Port 80 listen 80; server_name myec2isntance.com; access_log /var/log/nginx/guni-access.log; error_log /var/log/nginx/guni-error.log info; keepalive_timeout 5; # path for static files location /static { alias xxxxxx; } location /media { alias … -
Django - filter model
I have a model with a field that is a list. For example: mymodel.sessions = [session1, session2] I need a query to get all mymodels that session1 is exist their sessions. Thank you ! -
Using django filer out of admin area (or an alternative library)
Django filer is an awesome tool for managing files, it detects duplicates and organizes files based on their hashes in folders, has great UI for managing files and folders and handles file history and permissions. I read some of the source code and realized it extensively uses django admin features in code and in templates; is there any way to use these features for non-staff members that are logged in? To give them tools for uploading and managing their own files and folders in their personal upload area (without reinventing the wheel)? If there isn't an easy way, what alternatives are there and you suggest to provide such functionality with minimum changes in code? -
Include Django URLs in Sphinx documentation?
In the interests of staying DRY as possible, I am using Sphinx with autodoc for documenting my Django project. I'm currently adding some comments to show the URL endpoints to reach certain functionality, but in doing some I'm duplicating what is already defined in my urls.py files. Is there a way to include references to URLs within comments and have them processed by Sphinx such that the more extended URLs are shown in the documentation?