Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extending the AbstractUser Model in Django
What are the attributes that are defined in the Django AbstractUser model? I have extended the model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass Do I have to create my own fields for username, first name, last name, etc? Or are they already defined? -
Fail to verify RSA signature on server side that was created using Javascript on client side
I'm using forge on the client where I create the signature as follows. //Client Side var md = forge.md.sha256.create(); md.update(encryptedVote, 'utf8'); var pss = forge.pss.create({ md: forge.md.sha256.create(), mgf: forge.mgf.mgf1.create(forge.md.sha256.create()), saltLength: 20 }); var signature = privateKey.sign(md, pss); Then later on the server I try to verify the signature using the cryptography library as follows. #server side user_public_key_loaded.verify( signature, enc_encrypted_vote, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=20 ), hashes.SHA256() ) I get consistently an Invalid signature error. I tried changing the encoding on the client to md.update(encryptedVote, 'latin1'); and now sometimes works some others it doesn't. Any idea what I'm doing wrong? -
Django loaddata with natural keys and many-to-many-relation to self
I have a model with ManyToManyField to "self". Now I want to copy data from my local to the production environment. In order to do that, I'd like to dump all entries from my database to a fixture and load that on the production server. Because that server already contains data, I export them using natural keys. The export runs fine, but I get errors during loaddata if one instance references a relation to another instance of the same model that is defined below that one in the fixture. What confuses me: Everything goes well, if I don't use natural keys. But this clashes with data already present on production. Please consider the following example: from django.db import models class PersonManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Person(models.Model): objects = PersonManager() name = models.CharField(max_length=150, unique=True) friends = models.ManyToManyField("self", blank=True) def natural_key(self): return self.name, To reproduce: >>> python manage.py shell >>> from relations.models import * >>> person1 = Person.objects.create(name='foo') >>> person2 = Person.objects.create(name='bar') >>> person3 = Person.objects.create(name='baz') >>> person2.friends.add(person2) >>> person2.save() >>> exit() >>> >>> python manage.py dumpdata relations.Person --natural-primary --natural-foreign > relations/fixtures/people.json # change the database url to an empty database and run migrations >>> python3 manage.py loaddata people raises … -
Basic Search in Django
I am trying to implement a basic search in Django. When I click on search, it doesn't display anything. Can someone help me to fix the issue please. Not sure what is missing views.py template = 'blog/post_list.html' if 'q' in request.GET and request.GET['q']: query = request.GET['q'] assets = Post.objects.filter(Q(title__icontains=query) | Q(description__icontains = query) ) context = {'title': assets, 'description' : assets, } return render(request, template, context) html <form method = "GET" action ="{% url 'search' %}" class ="search-form" role ="search"> <input name = "q" value = "{{request.GET.q}}" type="text" placeholder="Search ..." class="input"> <div class="btn" type = "submit"> <i class="fa fa-search" aria-hidden="true"></i> </div> </form> -
Filtering with DjangoFilterBackend does not found the url
I'm using Django rest framework 3.8.2. I have read http://www.django-rest-framework.org/api-guide/filtering/ and follow the given example for DjangoFilterBackend section. my model: class Pregunta(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=512, null=False) descripcion = models.CharField(max_length=200, null=False) categoria = models.ForeignKey(Pregunta_Categoria, on_delete=models.PROTECT) tipoRespuesta = models.ForeignKey(TipoRespuesta, on_delete=models.PROTECT, related_name='fk_id_tipoRespuesta') #sacar el default privated = models.BooleanField(default=False) status = models.CharField(max_length=1, default='A') created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='proy_created_by8') created_on = models.DateTimeField(default=timezone.now) modified_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='proy_modified_by8') modified_on = models.DateTimeField(blank=True, null=True) class Meta: permissions = ( ('view_pregunta', 'View Pregunta'), ) def __str__(self): return "%s" % (self.name) def __unicode__(self): return u'%s' % (self.name) that's my view: class PreguntaViewSet(viewsets.ModelViewSet): queryset = Pregunta.objects.filter(estado='A') serializer_class = PreguntaSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('name', 'privated') that's my serializer: class PreguntaSerializer(serializers.ModelSerializer): nom_tipoRespuesta = serializers.CharField(source="tipoRespuesta.nombre", required=False, allow_blank=True) class Meta: model = Pregunta fields = ('id', 'name', 'descripcion', 'categoria', 'tipoRespuesta', 'created_by', 'created_on', 'modified_by', 'modified_on', 'status', 'privated', 'nom_tipoRespuesta') my urls: from django.conf.urls import url, include from rest_framework import routers from proy import views router = routers.DefaultRouter() router.register(r'questions', views.PreguntaViewSet) router.register(r'questionCategories', views.PreguntaCategoriaViewSet) router.register(r'projects', views.ProyectoViewSet) router.register(r'polls', views.EncuestaViewSet) router.register(r'questionnaire', views.CuestionarioViewSet) router.register(r'pollByUser', views.EncuestaPorUsuarioViewSet) router.register(r'answerType', views.TipoRespuestaViewSet) router.register(r'answers', views.RespuestaViewSet) router.register(r'answerByUser', views.RespuestaPorUsuarioViewSet) router.register(r'variablesType', views.TipoVariableViewSet) router.register(r'variablesCategory', views.CategoriaVariableViewSet) router.register(r'variables', views.VariableViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] settings.py: REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), 'DEFAULT_PERMISSION_CLASSES': ( #'rest_framework.permissions.IsAuthenticated', ), 'EXCEPTION_HANDLER': … -
Search for duplicates
I have two hundred thousand records in the SQL table. The model has 6 fields. Considered that duplicate is the match of 3 or more fields with any another tuple in this table. I need to find duplicates and their number for each row in this table -
Fetch multiple images from the server using Django
I am trying to download multiple image files from the server. I am using Django for my backend. Question related to single image has already been answered and I tried the code and it works on single image. In my application, I want to download multiple images in a single HTTP connection. from PIL import Image img = Image.open('test.jpg') img2 = Image.open('test2.png') response = HttpResponse(content_type = 'image/jpeg') response2 = HttpResponse(content_type = 'image/png') img.save(response, 'JPEG') img2.save(response2, 'PNG') return response #SINGLE How can I fetch both img and img2 at once. One way I was thinking is to zip both images and unzip it on client size but I dont think that is good solution. Is there a way to handle this? -
django-filters using ModelChoiceFilter to get value of ForeignKey
I'm trying to use ModelChoiceFilter to filter a database of letters based on the author. Author is a ForeignKey, and I can't seem to get it to display the "name" value of the ForeignKey. Here is what I have: models.py (limited to relevant bits) class Person(models.Model): name = models.CharField(max_length=250, verbose_name='Full Name') ... def __str__(self): return self.name class Letter(models.Model): author = models.ForeignKey(Person, related_name='author', on_delete=models.PROTECT, verbose_name='Letter Author') recipient = models.ForeignKey(Person, related_name='recipient', on_delete=models.PROTECT, verbose_name='Recipient') ... title = models.CharField(max_length=250, verbose_name='Title of Letter') def __str__(self): return self.title letter_filters.py class LetterFilter(django_filters.FilterSet): ... author = django_filters.ModelChoiceFilter(queryset=Letter.objects.order_by('author__name')) class Meta: model = Letter fields = ['author', 'recipient'] I can see that this kind of works. It is indeed limiting and ordering it properly, but instead of the author name being presented in the select box, it's presenting "title" from the letter (but I can tell from the title, in the proper order). What I thought should work is this: fields = ['author__name', 'recipient'] But that too continues to list "title" from Letter instead of "name" from Person. I know it has what I need, because if I do: author = django_filters.ModelChoiceFilter(queryset=Letter.objects.order_by('author__name').values('author__name')) I get exactly what I want! But, it's presented as {'author__name':'Jane Doe'} with fields author or author_name. I … -
how to call a view in one app to a template in another app in django
I am new to Django and I am doing a project which has multiple functionalities. I am planning to break down it into smaller ones. So what I planned to do is to have all the template in main.html and functions into different small apps. --main_app --templates --main.html --app_1 --app1_view.py --app_2 --app2_view.py So my problem is how can I link the main.html templates with the different logic I have written in the views of different apps. Can anyone point me to proper documents or examples. thank you. -
How to make django-treebeard MP_Tree ordering dynamic?
I have a project based on django-oscar (and django-cms), which runs on multiple domains with different SITE_IDs using the django.contrib.sites module. The project is already productive and i can't change the category slugs anymore. The initial requirements did not want a different category sorting for each domain, so i just used Oscars default category implementation. But since Oscars category model/manager is based on django-treebeards materialized path tree implementation, i have to consider a few differences to the usual Django-way of changing the default ordering. Given these two extra fields in the model (which inherits from django-oscars AbstractCategory) class Category(AbstractCategory): # ... order_site_1 = models.IntegerField( null=False, default=0 ) order_site_2 = models.IntegerField( null=False, default=0 ) I can't simply add the ordering to the meta class like: class Category(AbstractCategory): class Meta: ordering = ['depth', '-order_site_{}'.format(Site.objects.get_current().id), 'name'] First, it will ignore this directive since treebeards MP_NodeManager.get_queryset() does not respect custom sorting - for the MP_Tree logic it has to rely on a sorting generated at insertion time (which is stored in path), so this approach would defy the purpose of MP_Tree itself. I also had a look at node_order_by - but as stated in the docs: Incorrect ordering of nodes when node_order_by is enabled. … -
Making nested namespaces in a single Django 2 app
I'm trying to create nested namespaces in my application in Django 2. I'm aware that I am required to use app_name in my urls.py file, but my question is, how would I do it if I wish to nest multiple namespaces in a single app? My app is called account and I wish to have namespaces such as account:create, account:edit ++. How would I approach this in Django 2? Here is a simplified version of what I have tried so far, without success. In my account.urls file app_name = 'account' edit_url = [ path('', edit, name='index'), ] urlpatterns = [ path('', index, name='index'), # edit path('edit/', include(edit_url, namespace='edit')), ] In my root urls file: urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls', namespace='account')), ] -
Django datetime field is not saving
I have this weird issue saving a DateTimeField with Django 1.8 using Mariadb. In a veiws I have: print 'going to update lastposted', topic.lastposted topic.lastposted = timezone.now() topic.save() print 'new topic lastposted time', topic.lastposted the field lastposted is defined in the model as: class Topic(models.Model): #other fields lastposted = models.DateTimeField(blank=True) And when I add a new post into the topic I see in the terminal: going to update lastposted 2018-06-25 03:45:11+00:00 new topic lastposted time 2018-06-25 15:12:08.469940+00:00 But when I see the field in phpMyAdmin the database, it still has the same old value, i.e 2018-06-25 03:45:11. The odd thing is that sometimes the update takes place. What could be wrong here? How can I fix this? -
Django and Chart.js Not Rendering Graph Correctly
So I spent the weekend testing and searching SO and finally got Django and Chart.js working. Kind of. It renders the graph but the data is not correct. When I loop through the object, the results are not what I would expect. Maybe I'm blind from staring at this all weekend. Would appreciate any pointers. Here are my views... class ChartView(LoginRequiredMixin, TemplateView): template_name = 'Books/chart.html' def get_context_data(self, **kwargs): context = super(ChartView, self).get_context_data(**kwargs) qs1 = Class.objects.filter(id__in=self.request.user.userprofile.class.all()).order_by('id') qs2 = Books.objects.filter(department__in=self.request.user.userprofile.books.all()).distinct() context['qs1'] = qs1 context['qs2'] = qs2 return context class ChartData(LoginRequiredMixin,APIView): model = Books authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request, format=None): qs_count = Books.objects.filter(department__in=self.request.user.userprofile.class.all()).count() labels = [] default_items = [] data = { "labels": labels, "default": default_items, } return Response(data) Here's my HTML with the Javascript... {% extends 'base5.html' %} {% block body_block %} <div class="box6"> <h1 class="title">Number of Books By Class</h1> <canvas id="myChart"></canvas> <div> <script> var endpoint = '{% url "Books:chart_data" %}' var defaultData = []; var labels = []; $.ajax({ method: "GET", credentials: 'same-origin', url: endpoint, success: function(data){ labels = data.labels defaultData = data.default var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for i in qs1 %}{{ i.id }},{% … -
Data retrieval from saved instance to serializer in Django Rest Framework
(Django 2.0, Python 3.6, Django Rest Framework 3.8.2) I wanted to know how to retrieve data that's been saved as an instance in a separate model, and include it in a different serializer as a selection field. For example, let's say I have the following saved model instance: { 'id': 7 'email': 'example@example.com', 'favorite colors': 'red','blue','green' } When I go to a separate model to post, I would want to see the following options as a selection: { 'colors_user_id_7_selected': 'red','blue','green' } Where users 1 through 6 may have different favorite colors. How would I set up my model and serializer to obtain this result? I've tried nesting serializers, but that only allowed a user to post new favorite colors and not retrieve the favorite colors of some other specific saved instance. Any help is greatly appreciated. -
Error : Using django email i am sending an email after sending email got an error ? smtplib.SMTPServerDisconnected:[WinError 10054]
I am beginner and use django documentation for sending an email . i am facing a problem after submitting the form means posting the form . i got this error SMTPServerDisconnected at /buggy_app/booking/ and in my terminal i am facing this error smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] Views.py from django.template.loader import get_template from django.conf import settings from django.core.mail import EmailMultiAlternatives class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm models = Booking def form_valid(self, form): car_id = self.request.GET.get('car', '') car = Car.objects.get(id=car_id) car.is_available_car = False car.save() form.save() form.cleaned_data.get('username') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') to_email = form.cleaned_data.get('email') send_emails(first_name, last_name, to_email) return super(BookingView, self).form_valid(form) def send_emails(first_name, last_name, to_email): htmly = get_template('buggy_app/welcome.html') d = {'first_name':first_name, 'last_name':last_name} subject, from_email, to = 'Subject line', settings.EMAIL_HOST_USER, to_email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
Django display paragraph if nothing found
I want that a message gets displayd if no search results are found but somewho im doing it wrong! Is if post in object_list.count == 0 unsuitable? My Django template: {% extends 'quickblog/base.html' %} {% block content %} {% if post in object_list.count == 0 %} <p>No results, sorry :(</p> {% else %} {% for post in object_list %} <div class="post"> <h1><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h1> <p>{{ post.content|linebreaksbr }}</p> <div class="date"> <a>Published by: {{ post.author }}</a><br> <a>Published at: {{ post.published_date }}</a><br> <a>Category: {{ post.category }}</a><br> <a>Tag(s): {{ post.tag }}</a> </div> </div> {% endfor %} {% endif %} -
how to print cvs content in ordered form in django template
here is my django app... it print csv content in django template but not in organised form..(see output).. views.py from django.shortcuts import render import pandas as pd def index(req): df = pd.read_csv("Users\Documents\data\myproject\datanalysis\PastHires.csv") f=df.head() return render(req,'index.html', {'content':f}) <html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{content}} </body> </html> OUTPUT Years Experience Employed? Previous employers Level of Education \ 0 10 Y 4 BS 1 0 N 0 BS 2 7 N 6 BS 3 2 Y 1 MS 4 20 N 2 PhD Top-tier school Interned Hired 0 N N Y 1 Y Y Y 2 N N N 3 Y N Y 4 Y N N but i want like this in my django template Years Experience Employed? Previous employers Level of Education \ 0 10 Y 4 BS 1 0 N 0 BS 2 7 N 6 BS 3 2 Y 1 MS 4 20 N 2 PhD Top-tier school Interned Hired 0 N N Y 1 Y Y Y 2 N N N 3 Y N Y 4 Y N N -
ImportError: No module named site deploying Django with mod-wsgi and httpd
I'm trying to deploy a django project on CentOS 7, but I keep getting ImportError: No module named site on my httpd error log. This is my config file for httpd located at /etc/httpd/conf.d: <VirtualHost *:8008> WSGIProcessGroup programa_registos WSGIDaemonProcess programa_registos python-home=/var/www/html/programa_registos/.env python-path=/var/www/html/programa_registos Alias /static /var/www/html/programa_registos/static <Directory /var/www/html/programa_registos/static> Require all granted </Directory> WSGIScriptAlias / /var/www/html/programa_registos/programa_registos/wsgi.py <Directory /var/www/html/programa_registos/programa_registos> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> My project is located at /var/www/html/programa_registos and my virtualenv at /var/www/html/programa_registos/.env. Here is my wsgi.py file, located at /var/www/html/programa_registos/programa_registos: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "programa_registos.settings") application = get_wsgi_application() -
Django queryset with one-to-many relationships attached in one query
I have a queryset of model A. Each instance of model A is in a one-to-many relationship with model B. I can get the instances of model B associated with an instance of model A by doing A.b_set.all() but is there a way to attach the results of b_set.all() to each instance of a queryset run on A, maybe with an annotation? I am using Django 2.0 Thanks! -
Djanog Nginx, and Gunicorn .sock failed (2: No such file or directory) while connecting to upstream
I am newbie to Python Django, I have create my application successfully and when I try to host my Django application on Ubuntu 16.04 it is not working properly I tried several way and Google it a lot, Please help to escape from this. I followed this URL How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu I have done everything set up properly but it still I didn't succeed on this. Here I share the necessary file for your reference please let me know if I missed out anything. etc/nginx/site-available server { listen *:91; server_name ip-address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/iradmin/django/scm; } location / { include proxy_params; proxy_pass http://unix:/home/iradmin/django/scm/scm.sock; } } etc/inint/gunicorn.confi decription "Gunicorn application server handling scm" start on runlevel [2345] stop on runlevel [!2345] respawn setuid iradmin setgid www-data chdir /home/iradmin/django/scm/ exec python3venv/bin/gunicorn --workers 3 --bind unix:/home/iradmin/django/scm/scm.sock scm.wsgi:application When I completed all the steps for deployment this the following error I am getting in nginx/error.log 2018/06/25 18:59:50 [crit] 32640#32640: *8 connect() to unix:/home/iradmin/django/scm/scm.sock failed (2: No such file or directory) while connecting to upstream, client: 10.200.101.124, server: ip-address, request: "GET / HTTP/1.1", upstream: "http://unix:/home/iradmin/django/scm/scm.sock:/", host: … -
Django group up by foreign keys
So i have two models: class Product(models.Model): name = models.CharField(_('Name'), max_length=200) class Like(models.Model): product = models.ForeignKey(Product, related_name='likes', on_delete=models.DO_NOTHING) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='likes', on_delete=models.DO_NOTHING) What i want, is get ‘base’ products (<5 likes), ‘standard’ products (<10 likes) and the total number of ‘premium’ products. I just cant get in, how should I count fk of each product and then group up them. And do that in 1 query. If you have any suggestions or ideas. python3.6, db:posgtresql, django 2.1 -
Django conditional Subquery aggregate
An simplified example of my model structure would be class Corporation(models.Model): ... class Division(models.Model): corporation = models.ForeignKey(Corporation) class Department(models.Model): division = models.ForeignKey(Division) type = models.IntegerField() Now I want to display a table that display corporations where a column will contain the number of departments of a certain type, e.g. type=10. Currently, this is implemented with a helper on the Corporation model that retrieves those, e.g. class Corporation(models.Model): ... def get_departments_type_10(self): return ( Department.objects .filter(division__corporation=self, type=10) .count() ) The problem here is that this absolutely murders performance due to the N+1 problem. I have tried to approach this problem with select_related, prefetch_related, annotate, and subquery, but I havn't been able to get the results I need. Ideally, each Corporation in the queryset should be annotated with an integer type_10_count which reflects the number of departments of that type. I'm sure I could do something with raw sql in .extra(), but the docs announce that it is going to be deprecated (I'm on Django 1.11) -
Looking to display text for each option in a model form field
I am new to Django, but I'm just looking for a clean way to allow help texts per choice. I have a model form class in forms.py that has 4 fields. One is a drop-down box and the rest are checkbox widgets. Instead of giving the overarching widget/field help_text, I want to give individual hover-over definitions (in the form of help-text, tool tips, or using the title attribute) to the drop down options and checkbox option labels. Before, I did this using 'title = "I put my definition here"' in each option in the template. Is there a way to do this using model forms-- whether it be in the model, form, or when iterating over a field in the template? -
Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused - Executable file not found
I am following the django tutorial from their web site; https://docs.djangoproject.com/en/2.0/intro/tutorial02/ I got a problem on this step; python manage.py migrate I am trying to develop the application in a docker container, so when I run the below command; docker-compose run web manage.py migrate I got this error; Starting docker-django-project_db_1 ... done Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"manage.py\": executable file not found in $PATH": unknown I tried to add the path of the manage.py directory to $PATH but I am still getting the same error. -
How to make Highchart rangeselector buttons load new data?
I am trying to create a website using django, displaying highcharts (highstock) graphs for different ranges of data. I am an advanced python user, though a beginner with javascript. I want the buttons for the data ranges (1d, 1w, 1m, all) to each call a different url when clicked on. I have put the code below, as well as the documentation for rangeSelector buttons. In the example code I have attempted several variations of things I have found online, though none work. Any help is much appreciated! rangeSelector: { allButtonsEnabled: true, buttons: [{ type: 'day', count: 1, text: 'Day', events: { click: function () { return "https://0.0.0.0/daydata"; } }, dataGrouping: { forced: true, units: [['day', [1]]] } }, { type: 'week', count: 1, text: 'Week', events: { click: function () { return "https://0.0.0.0/weekdata"; } }, }, { type: 'month', count: 1, text: 'Month', click: function () { return "https://0.0.0.0/monthdata"; }, dataGrouping: { forced: true, units: [['month', [1]]] } }, { type: 'all', text: 'All', events: { click: function (event) { return "https://0.0.0.0/alldata"; } }, dataGrouping: { forced: true, units: [['month', [24]]] } }], }, https://api.highcharts.com/highstock/rangeSelector.buttons https://api.highcharts.com/highstock/rangeSelector.buttons.events.click Thank you!