Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model filter queryset: store filter and exclude result in single query
I am new in Django framework. I am stuck on a very simple problem. Let's say I have a Model(table) name Author which have two columns name and gender. Now I want to filter the querysets whose author name is 'amit' and whose author name is not `amit'. One way to do this is: qs1 = Author.objects.filter(name='amit') qs2 = Author.objects.exclude(name='amit') Can we get the result qs1 and qs2 in single query? Something like this qs1, qs2 = Author.objects.some_filter_method(name='amit) Any help would be appreciated. Thanks. -
Why am I getting method not allowed using Django Ajax Post call in the same project
I am building a simple Django post with has LIKE/DISLIKE feature which works perfectly fine on without adding any Ajax using RedirectView CBV. In the Ajax version I use just View. Why am I getting method not allowed in my console.log Below is the error I see in my console.log Below is my script <script> $(document).ready(function () { $(".like_button").click(function (event) { event.preventDefault(); var username = "{{ request.user.username }}"; var slug = $(this).attr("value"); var like = $("#like-section"); console.log(username); console.log(slug); $.ajax({ url : "{{post.get_api_like_url}}", type: "POST", data: { "username": username ,"slug": slug, "csrfmiddlewaretoken": "{{ csrf_token }}"}, dataType: "json", success: function (data) { like.html(data["form"]); }, error: function (rs, e) { console.log(rs, e); } }) }) }) </script> My Template is: <form action="{{post.get_api_like_url}}" method="post"> {% csrf_token %} {% if user in post.likes.all %} <button type="submit" name="post_slug" value="{{ post.slug }}" >LIKE</button> {% else %} <button type="submit" name="post_slug" value="{{ post.slug }}" >DISLIKE</button> {% endif %} </form> My Models class Post(models.Model): #title, slug, message, etc exist but not included here likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) def get_api_like_url(self): return reverse('posts:like_post', kwargs={'username': self.user.username, 'slug': self.slug}) My Url is as below url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/like_post/$', views.PostLikeToggle.as_view(), name="post_like"), The code doesn't reach my Views I know … -
Django - How to nest models properly
I want to nest my models so that I can have a template structure like this: {% for item in nav %} <a href="{{ item.href.value }}" {% if item.href.target %} target="{{ item.href.target }}" {% endif %} class="nav__item">{{ item.label }}</a> {% endfor %} So in my templates i have always kind of a JSON like structure. e.g. "nav": [ { "label": "ABC", "href": { "value": "#", "target": "_blank" } }, { "label": "DEF", "href": { "value": "#", "target": "_blank" } } ] What is the best way to integrate those structures in Django? So I can render all of my context from Database. Should I just take every field like so: class Nav(models.Model): label = models.CharField(max_length=80) value = models.URLField() target = models.URLField(blank=True) and code somehow my own dictionary with the data, or is there a better solution? -
Django Blog site database design
I'm looking to create a simple blogging website in Django and I'm wondering what the best design for my models. Most tutorials for Django bloggin sites have a simple Post model like this: class Post(models.Model): title = models.CharField(max_length = 140) body = models.TextField() date = models.DateTimeField() However, this has the drawback that the body field will just be displayed as a single block of text. This is not ideal as I want to be able to split it into paragraphs, insert inline images, etc. The two solutions I can see to solve this are: Let users write HTML into the Django admin panel and then render it in the template with: {{ body |safe }} to enable rendering HTML rather than just displaying it as raw text. Making a PostParagraph model that has a OneToMany field referencing Post, which means I'd be able to iterate over them and render them inside <p> tags in the template. Neither of these solutions is ideal. The first option lets the user insert HTML that can be rendered on a page, which I'm assuming is vulnerable to XSS. The second option could get confusing if the user wants to modify an existing blog post; … -
Django page URL contain %3f instead of "?" sign
Im using Django paginator in CBV, and after form submit (creates new post) Im trying to redirect to actual page with newly created post. I`m using reverse_lazy with keyword argument for page number, but in URL generated with reverse_lazy, "?" sign on the beginning is changing for %3F, e.g. ?page=7 --> %3Fpage=7. And consequently, I get redirect to first page. My URL path: path("homeT/?page=<int:num>", views.homeTestView.as_view(), name="actual_page"), Reverse_lazy: return reverse_lazy("actual_page", kwargs={'num': page_num}) P.S. And is there a easier way to get redirect to page with newly created post/comment?? Thank you. -
SET_DEFAULT for ForeignKey column itself
I,m create this table in django models: class customer(models.Model): name = models.CharField(max_length=100) inviter = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_DEFAULT) inviter is ForeignKey of self Now I want set_default one Row of customer table for inviter column. -
Django: combining inputs from multiple text boxes into single field
I have developed a Django project for students marksdata entry.I have varying number of question in each subjects. In order to facilitate easy data entry, I have planned for multiple textboxes which are inside a html table upon submitting, the values from these multiple textboxes should be joined with comma and stored in a single a field in the database. I have provided my views, model and template codes as below: views.py: def savemark(request): if request.POST: subject=request.POST.get("subject") subdata = Subject.objects.filter(subid=subject) course=request.POST.get("course") year=request.POST.get("year") cohart=request.POST.get("cohart") exam=request.POST.get("exam") examdata = Exam.objects.filter(examid=exam) qddata=Questiondetails.objects.filter(subid=subject,examtype=exam) studata=Studentcohart.objects.filter(cohartid=cohart,currentyear=year).values('studentid') return render(request,'blog/savemarks.html',{'student':studata,'question':qddata,'subject': subdata,'exam':examdata,'course':course,'year':year,'cohart':cohart}) else: return render(request,'blog/home.html') models.py class Mark(models.Model): year = models.CharField(max_length=20) mark = models.IntegerField() subid = models.ForeignKey('Subject', models.DO_NOTHING, db_column='subID') # Field name made lowercase. studentid = models.ForeignKey('Student', models.DO_NOTHING, db_column='studentID') # Field name made lowercase. examid = models.ForeignKey(Exam, models.DO_NOTHING, db_column='examID') # Field name made lowercase. cohartid = models.ForeignKey(Cohart, models.DO_NOTHING, db_column='cohartID') # Field name made lowercase. savemarks.html <html> <body> <table> <form action="/submit/" method="post" > <tr> <th>studentid</th> {% for i in "x"|rjust:"30" %} <th>Q{{forloop.counter}}</th> {% endfor %} </th>q{{forloop.counter}}<th> </tr> {% for sub in student%} <tr> <td> {{ sub.studentid}} </td> {% for i in "x"|rjust:"30" %} <td> <input type="text" name="mark" /><br /> </td> {% endfor %} </tr> {% endfor %} <table> <input type="submit" value="Log … -
Load more button in Django
commerce project and I want to load all products in the same page that is in the homepage but instead of loading all the products at once I want them to load them in sets of 16 at once so that sites doesn't gets slow. I used Django pagination with waypoints and jquery but the problem with this was it automatically loads the products while scrolling down I only want products to be loaded when clicked on load more button and I don't want the homepage URL to be changed. What would be the best approach to take in such a case? Views.py class ProductListView(generic.ListView): model = Product queryset = Product.objects.all() context_object_name = 'products' paginate_by = 16 template_name = 'index.html' -
django rest framework serialialzer's update method appears to have an implicit transaction.atomic
models.py MAX_SUB_PAGES=100 class Book(BaseModel): title = CharField(...) @property creatable_sub_pages(self): return MAX_PAGES-sum of sub_page_count of all pages class Page(BaseModel): book = ForeignKey("Book", related_name="pages", ...) string = CharField(...) serializers.py class PagePOSTSerializer(serializers.ModelSerializer): class Meta: model = Page fields = ('book', 'string', 'sub_page_count') def validate_book(self, value): print(value.creatable_sub_pages) if value.creatable_sub_pages== MAX_PAGES: raise serializers.ValidationError("sub_page limit reached.") return value class BookUPDATESerializer(serializers.ModelSerializer): pages = PagePOSTSerializer(many=True) class Meta: model = SaleReturnInvoice fields = ('title', 'pages') def validate_pages(self, value): if len(value)==0: raise serializers.ValidationError("atleast one page is required.") @transaction.atomic def update(self, instance, validated_data): book = instance book.pages.all().delete() pages_data = validated_data.pop('pages') for page_data in pages_data: page = Page(book=book) page_serializer = PagePOSTSerializer(page, data=page_data) if page_serializer.is_valid(): page_serializer.save() else: raise serializers.ValidationError(page_serializer.errors) return book Note: It doesn't appear logical. The above code isn't actual one I am working on. Please don't answer like: "you could have done the validation inside the update method of the BookUPDATESerializer itself." My actual models and serializers are huge and I would like the validation to be done as it is as shown above. constraints: A Book can have maximum of 100 sub_page_count only. Let's say I have a Book B with 98 sub_page_count in the database already. And if I try to update the Book instance with sub_page_count greater than … -
React how to pass variable in index.html to components javascript
It is my first time asking a question on STACKOVERFLOW. I am making a project using Django and React. I fetch the data from Twitter API from Django and I want to show the data in frontend. I pass the data from django views.py to index.html as a javascript variable. Then I want to present it in the Landing.js in Components folder. I used React router and I Landing and Main page are pages that I am routing to so far. I have not figured out how to pass the data from a single html file to Javascript components in React Thanks in advance This is my tree structure this is context I pass from Django views.py this is a variable I want to pass to "LANDING" componentsThis is "Landing.js" components I want to show the variables -
How to include facets that have a count of 0 in facet_counts() with django-haystack when narrowing or filtering?
I am using django-haystack with elasticsearch. I want to show sport sessions on a website. For now I have two facets; sport and training level. Both of them are a list of check boxes and are 'OR' oriented, which means that multiple can be selected. For the example, there are 3 training options with 4 different training each. All the basketball training is for beginners and all football and dancing training is for advanced. This would result in the following: Training options: Basketball (4), Football (4), Dancing (4) Training levels: Beginner (4), Advanced (8) If I click on basketball, the following result is displayed: Basketball (3), Football (3), Dancing (3) Beginner (3) In this case the advanced is left out. What I want though is: Basketball (3), Football (3), Dancing (3) Beginner (3), Advanced (0) I use the following code: from haystack.forms import FacetedSearchForm class FacetedSearchSportForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.sports = data.get('sports', []) self.level = data.get('level', []) super().__init__(*args, **kwargs) def search(self): sqs = super().search() if not self.is_valid(): return self.no_query_found() if self.sports: query = None for sport in self.sports: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(sport) sqs … -
InconsistentMigrationHistory Exception in django db migrations
I'm getting this below error when I tried to migrate the changes to database in django Error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration authtoken.0001_initial is applied before its dependency seeker.0001_initial on database 'default' -
how reverse relation works in django model while working with serializers?
here is my models.py from __future__ import unicode_literals from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) owner = models.ForeignKey('User') class Meta: ordering = ('created',) def __str__(self): return self.title class User(models.Model): name = models.CharField(max_length=100, blank=True, default='') def __str__(self): return self.name here is my seralizers.py from rest_framework import routers, serializers, viewsets from .models import Snippet from django.contrib.auth.models import User from rest_framework import permissions class SnippetSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.user') permission_classes = (permissions.IsAuthenticatedOrReadOnly,) class Meta: model = Snippet fields = '__all__' class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) class Meta: model = User fields = '__all__' here is my view.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import * from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,mixins,generics from django.http import Http404 class … -
redis not following redis.conf settings
I am running redis server and have set the dir to /var/lib/redis and dbfilename to dump.rdb but i notice redis starts to produce these errors below 120844:C 23 Sep 02:59:31.098 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:31.198 # Background saving error 42657:M 23 Sep 02:59:37.018 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:37.019 * Background saving started by pid 120868 120868:C 23 Sep 02:59:37.019 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:37.119 # Background saving error 42657:M 23 Sep 02:59:43.035 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:43.036 * Background saving started by pid 120869 120869:C 23 Sep 02:59:43.036 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:43.136 # Background saving error 42657:M 23 Sep 02:59:49.052 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:49.052 * Background saving started by pid 120895 120895:C 23 Sep 02:59:49.053 # Failed opening .rdb for saving: Read-only file system 42657:M 23 Sep 02:59:49.153 # Background saving error 42657:M 23 Sep 02:59:55.067 * 1 changes in 900 seconds. Saving... 42657:M 23 Sep 02:59:55.067 * Background saving started by pid 120939 then i … -
Add Dynamic Fields Render Textinput Only
I am creating dynamic fields in django forms by the init override of the form class: forms.py class LearnerEventsLogForm(forms.Form): def __init__(self, *args, **kwargs): super(LearnerEventsLogForm, self).__init__(*args, **kwargs) self.fields["division"] = forms.ChoiceField(required=True ,choices=[]) self.fields["division"].widget = forms.Select self.fields["lin"] = forms.CharField(required=True) self.fields["remarks"] = forms.CharField() self.fields["remarks"].widget = forms.Textarea In my template: {% extends 'base.html' %}{% load static %} {% load widget_tweaks %} <form id="learnerClassForm" method="post"> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field | add_class:'form-control' }} </div> {% endfor %} <div class="form-group"> <button type="submit" class="btn btn-success"> <span class="glyphicon glyphicon-ok"></span> Save </button> <a href="{% url 'home' %}" class="btn btn-default">Cancel</a> </div> </form> To my suprise all fields widget are of type textinput. Is there an explanation for this behaviour ? -
ForeignKey to 'self' in sub-application throws error on makemigrations
I'm currently working on an large Django project (version 1.10.7) and am running into an error with a model field in a sub-application. Here's what the basic structure looks like: project/ app_one/ __init__.py apps.py models.py urls.py views.py app_two/ __init__.py apps.py models.py urls.py views.py The model and field in question looks like this (project/app_one/app_two/models.py): class SampleModel(model.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='members') When I run python manage.py makemigrations app_one.app_two in the root folder I get this error message: File .../django/db/models/utils.py", line 23, in make_model_tuple "must be of the form 'app_label.ModelName'." % model ValueError: Invalid model reference 'app_one.app_two.SampleModel'. String model references must be of the form 'app_label.ModelName'. Here is code from other files that are relevant: project/settings.py: INSTALLED_APPS = filter(None, ( ... 'app_one', 'app_one.app_two', ... ) project/app_one/app_two/apps.py: from __future__ import unicode_literals from django.apps import AppConfig class AppOneAppTwoConfig(AppConfig): name = 'app_one.app_two' label = 'app_one.app_two' project/app_one/app_two/__init__.py: default_app_config = 'app_one.app_two.apps.AppOneAppTwoConfig' I believe the error here is that Django is only looking for one . in the full model name (app_one.app_two.SampleModel) to separate the app label from the model name in django/db/models/utils.py, and since there are two in this case, it fails. My question is: This seems like a weird for Django not to account for...is … -
Attempting to install postgis getting error : syntax error at or near "postgis_lib_version"
I am attempting to install postgis and trying to integrate it with my django. I am following this tutorial here. It says the following after connecting to db we need to add geo-extensions: -- Enable PostGIS (includes raster) CREATE EXTENSION postgis; -- Enable Topology CREATE EXTENSION postgis_topology; -- fuzzy matching needed for Tiger CREATE EXTENSION fuzzystrmatch; -- Enable US Tiger Geocoder CREATE EXTENSION postgis_tiger_geocoder; check POSTGIS version: postgis_lib_version(); as a tupple we add it to django settings: POSTGIS_VERSION = (2, 1, 3) This is what I did mst=# \connect school psql (10.5, server 10.4) You are now connected to database "school" as user "mst". school=# CREATE EXTENSION postgis; CREATE EXTENSION school=# CREATE EXTENSION postgis_topology; CREATE EXTENSION school=# CREATE EXTENSION fuzzystrmatch; CREATE EXTENSION school=# CREATE EXTENSION postgis_tiger_geocoder; CREATE EXTENSION school=# postgis_lib_version(); ERROR: syntax error at or near "postgis_lib_version" LINE 1: postgis_lib_version(); Any suggestions on why I am getting this error. Anything that I might be missing or doing wrong ?? -
customize bootstrap pagination in Django
this is the default code for django pagination: {% load bootstrap4 %} {% with bpurl=bootstrap_pagination_url|default:"" %} <ul class="{{ pagination_css_classes }}"> <li class="prev page-item{% if current_page == 1 %} disabled{% endif %}"> <a class="page-link" href="{% if current_page == 1 %}#{% else %}{% bootstrap_url_replace_param bpurl parameter_name 1 %}{% endif %}"> &laquo; </a> </li> {% if pages_back %} <li class="page-item"> <a class="page-link" href="{% bootstrap_url_replace_param bpurl parameter_name pages_back %}">&hellip;</a> </li> {% endif %} {% for p in pages_shown %} <li class="page-item{% if current_page == p %} active{% endif %}"> <a class="page-link" href="{% if current_page == p %}#{% else %}{% bootstrap_url_replace_param bpurl parameter_name p %}{% endif %}"> {{ p }} </a> </li> {% endfor %} {% if pages_forward %} <li class="page-item"> <a class="page-link" href="{% bootstrap_url_replace_param bpurl parameter_name pages_forward %}">&hellip;</a> </li> {% endif %} <li class="last page-item{% if current_page == num_pages %} disabled{% endif %}"> <a class="page-link" href="{% if current_page == num_pages %}#{% else %}{% bootstrap_url_replace_param bpurl parameter_name num_pages %}{% endif %}"> &raquo; </a> </li> </ul> {% endwith %} So, where should I change the code to display less number of pages . like displaying in this pattern : << 1 2 3 .... 20 >> -
Django Debug views during unit tests
I'm trying to debug a failing unit test in Django. I'm running VScode and the python extension. I got the debugger to attach to the manage.py testcommand and can see what is happening in the unit tests themselves. However, when I insert a breakpoint into a view function is does not break when I make a call with test client. My code coverage picks it up but apparently not the debugger. -
How can I delete unused tags in django?
This is a general problem of tags created with django-taggit. Tags are not removed when removing an object (layer, map, document, remote service etc...). -
How to Sum all instances of a model in Django
these are my models class Countries(models.Model): Name = models.CharField(max_length=100) Language = models.IntegerField() Population = models.IntegerField(default=0) class World(models.Model): Languages_spoken = model.Charfield(max_length=12000) World_population = models.IntegerField(default=0) I am trying to add Population of all instances in Countries to sum and show on World_population field on class World What I have tried class World(models.Model): Languages_spoken = model.Charfield(max_length=12000) World_population = models.IntegerField(default=0) def save(self, *args, **kwargs): self.World_population = Countries.obejects.get(Population)#I know this is not correct super(World,self).save() -
Pycharm debugging manage.py commands in docker compose
I have a pretty simple setup. I'm running Pycharm 2018.2.3 and using docker compose to spin up 3 containers. My Django application NGINX to serve static Postgres DB I've configured the remote interpreter for debugging the container, and break point work just fine in most cases, at least when I hit my API endpoints or some other action to the django application. What does not work, is when I run one of my manage custom manage.py custom commands. I've tried this 2 ways so far. I setup another debug configuration in PyCharm to execute the command. This results in another container spinning up (in place of the original. Running the command, without breaking on any line breaks. Then the whole container shuts down. I've logged into the container, run the manage.py command directly via the command line, and it execute in the container, but again no breakpoints. The documentation seems to work in the normal case, but I can't find any help for debugging these commands in the container. Thanks for any help or tips. -
How to access data from filter in Django
using this in template {{ filter.data }} giving me result as below: What should I do to get the value Phnom Penh instead of QueryDict? -
Django Backward-Relationship Queries: Good way to Handle User-Generated Model Attributes?
Trying to design library catalogs where we will filter different books to show. Certain book attributes will always be on each book, so we can code those like normal model attributes. class Book(models.Model): title = models.CharField() author = models.CharField() #then an example query books_starting_with_a = Book.objects.filter(title__startswith='a') The challenge is after talking to various libraries they each have different features they want to sort on. We want to make this flexible where the library can add attributes to save using some form and then users can filter on. Ie. color of book, nationality_of_author, languages_translated_into, has_been_translated_boolean. What’s best way to do this? I want to make the filtering easy, and trying to prevent overload. Don't think we'd have more than 80,000 books in a given library. One idea is to have a separate CustomBookAttribute model that the libraries could create in a form and then CustomBookAttributeAnswer fields would be for each book. Like this: class CustomBookAttribute(models.Model) library = models.ForeignKey(Library) prompt = models.CharField() boolean_type_attribute = models.BooleanField(default=False) select_type_attribute = models.BooleanField(default=False) select_choices = ArrayField(models.CharField()) class CustomBookAttributeAnswer(models.Model) customBookAttribute = models.ForeignKey(CustomBookAttribute) book = models.ForeignKey(Book) answer = models.CharField() My question is: 1)is this a good approach? Will it scale well and not turn database into slag? AND 2)How … -
Add password to Django Group model
Is it possible to password protect groups so that a user can only join a group if it has a password? I know it's possible to add fields to the Group model with Group.add_to_class('password', CharField(max_length=180, null=True, blank=True)) But how can I implement this in a secure way? I want the password to be properly hashed and stored. In essence, how can I add the User password field to Group as well?