Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a Complex Single Page Application using Django
This question is a bit broad but I haven't found any answers. So, I have been working on some projects with Django for a while (All were Multi Page Apps). But I have been doing some research on single-page applications and want to create one for my next project. So here is a basic list of the features that I want my single-page app to implement Extensive use of a database Extensive use of data processing A rich UX with many different screens, lots of media, and a large amount of interactive features The ability for users to add data with some sort of forms. So I want this site to be very interactive and data/dynamic content focused. The best way I can describe it is that there will be the main app that houses everything and then "sub-apps" that have more specific functionality (for example; housing a game, or a messaging system, etc.) and to have these "sub-apps" be integrated in to the main app so that they can be used together or at different times without reloading the page, kind of like how you can have different programs open on your desk top (like having a web browser, … -
Using Django to Create Tabs
I'm new to Django, as well as HTML, CSS, etc. I'm wondering what is the simplest way to create tabs. I can't seem to find a simple explanation for this. In my project, I have a python file named forms.py where I have a class which generates text-fields: class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) for name in listNames: locals()[name] = forms.CharField(label=name, max_length=100) My goal is to have this code in one tab, but also give a user the option of adding a new tab with the text-fields from this class being added in. What approach would make the most sense here? I tried looking at this: http://django-suit.readthedocs.io/en/develop/form_tabs.html , but I didn't really understand what I was looking at. It does seem I need to add something to my admin.py file though? Thanks in advance! -
Queryset filters: Q objects and filters auto generation (Django)
For example I have an a function for generating filters parameters: def get_filters_parameters(name=None, mother_age=None, surname_not=None): filters = {} if name: filters['name'] = name if mother_age: filters['mother__age'] = mother_age # if surname_not: # here we need `~Q(surname = surname_not)` expression return **filters my_filters = get_filters_parameters(name='ululu') qs = MyModel.objects.filter(**my_filters) I need to use Q objects in my filters parameters for surname_not field. Does anyone knows how I can do that? -
How to read query string parameters in restless (Django)?
I'm working on a blog application with Django and using restless. For example, I have an URL like this... GET /api/1.0/articles/?content=Base64EncodedJSON&author=Base64EncodedJSON&content=Base64EncodedJSON Then how can I read the query string parameters in restlest? -
How to return JSON response for exceptions in Python?
I am using exception handling classes e.g., werkzeug.exceptions.BadRequest to raise exceptions when they occur. I want to return a JSON to the user when an exception is encountered. For example, { 'http_response': 400, 'message':'error message' } By default, the user gets an HTML error message like: <title>400 Bad Request</title> <h1>Bad Request</h1> <p>error message</p> Should I create a custom subclass of BadRequest and JSONify the response there? I am reluctant to do it this way because I would have to create subclasses for all the types of exceptions there are. Is there any existing library or a better way to do this? -
Heroku - Reactjs not rendered
I have deployed my Django, rest-framework, reactjs app to heroku with this as reference. Also, I have followed this procedure to set up my postgre sql database. Now, the URL to access the API are working fine. So, I can go to /api/.... and they seem to work. Now the react's URL which is / is not rendering anything. What can be the possible reasons for that and how do I fix that?? -
Django, Response using List of Dict
I'm looking to be able for response using list of dict like following bio_dict = [{'subject' : 'Name', 'value' : 'MyName'},\ {'subject' : 'Birth Date', 'value' : '1998-1-1'},\ {'subject' : 'Sex', 'value' : 'M'}] def index(request): response = { bio_dict['subject'] : bio_dict['value'] } return render(request, 'page.html', response) but that response return: TypeError: list indices must be integers or slices, not str Using python 3.6 and django 1.11 -
How can I pass a parameter from the view into a modelForm in django?
My goal here is to have the user upload a document but my program names the document automatically. Essentially, from the view I pass the name into the form, where that name is placed in the 'descriptions' field of my Document model. Thanks! Views.py def testing(request): if request.method == 'POST': name = 'testing' form = DocumentForm(request.POST, request.FILES, description=name) if form.is_valid(): form.save() return redirect('landing') else: form = DocumentForm() return render(request, 'testing.html', { 'form': form }) forms.py class DocumentForm(forms.ModelForm): def __init__(self, *args, **kwargs): description = kwargs.pop('description') super(DocumentForm,self).__init__(*args, **kwargs) self.fields['description'].initial = description class Meta: model = Document fields = ('description', 'document', ) models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) -
Django - object.id in {% static %} tag not working
I have stumbled upon a very weird thing. I am using Django 2.0.7 Having the following code in my template: <img src="{% static 'external_page/assets/img/profile_pics/'|add:instructor.id|add:'.jpg' %}"> On deployment it returns (which is wrong): <img src="/static/.jpg"> However if I for instance would change: |add:instructor.id To: |add:instructor.first_name It works as it should, but with first_name instead of id. Even weirder is that not long before this, I have the following code. ...onclick="window.location='{% url 'profile' instructor.id %}'" Which works fine. Here is the whole code segment for a more holistic view: template.html <div class="team"> <div class="row row-instructor"> {% for instructor in instructors %} <div class="card card-signup col-md-4" data-background-color="orange" style="cursor: pointer;" onclick="window.location='{% url 'profile' instructor.id %}'"> <div class="team-player"> <img src="{% static 'external_page/assets/img/profile_pics/'|add:instructor.id|add:'.jpg' %}" alt="Thumbnail Image" class="rounded-circle img-fluid img-raised"> <h4 class="title">{{ instructor.first_name }} {{instructor.last_name}}</h4> -
Django: minimize database hits with QuerSets
I've got this custom admin command to remove some old records. QuerySets are lazy so I was wondering if there is a way to optimize this code because at the moment there are four hits to database in --dry-run mode: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--dry-run', action='store_true') def handle(self, *args, **options): threshold = timezone.now() - timezone.timedelta(5) try: if options['dry_run']: queryset = Mointor.objects.filter(created__lt=threshold) if queryset.exists(): msg = f'{queryset.count()} record(s) will be deleted, from {queryset.first().created} to {queryset.last().created}' else: msg = 'No records to delete' else: Monitor.objects.filter(created__lt=threshold).delete() msg = 'OK' except Exception as e: raise CommandError(e) self.stdout.write(msg) -
How to get related set in django(Many to many field)
I have an Employee model class Employees(models.Model): name = models.CharField(max_length=200, help_text="Enter the name of the employee") location = models.ManyToManyField('Location') def __str__(self): return self.name' And a Location model class Coverage(models.Model): name = models.CharField(max_length=300, help_text="Enter employee location") time_needed = models.IntegerField(help_text="Enter time needed to get to work. eg (40 = > 40 minutes)") def __str__(self): return self.name How do i access coverage - time_needed from my templates with ( employees = Employees.objects.all()) I have tried {{employees.location.time_needed}} but it doesn't work. Any good answer would be appreciated. ps : this is just a snippet of a bigger model class -
how to render the django usercreation form help text list using django widget tweaks
In django I implemented a custom view for user creation form using jinja templating language and django-widget-tweaks. but in form there the help text for password field is list item which is rendering as raw text. is there a way to fix that. here is the image which shows the ul element rendering as raw text and here is a code -
Permission denied on running collectstatic with django-pipeline on Heroku
I have a Django 2.0 project that uses django-pipeline for static files with pipeline.compilers.sass.SASSCompiler compiler. It works perfectly in development, but when I deploy it on Heroku, I get the following error on running collectstatic: pipeline.exceptions.CompilerError: [Errno 13] Permission denied: '/app/node_modules/.bin' Pipeline configuration: PIPELINE['SASS_BINARY'] = '/app/node_modules/.bin node-sass' package.json: { "name": "myprojectname", "version": "1.0.0", "engines": { "node": "8.11.3" }, "description": "myprojectdescription", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "postinstall": "bower install" }, "dependencies": { "bower": "^1.8.4", "node-sass": "^4.9.2", "yuglify": "^2.0.0" } } bower.json: { "name": "myprojectname", "main": "index.js", "private": true, "ignore": [ "**/.*", "node_modules", "bower_components", "app/static/bower_components", "test", "tests" ], "dependencies": { "bootstrap4": "bootstrap#^4.1.1", "bootstrap-datepicker": "^1.8.0", "font-awesome": "^5.1.0" } } I tried to install sass ("sass": "^1.9.0") with npm and change my pipeline config to PIPELINE['SASS_BINARY'] = '/app/.heroku/node/bin sass' But it still fails with the same error: pipeline.exceptions.CompilerError: [Errno 13] Permission denied: '/app/.heroku/node/bin' From logs and heroku run bash I can see that all listed node packages where successfully installed. How could I fix this permission error? -
In Django Factory Boy, is it possible to specify custom FactoryOptions for a certain instance?
I'm writing unit tests for a Django app which use factory_boy test fixtures. In some cases, one fixture might try to create an object that was already created by another fixture, which leads to error messages similar to the following: django.db.utils.IntegrityError: duplicate key value violates unique constraint "lucy_web_sessiontype_title_c207e4f8_uniq" DETAIL: Key (title)=(Postpartum Doula Support) already exists. To avoid this, my first inclination is to write a try..except block, like so: try: SessionTypeFactory(title='Welcome') except psycopg2.IntegrityError as e: pass However, it seems like it would be more elegant to use the django_get_or_create option described at http://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create. However, as far as I can tell from http://factoryboy.readthedocs.io/en/latest/reference.html#factory.FactoryOptions, options specifie in the factory's Meta class will apply to all instances, whereas I would only like it to only apply to this instance. Is it possible to specify these options in the constructor? -
Appending a single character suffix to the end of the image id, and before the file extension in a django template
Iam using the imgur API for managing images on a website I am running. to acquire the thumbnail link you have to append a single character suffix to the end of the image id, before the file extension as described here. Is there a way to do this in the template language, or is it only possible solution as following? for image in images: url = image.link.rsplit('.', 1) image.thumbs = url[0] + 'm.' + url[1] -
Another Django "Apps aren't loaded yet"
I'm very new to both django and python and I have run in too an error to which I do not understand. The runserver command works, and I can enter my website on localhost. But the Shell is broken somehow. Im using PyCharm on an Conda virtual env as far as I know. I'm using mac os high sierra. Error when trying to import a model Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from catalog.models import Routines Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/fridalarsson/PycharmProjects/hapionline6/catalog/models.py", line 3, in <module> from senders.models import Senders File "/Users/fridalarsson/PycharmProjects/hapionline6/senders/models.py", line 4, in <module> class Senders(models.Model): File "/Users/fridalarsson/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/fridalarsson/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/Users/fridalarsson/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The model in question looks like this: from __future__ import unicode_literals from django.db import models from senders.models import Senders class Routines(models.Model): routine_id = models.AutoField(primary_key=True) sender_id = models.ForeignKey(Senders, on_delete=models.CASCADE, default=1) in_routine = models.CharField(max_length=20) out_routine = models.CharField(max_length=20) mail_class = models.CharField(max_length=5) last_change = models.DateTimeField(auto_now=True) def … -
Django photo upload UnicodeDecodeError
I'm currently using DRF for my application. I managed to send the .jpg file to the server and retrieve it using request.FILES. But when I try to set my object's photo to the image, it gives me a unicode error. Pls help. Traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response response = response.render() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/renderers.py", line 105, in render allow_nan=not self.strict, separators=separators File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/utils/json.py", line 28, in dumps return json.dumps(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 52, in default return obj.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte [12/Jul/2018 00:16:07] "POST /users HTTP/1.1" 500 107175 sample usage: - I already retrieved the photo from request.FILES and it prints file.jpg @staticmethod def create_user_type(user_type, data, photo): if user_type == "Driver": driver = Driver.objects.create(**data) driver.photo = photo driver.save() return driver … -
Filter a django queryset based on a custom function
I'm actually using Mongo as my DB and mongoengine as a datamapper. My models.py looks like so: class TestResultQuerySet(mongoengine.queryset.QuerySet): def filter_by_status(self, status): return self(data__deviceStatus=status) def another_custom_filter(self, **params): return self('here I would like to somehow use my custom conditional function' ) class TestResult(mongoengine.Document): data = mongoengine.DictField() meta = {'queryset_class': TestResultQuerySet} Now using my another_custom_filter I want to select only those json files from my DB that satisfy a very complex condition. Whether the condition is satisfied or not must be determined by a boolean function. This function is supposed to parse a json (json objects are deeply nested) that is passed to it and return True or False. So basically, that's what I would normally do using the native filter function: filter(boolean_cond_function, iterable) In my case boolean_cond_function is pretty complicated, and I would like it to work inside the filter method that I revoke on the object manager: TestResult.objects.another_custom_filter(). The problem is that the function must operate on a queryset, not on a list of jsons. I know there have already been questions like that on the site but they are somewhat old and not that informative. I want to believe that there's a sensible way of doing what I want … -
Sort the queryset in an arbitrary order
I have such a template to present the blocks from database <div class="panel panel-default"> <div class="panel-heading"> <a style='font-size:18pt' href="article/list/{{ b.id }}">{{ b.name }}</a> <span class='pull-right'>{{ b.admin }}</span> </div> <div class="panel-body"> {{ b.desc }} </div> </div> the data model: class Block(models.Model): STATUS = ( (1, 'normal'), (0, 'deleted'), ) name = models.CharField("block name", max_length=100) desc = models.CharField("block description", max_length=100) admin = models.CharField("block admin", max_length=100) status = models.IntegerField(choices=STATUS) class Meta: ordering = ("id",) def __str__(self): return self.name I retrieve the data as In [2]: from article.models import Block In [3]: blocks = Block.objects.all() In [4]: blocks Out[4]: <QuerySet [<Block: Concepts>, <Block: Reading>, <Block: Coding>, <Block: Action>]> I want to present the data as an arbitrary order of ['concept','code', 'read', 'action'] rather than by id, By observing, I find that this could achieved by order its second letter, In [7]: sorted(l, key=lambda item: item[1], reverse=True) Out[7]: ['concept', 'code', 'read', 'action'] How could sort the queryset this way? -
how to show a django application inside a site in wordpress
I have a site made in wordpress and i´d like to show my django application inside this site. I don´t know how to do that. How do call my django application and show it inside the site. -
django rest framework token authentication and queryset
I want to filter using token authentication.. if remove get_queryset, get all TodoList author and working at postman. but I want to filter user like get_queryset. todo app in views.py class TodoList(generics.ListCreateAPIView): serializer_class = TodoSerializer permission_classes = () #queryset = Todo.objects.all() def get_queryset(self): return Todo.objects.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) and using Httpie, I get json I want! (myvenv) D:\django\todo_project>http GET http://localhost:8000/todo/ "Authorization: Token 7681fc35d7fb9fdb20dbad65ca8220b3ca12c1e6" HTTP/1.0 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json [ { "content": "todo!", "timestamp": "2018-07-11T10:06:27.710916Z", "title": "todo!", "updated": "2018-07-11T10:06:27.710916Z", "user": "user3" } ] but using postman, error occurs.. I think when filting, authentication is not working, so user is AnnoymouseUser How can I filter request user??? -
Incorrect blog count in Django
I am trying to get the sum of count of posts and count of likes on all the posts of an author in views.py, but it is giving incorrect value. I have even attached the corresponding SQL query. Can someone guide me on how to get the correct count of posts ? models.py class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='posts') slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) views.py def get_queryset(self): return(Post.objects.filter(published_date__lte=timezone.now()) .annotate( blog_count = Count('author_id__posts')) .annotate( author_total_likes=Count('author__posts__likes'), score = F('blog_count')+F('author_total_likes') ) ).order_by('-published_date')) SQL SELECT *** FROM "blog_post" INNER JOIN "auth_user" ON ("blog_post"."author_id" = "auth_user"."id") LEFT OUTER JOIN "blog_post" T3 ON ("auth_user"."id" = T3."author_id") LEFT OUTER JOIN "blog_post_likes" ON (T3."id" = "blog_post_likes"."post_id") WHERE "blog_post"."published_date" <= '''2018-07-11 15:38:50.950986''' GROUP BY "blog_post"."id", "blog_post"."author_id", "blog_post"."slug", "blog_post"."created_date", "blog_post"."published_date", ORDER BY "blog_post"."published_date" DESC -
Value Error: Too many values to unpack django
I am creating a filterable search page in django that allows users to search the database based on people that match some or all of the requirements in the form. Because I don't know which attribute they will select My views.py class SearchFilter(View): form_class = SearchByFilter initial = {'tattoo': False, 'scar_marks': False, 'polydactyly': False} template_name = 'donors/donor_search_attr.html' def get(self, request): form = self.form_class(initial=self.initial) args = {'form': form} return render(request, self.template_name, args) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): ethnicity = form.cleaned_data['ethnicity'] skintone = form.cleaned_data['skintone'] eyecolor = form.cleaned_data['eyecolor'] haircolor = form.cleaned_data['haircolor'] body_build = form.cleaned_data['body_build'] tattoo = form.cleaned_data['tattoo'] scar_marks = form.cleaned_data['scar_marks'] polydactyly = form.cleaned_data['polydactyly'] nose = form.cleaned_data['nose'] facial = form.cleaned_data['facial'] race = form.cleaned_data['race'] academic_info = form.cleaned_data['academic_info'] blood_group = form.cleaned_data['blood_group'] genotype = form.cleaned_data['genotype'] filter_values = {'ethnicity': ethnicity, 'skintone': skintone, 'eyecolor': eyecolor, 'haircolor': haircolor, 'body_build': body_build, 'nose': nose, 'facial': facial, 'race': race, 'academic_info': academic_info, 'blood_group': blood_group, 'genotype': genotype} d = ['donorprofile__tattoo__name={}'.format(tattoo), 'donorprofile__scar_marks__name={}'.format(scar_marks), 'donorprofile__polydactyly__name={}'.format(polydactyly)] for table_name, values in filter_values.items(): if values: data_format = 'donorprofile__{}__name={}'.format(table_name, values) d.append(data_format) # print(d) donors = donor.objects.filter(d) # donors = donor.objects.filter(Q(donorprofile__ethnicity__name=ethnicity) | Q(donorprofile__skintone__name=skintone) | # Q(donorprofile__eyecolor__name=eyecolor) | Q(donorprofile__haircolor__name=haircolor) | # Q(donorprofile__body_build__name=body_build)) return render(request, self.template_name, {'form': form, 'donors': donors, 'filter_values': d}) -
Django - Check if a non-foreign-key integer field exists as a Primary Key to another Model?
Say you have the following legacy model: class Foo(models.Model): bar_id = models.IntegerField(null=True, blank=True) # more fields bar_id is supposed to refer to a primary key from the Bar model, but for some reason, it's not registered as a foreign key. Now, how can I filter out all the Foos that do not have corresponding Bar objects? -
python - request.get("https://www.example.com") doesn't work when trying to run Django app with Apache and mod_wsgi
import requests response = requests.get("https://www.example.com") This fails with error: Exception Value: Can't convert 'NoneType' object to str implicitly Tried all the steps mentioned here: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 Is there any other way to run django server in production? or any other way to run https requests in python 2.x? I have tried httplib2 and urllib. Tried installing httplib but couldn't install.