Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using custom context processor with django mptt model
I have models with Product and Category. Category is a foriegn key of a product, and Category also self-relates itself for sub-categories. to get a queryset of products with category of which the name contains certain string, I think there should be a more clever way than making it like below (product__category__parent__parent__parent ...... __name__icontains) can someone advise better way? Thanks models.py class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Category(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) class MPTTMeta: order_insertion_by= ['name'] def __str__(self): return self.name def trees(self): ancestors = self.get_ancestors(ascending=False, include_self=True) return ' | '.join(category.name for category in ancestors) context_processor.py def filter_category(request): query = request.GET.get('fq', None) if query is not None: lookups = Q(category__name__icontains=query) | Q(category__parent__name__icontains=query)\ | Q(category__children__name__icontains=query) | Q(category__parent__parent__name__icontains=query) results = Product.objects.select_related().filter(lookups) else: results = Product.objects.all() context = { 'results': results } return context -
Syntax Error path(..., ..., name='...') Django
I have a problem with my urls.py file in Django: from django.urls import path from django.conf.urls import include from .views import accueil, lire_article urlpatterns = [ path[(r'^$', 'accueil', name='accueil'), path[(r'^(?P<slug>.+)$', 'lire_article', name='blog_lire'), ] It says: path[(r'^$', 'accueil', name='accueil'), SyntaxError: invalid syntax but I don't know what is the error, could you help me please ? -
multiple foreign key in a model (One to Many mapping) django python? [duplicate]
This question already has an answer here: Any alternatives for OneToMany or ManyToOne in Django 1 answer I am trying to map a relationship between a gym model and its offer and events model. The idea is 1 gym can have many offers and many events. But 1 offer cannot belong to many gyms and 1 event cannot belong to many gyms. So, with the look of things, it is a one to Many relation. So far so good. This is my first time working with the Django ORM, so my approach might be a bit naive. I would like to essentially have tables in my db such as a table for gym, table for events and a table for offers. The offer and event table is connected to the gym through the gym id.How can i achieve that ? Because so far i see some pretty strange things in my Django admin page.This is what i tried so far class Program(models.Model): id = models.AutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: ordering = ('last_updated',) def __str__(self): return "%s %s" % (self.id, self.price) class Offer(models.Model): id = models.AutoField(primary_key=True) created = … -
Database query vs store in table
I have a few models. Game: pk: id ...other GameSession (Manyto1 with game): pk: id game: game_id ...other ChatSession (1to1 with GameSession): pk: id session: game_session_id ...other Would it be better to store the information in multiple models, or query for the correct object? Aka To get the chat session for a given game session, should I query something like select * from chatsessions where session=INT or should I store the chatsession id in the GameSession model so it doesn't have to query every time it needs to access the chat session? -
The Django test client: polls app part 5
I am following the polls app and I am copying every thing making sure I have 100% the same code they have but when I use response = client.get(reverse('polls:index')); I get a huge error and none of the notes are making sense to me I was told by someone it has to do with my Views but I looked and the Django site and its 100% the same as mine I will attach a photo of the error and some of the code where I think there is the problem. enter image description hereThank you in advance -
Send a large raw JSON string from our database as a Response directly to the frontend without parsing/decoding it
We have large JSON blobs stored in the database we want to pass to the frontend using DRF. Instead of parsing that JSON string then having it decode, could we have it just return the JSON string itself? For example, is there a way for this to to be sent to the frontend: Response({ 'json': '{"example": "json-from-database"}' }, status=status.HTTP_200_OK) Right now this will create an undesired JSON response that looks like this: { 'json': '{"example": "json-from-database"}' } We want it to create a JSON response that looks like this: { 'json': {"example": "json-from-database"} } Is there a way to send 'raw' JSON response to the frontend without it having to parse/decode our existing JSON string? At the moment we are using json.load. -
How to rank a list of users from a queryset in templates?
Hello Awesome People! have a list of users displaying in templates like the following. {% for u in users_list %} {{u.name}} {% endif %} How can I rank two or more users at the top If I want to? For instance with one user, when the current user visits that list, I want to rank him in the top without a specific ordering. 1) me 2) user2 3) user3 -
How to debug Django segmentation faults?
I think after some update my Django app has started to segfault time after time. Below is my attempt to debug using gdb, however I cannot see the root cause: # gdb -ex=r --args ../pyenv/bin/python3 -X faulthandler manage.py runserver 127.0.0.1:8000 GNU gdb (GDB) 8.1.1 Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-pc-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ../pyenv/bin/python3...(no debugging symbols found)...done. Starting program: /home/narunas/website/www/pyenv/bin/python3 -X faulthandler manage.py runserver 127.0.0.1:8000 [Thread debugging using libthread_db enabled] Using host libthread_db library "/usr/lib/libthread_db.so.1". Performing system checks... System check identified no issues (0 silenced). August 27, 2018 - 15:59:58 Django version 2.0, using settings 'website.settings.dev' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7de107b in kill () … -
Setting 'Inline' js and css for bokeh in django framework
I'm trying to run a project downloaded from the link django-bokeh-example. When I ran the server and load the webpage i see only a blank page on inspecting i got to know that there's some error in loading the javascript and css. After googling i came to know that I have to set some kind of static parameters . But, I didn't really get how and where to set these parameters below is my code. I tried to add the from bokeh.resources import INLINE, which didn't help. Could someone please put some light on this views.py from django.shortcuts import render, render_to_response from django.http import HttpResponse from bokeh.plotting import figure, output_file, show from bokeh.embed import components from bokeh.resources import INLINE def debug(x, name): print('\n' * 5) print('{} = {}'.format(name, x)) print('type({}) = {}'.format(name, type(x))) print('\n' * 5) def home(request): return render_to_response('home_links.html') def plot(request): x = [1, 2, 3, 4, 5] y = [6, 7, 2, 4, 5] # output to static HTML file output_file("lines.html") # create a new plot with a title and axis labels p = figure(title="simple line example", x_axis_label='x', y_axis_label='y') # add a line renderer with legend and line thickness p.line(x, y, legend="Temp.", line_width=2) # Store components script, div … -
Get user name not just ID in View List
I am programming on web app where I am trying to display in List View user's name but I always get just id. Here is the code of List View: activities = Activity.objects \ .annotate(day=ExtractDay('created'), month=ExtractMonth('created'), year=ExtractYear('created'))\ .values('user', 'day', 'month', 'year') \ .annotate(total=Count('user')) \ .order_by('user') \ Getting user: for activities_data in activities: user = activities_data['user'] Code of model: class Activity(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) I really try everything but I don't know how to deal with that. Could you help me how to get full user name? -
Create and UpdateView with foreign key related model in Django CBV
I got 1 app "portfolio" with 2 models, the 2nd one has a FK with first and I need (create and update) view of that. I have the complete CRUD for the first model but I no have idea to get the same result with fk model. I'm looking for a create and update view with both. But I can't get access for proyects in a album form, so in that way for choosing the FK from projects to get related album to one of all projects created models.py from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField # Create your models here. class Project(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, default=1) name = models.CharField(verbose_name='Nombre del proyecto', max_length=200) client = models.CharField(verbose_name='Nombre del cliente', max_length=200) description = RichTextField(verbose_name='Descripción') start = models.DateField(verbose_name='Fecha de Inicio', null=True, blank=True) ending = models.DateField(verbose_name='Fecha de Finalización', null=True, blank=True) order = models.SmallIntegerField(verbose_name="Orden", default=0) created = models.DateTimeField(verbose_name='Fecha de creación', auto_now_add=True) updated = models.DateTimeField(verbose_name='Fecha de modificación', auto_now=True) class Meta: verbose_name = 'Proyecto' verbose_name_plural = 'Proyectos' ordering = ['-start', 'order'] def __str__(self): return self.name class Album(models.Model): project = models.ForeignKey(Project, on_delete = models.CASCADE) title = models.CharField(verbose_name='Título de la imagen', max_length=200, null=True, blank=True) image = models.ImageField(verbose_name='Imagen', upload_to='portfolio') created = models.DateTimeField(verbose_name='Fecha … -
ImportError while deploying Django app to heroku
What I am trying to do ? I am trying to deploy my Django app to heroku. What is the problem ? After uploading my app to heroku. I try to access it but I get an Application Error which also mentions this command heroku logs --tail to get the details of the error. So I run the command and I get a log with the following details (It shows a lot of content in the log but I have shown only a few): 2018-08-27T20:03:18.139298+00:00 app[web.1]: [2018-08-27 20:03:18 +0000] [11] [ERROR] Exception in worker process 2018-08-27T20:03:18.139347+00:00 app[web.1]: Traceback (most recent call last): 2018-08-27T20:03:18.139351+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2018-08-27T20:03:18.139356+00:00 app[web.1]: worker.init_process() 2018-08-27T20:03:18.139358+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process 2018-08-27T20:03:18.139360+00:00 app[web.1]: self.load_wsgi() 2018-08-27T20:03:18.139361+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2018-08-27T20:03:18.139363+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-08-27T20:03:18.139365+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-08-27T20:03:18.139366+00:00 app[web.1]: self.callable = self.load() 2018-08-27T20:03:18.139368+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2018-08-27T20:03:18.139370+00:00 app[web.1]: return self.load_wsgiapp() 2018-08-27T20:03:18.139371+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2018-08-27T20:03:18.139373+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-08-27T20:03:18.139375+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app 2018-08-27T20:03:18.139377+00:00 app[web.1]: __import__(module) 2018-08-27T20:03:18.139379+00:00 app[web.1]: File "/app/ditook/wsgi.py", line 16, in <module> 2018-08-27T20:03:18.139380+00:00 app[web.1]: application = get_wsgi_application() 2018-08-27T20:03:18.139382+00:00 app[web.1]: … -
'ERROR: relation does not exist at character', error in celery with django
I have a model called UserApp, of which I make a query from an asynchronous task with Celery, but I get the following error from the output of the docker compose. postgres_1 | ERROR: relation "users_userapp" does not exist at character 536 celery_1 | django.db.utils.ProgrammingError: relation "users_userapp" does not exist This is the code of the task: @app.task(bind=True, default_retry_delay=50, max_retries=10, ignore_result=False) def send_reset_password_email_task(self, muser): user = UserApp.objects.get(pk=muser.get('id')) print("send_reset_password_email_task user: ",user) that query from the views runs without problems, in the same way if I call the task synchronously without the delay from the view, it also runs without problems, I have already run the migrations and the problem is not fixed either. I would really appreciate the help. -
Generate test data in Django using loaddata
I'm working in a Django project, and I want to implement an easy way to generate a costum number of object in the database for testing purposes. These are my models: class Author(models.Model): name = models.SlugField( max_length=150, ) last_name = models.CharField( max_length=100, ) class Book(models.Model): author = models.ForeignKey( Author, on_delete=models.CASCADE, ) name = models.CharField( max_length=100, ) So, I need to find an easy way to generate a custom number of new instances of the Author and the Book models. I think that maybe I can use the loaddata function of django, to read a json file in which I include the following information: { "authors_number": 1000, "books_number_per_author": 4 } And then, by read this file, I a script will generate 1000 instances of the Author model, and will generate 4 instances of the Book model for each author. (The author name and the books name can be random strings.) It's ideal if this script runs by running a command line command, for this reason I think that maybe the loaddata function could be used for that, but I don't know if this command requires an specific structure of the json file. How can I generate all those objects in a … -
Do django Class Based Views, CreateView and UpdateView, clean the data behind the scenes?
I know the data is validated. But I can't figure out if the CBV clean the data. When using class className(forms.Form): OR class className(forms.ModelForm) you add (inside your CBV): def post(self, request): form = HomeForm() if form.is_valid(): text = form.cleaned_data['p] Can someone tell me if you have to also clean your data manually of if the CreateView and UpdateView clean the data behind the scenes? -
Python 3.7 with django 1.11
I've created a new django project, when I run the server I get the error below: from django.urls import path ImportError: cannot import name 'path' I seem to be running both django 1.11 and 2.0, when i try create the folder in a virtual environment it installs python 3.7 which sets django 2.0 as the default. Is there a way around this? Thanks -
deploying a django app with nginx, gunicorn, daphne (for channels 2) and supervisor
As it follows from the title I'm trying to deploy a django application with the above-mentioned stack of technologies. We're using django for the serverside and angular 6 for the frontend. I'm doing this for the first time in my life and there are some things that are not quite clear to me, so correct me if I say something weird. I'm using Nginx to serve static. The config looks as follows: serverside_nginx_static.conf server { listen [::]:80 ; root /home/user/serverside_deployment/static/; index index.html index.htm index.nginx-debian.html; client_max_body_size 4G; access_log /home/user/serverside_deployment/logs/nginx-access.log; error_log /home/user/serverside_deployment/logs/nginx-error.log; location / { try_files $uri $uri/ /index.html; proxy_set_header Host $http_host; proxy_redirect off; } error_page 500 502 503 504 /500.html; location = /500.html { root /home/user/serverside_deployment/static/; } 1.1 I'm also using Nginx to communicate with gunicorn which in turn communicate with the django app itself. The appropriate config looks like this: serverside_nginx.conf upstream mtt_server { server unix:/home/user/serverside_deployment/serverside_env/run/gunicorn.sock fail_timeout=0; } server { listen 8000; server_name 192.168.10.98; client_max_body_size 4G; access_log /home/user/serverside_deployment/logs/nginx-access.log; error_log /home/user/serverside_deployment/logs/nginx-error.log; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://mtt_server; break; } } error_page 500 502 503 504 /500.html; location = /500.html { root /home/user/serverside_deployment/static/; } } I'm using supervisor to start the … -
UnicodeDecodeError with Django Rest Framework on Model's __str__ field
I'm banging my head on the table regarding this error, and I've scoured the internet but either 1) haven't been able to find the answer or 2) am not knowledgable enough to figure out what's going on. The tldr summary of my problem: When I store a non-ASCII character (such as è) in a models.TextField and serialize it with serializers.CharField, I do not encounter and problems. However, if I have a str method on the model that returns that same text field, upon serialization I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128) First of all... I'm running Python 2.7.10 on OS X. I'm using Django==1.11.7 and djangorestframework==3.7.3. My LANG and LC_ALL environment variables are both set to en_US.UTF-8. Lastly, I'm using PostgreSQL 9.5.6 and I verified that my database is encoded in UTF8. The details of my problem: I have a simple model as shown below. It has a name variable that is a TextField as well as a __str__ method that simply returns self.name. I also have defined a testing variable that also simply returns self.name for demonstration purposes. from __future__ import unicode_literals from django.db import models from … -
Using Django, the selected option of a dropdown menu is not passed to the server
I'm using Django and jQuery. My forms.py: CARPET_TYPE = ( ('', 'Select a carpet type'), ('NRM', 'Normal'), ('SLK', 'Silk'), ('WOL', 'Wool'), ('PER', 'Persian') ) class CalculationForm(forms.Form): carpet_types = forms.ChoiceField(initial='', choices=CARPET_TYPE, label='Carpet Types',) length = forms.FloatField(min_value=0) width = forms.FloatField(min_value=0) My calculation_form.html(which is used as block content in my index.html): <form action="{% url 'cleaners:pick_up' %}" method="POST" id="main_form" class="probootstrap-form"> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col-md"> <div class="probootstrap-size-wrap"> <label for="{{ form.carpet_types.id_for_label }}">{{ form.carpet_types.label_tag }}</label> <!-- <label for="id_label_single" style="width: 100%;"> --> <select class="js-example-basic-single js-states form-control" id="id_label_single" name="dd-carpets" style="width: 100%;"> {% for choice in form.carpet_types.field.choices %} <option value="{{choice.0}}" name="{{form.carpet_types.html_name}}">{{choice.1}}</option> {% endfor %} </select> <!-- </label> --> </div> </div> </div> <!-- END carpet type row --> <div class="row carpet-length"> <div class="col-md meters-column"> <div class="form-group" id="calc_main"> <label for="{{ form.length.id_for_label }}">{{ form.length.label_tag }}</label> <div class="probootstrap-size-wrap"> <input type="text" id="length" class="form-control" name="{{ form.length.html_name }}" placeholder="Enter the length of your carpet"> </div> </div> </div> </div> <!-- END length row --> <div class="row carpet-width"> <div class="col-md meters-column"> <div class="form-group" id="calc_main"> <label for="{{ form.width.id_for_label }}">{{ form.width.label_tag }}</label> <div class="probootstrap-size-wrap"> <input type="text" id="width" class="form-control" name="{{ form.width.html_name }}" placeholder="Enter the width of your carpet"> </div> </div> </div> </div> <!-- END width row --> <input type="hidden" id="service_cost" name="service_cost" value=""> <div class="row"> <div class="col-sm-12 calculate"> … -
pytest-django: No such database error
I understood that the default behaviour for pytest-django is to create the test database by applying migrations and remove the database after the test run. I have NO conftest.py file just a pytest.ini as follows: DJANGO_SETTINGS_MODULE = myproject.test_settings python_files = tests.py test_*.py *_tests.py I run pytest with a sample test that accesses the database as follows: pytest -v test_db_access.py I get an error saying: E OperationalError: ERROR: No such database: test_database If I create a conftest.py to point to my existing database, my tests all run fine. My question is - how can I avail of pytest-django default behaviour? What do I need apart from my pytest.ini shown above? I want pytest-django to: Look at settings in pytest.ini Create a test database Run migrations Run tests Drop the database Version Info: Python 2.7 Django 1.11.12 djangorestframework Version: 3.8.2 Any help appreciated. -
Django, CreateView: pass form argument to reverse_lazy
To redirect the user after filling out the CreateView form I would like to access an argument from the form and pass it to the reverse_lazy function. How can I access the parameters of the form within CreateView? I actually use the argument I'm looking for to pass it to the form itself (self.request.META.get('HTTP_REFERER').split('/')[-1]), but seem not to be able to use this logic in reverse_lazy. get_form_kwargs also seems not to achieve the result: views.py class PieceInstanceCreate(LoginRequiredMixin, CreateView): model = PieceInstance fields = ['version', 'piece_image', 'status'] def form_valid(self, form): obj = form.save(commit=False) obj.piece = Piece.objects.get(id=self.request.META.get('HTTP_REFERER').split('/')[-1]) return super(PieceInstanceCreate, self).form_valid(form) def get_form_kwargs(self): kwargs = super(PieceInstanceCreate, self).get_form_kwargs() return kwargs['piece'] success_url = reverse_lazy('piece-detail', kwargs={'pk': get_form_kwargs(self)}) urls.py path('piece/<int:pk>', views.PieceDetailView.as_view(), name='piece-detail') -
modify dataTable Editor to save updated data to database
my dataTable worked properly to display data, I want to add create, edit, and remove buttons to get updated data from client and save updated data to database. Im struggling of writing a view to update these updated data from client to database. And I want to do something like that link below. Please let me know if you need more details. Any helps will be highly appreciated!! https://editor.datatables.net/examples/advanced/deepObjects.html views.py @csrf_exempt def ajax_projects(request): if (Employee.objects.filter(Q(emp_type__icontains = "user") | Q(emp_primary__icontains = 2)).filter(user__username__icontains = request.user.username)): projects = Project.objects.filter(user__id__icontains = request.user.id) #data = serializers.serialize("json", projects, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) data = serializers.serialize("json", projects, indent=2) return HttpResponse(data, content_type = "application/json") elif (Employee.objects.filter(emp_type__contains = "admin").filter(user__username__contains = request.user.username)): projects = Project.objects.all() data = serializers.serialize("json", projects, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) return HttpResponse(data, content_type = "application/json") urls.py url(r'^ajax/projects/$', views.ajax_projects, name = 'ajax_projects'), json format [ { "model": "polls.project", "pk": 2, "fields": { "user": [ "abc1" ], "pro_no": "9.1", "pro_section": "9.1 ABCD", "pro_description": "SUPPORT ABCDEFG", "pro_ID": "001332, "percent": 0.04, "employee": [ "NGUYEN" ] } } ] js code var editor; $(document).ready(function(){ editor = new $.fn.dataTable.Editor({ ajax: { edit: { type: "POST", url: "ajax/projects/", contentType: "application/json", data: function(d){ return JSON.stringify(d); }, traditional: true, dataSrc: '' }, }, table: "#project_table", fields: [{ label: … -
How to write site identity for django application?
I have developed an application in Django. I have to enter url correctly to reach my site. But it is never displayed when I enter the name in google. How to use SEO for my application. What additional thing I need to do so that my Django application appear in google search index by keyword without typing the whole URL -
Move objects with mouse
I would like to have objects that user can move with mouse from place to place (like moving the cards between columns in Trello or GitHub projects). How do I approach this in Django? -
How to add instance of a model having foreign key of other model Django
I am new to django and I am stucked in a problem, I have extended user model in which there are two user teacher and student. The teacher is added from the admin site while the student is added by teacher through csv_files. The models structure is as follows: class User(AbstractUser): is_student=models.BooleanField(default="False") is_prof=models.BooleanField(default="False") class Teacher(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) designation=models.CharField(max_length=30) class Student(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) teacher=models.ForeignKey(Teacher,on_delete=models.CASCADE,default="") batch=models.CharField(max_length=30) Now, as the user is logged in, I want the user to be teacher and it should add student.As during login User model is logged in, how can I assure the specific teacher is adding student and that particular teacher is also to be saved in student model as it is referring(foreign key) teacher model.I now it has to be done through primary keys but how can I do.I searched a lot and can't get anything need some good approach.