Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically set the value of next in all django CBV
I want my website to work like this: Attempt to go to a URL. (=>should become the 'next' parameter) You get redirected to the login page, because you're not logged in. After logging in, it should take you to 'next.' Nobody has ever framed their usage of next in this manner, so far that I've seen on S.O. and the docs don't help at all. Everyone else asks how to redirect if you click Login explicitly. Do I have to modify every single get_success_url() or get_context_data() method in every one of my CBV to properly give it the 'next' parameter? I can't even tell which view is actually saying "oh you're not logged in, go to /login/ ," cause if I could tell that I could at least attempt to override that method and give it the request.path parameter. I assume it is AuthenticationMiddleware, or LoginRequiredMiddleware Apparently it isn't "LoginView" (django 1.11) because when I put a breakpoint on the dispatch method there, it doesn't see my original attempted URL anywhere, it simply sees request.path = '/login/' How do I nab the value of "originally intended url" and set it to the 'next' parameter, so that it redirects to '/login/?next=next_page' … -
Loop through the end of a Django queryset
I am trying to loop through a Django queryset, starting at the last record and going back 1,000 records at a time. I'm able to get the last 1,000 records with the following query: employees = Employee.objects.all().order_by('-id')[:1000] Say my queryset is 10,0000 results. How can I go from 8,000 to 9,000? Do I have to use .count() to get the total record count? My full queryset is 12 million records so I am trying to avoid that if possible. -
Best place to update related fields via django-import-export
In our project, we have to import and export complicated models in *.xls and other formats. django-import-export great tool and helped us. I wrote a lot of code for creating/editing related models vie additional meta fields (two or three levels in deep). I used import_row, import_field, before_import_row and others methods in our base ModelResource. And now I have little trouble where to place the code for simple logic. We want to update related object's field. For example: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.OneToOneField(Author) I want to export and import (update) author__name via book resource. I tried to write Widget for this field but it wasn't a good idea. Give me an example how to export end import author__name from BookResource in right way, please. -
Django - disallow NaN and infinity in FloatField
How can I make a FloatField in Django that does not allow saving NaN or Infinity values (while still allowing null values) - i.e. something along the lines of: class MyModel(models.Model): rate = models.FloatField(null=True, nans=False) # ??? I am using Postgres as a backend. If a general solution does not exist, maybe there is a Postgres specific solution? -
Django: All URLs are getting redirected to 404
Following is my urls.py file: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static handler400 = 'mysite.views.bad_request' handler403 = 'mysite.views.permission_denied' handler404 = 'mysite.views.page_not_found' handler500 = 'mysite.views.server_error' urlpatterns = [ url(r'^', include('app1.urls')), url(r'^', include('app2.urls')), url(r'^', include('app3.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) This started when I have recently uploaded the application to Digital ocean on Ubutu box which is serving pages using Apache2 and mod_wsgi. Site is being redirected to the custom 404 HTML template which I have created. What can be the reason, please suggest. -
Debug Django code in Docker
I want to debug my Django code running through docker container. Is it possible with PDB, PYCHARM debugger or with another technique? -
django-bower: `./manage.py bower install` (and variants) fail with KeyError: 'bower'
New to Django. I'm trying to clone and set up a pre-existing Django project which uses django-bower. It uses Django 1.10.6 and django-bower 5.2.0. I've set up a new virtualenv with all the project's requirements. The manage.py file is the same as the example from the django-bower library: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Running ./manage.py bower install (bower_install) too fails because Django and django-bower are only installed in the virtual environment. When I run it through python manage.py bower install or python manage.py bower_install I get this stack trace: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/django/core/management/__init__.py", line 189, in fetch_command app_name = commands[subcommand] KeyError: 'bower' -
How can I run function asynchronously to make calculation parallelly on Heroku with Django app?
I have to run function 500 times with different arguments on Heroku with hobby plan in my Django app at a specific time. I need to do it in the shortest period of time. I noticed that when I use Heroku Scheduler every task is running parallelly and asynchronously and each of them has own worker. So for example 10 functions ran in this way will calculate results as there would be only 1 ran function. As I have mentioned I need to run 500 functions with different arguments. I could create 500 Heroku schedulers and ran it separately but it seems to me that it's not supported by Heroku or maybe I am wrong? If so maybe someone know how it could be solved in another way? -
I can't change main Django project settings file
I was trying to configure the Django Database Settings to use mysql. I followed the instructions provided here I started a Django project within the myproject directory. django-admin.py startproject myproject . I tried to open the main Django project settings file nano ~/myproject/myproject/settings.py And the terminal did not display a DATABASES section at the bottom of this file. Instead I had ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text^T To Spell What do you recommend? I need to change this settings file to use mysql database.I have Ubuntu 14.04. and python 3.4. installed. -
Django - Getting AttributeError 'User' object has no attribute 'cleaned_data' while cleaning form data
I was trying to make a user registration page in Django. everything went fine. but when I submit the form data I get this below error AttributeError 'User' object has no attribute 'cleaned_data' Image of that AttributeError I searched on stackoverflow and found that the object.cleanded_data should be placed after object.is_valid() else one should face the AttributeError. But I placed that after checking is_valid() still getting error. my codes: views.py class UserFormView(View): form_class = UserForm template_name = "music/registration_form.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = user.cleaned_data["username"] password = user.cleaned_data["password"] user.set_password(password) user.username = username user.save() user = authenticate(username= username, password= password) if user is not None: if user.is_active: login(request, user) return redirect("music:index") return render(request, self.template_name, {"form": form}) forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email", "password"] I cant find where I made mistake. -
Adding fields to table dynamically in django
After reading about database designs, i've decided to go with a single table for all users. my question is how can i create fields for new users to add their data into it? also what's a good approach for retrieving data specific to each user? I appreciate any advise regarding this subject. -
can not connect module django-AB-project
I installed the library itself, added in INSTALLED_APPS = [ 'ab' ] But for some reason I get an error if I'm making a migration: ModuleNotFoundError: No module named 'ab' I use django==1.11 -
How can I calculate time from model object created time?
models.py @python_2_unicode_compatible class UserAuthToken(models.Model): email = models.ForeignKey(UserSubEmail) token = models.CharField(max_length=34, unique=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return "AuthToken for %s" % self.email I want to check elapsed time between token's created time and now So if token created before more than 10 minutes, I can recognize this token is invalid. views.py def create_email_confirm_key(request, uid, token): try: user_authtoken = UserAuthToken.objects.get(uid=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user_authtoken = None if not 'user_authtoken is created before more than 10minutes' : This token is valid and do something How can I calculate and check time between the token created and now? -
Send Python Data on Django
I have informations generated by a Python Script and I'd like to recovering this datas on Django. Simplifying: Python Script: extract information from log system Django: Web View - Is how I would like to show this informations to my user. Does Django has any features to it that or I need to create a webservice, because, one I am not familiarized with this Framework, I would send this data on to PHP using WEBService. -
Django SQL query duplicated 2 times
Model.py: class Match(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) class Stat(models.Model): match = models.ForeignKey(Match) team = models.CharField(max_length=100) goals = models.IntegerField(default=0) assists = models.IntegerField(default=0) views.py context_dict = {} match = Match.objects.get(pk=1) home_stat = Stat.objects.get(match=match, team=match.home_team) away_stat = Stat.objects.get(match=match, team=match.away_team) context_dict['home_stat'] = home_stat context_dict['away_stat'] = away_stat return render(request, 'index.html', context_dict) template goals: {{ home_stat.goals }} : {{ away_stat.goals }} assists: {{ home_stat.assists }} : {{ away_stat.assists }} django-debug-toolbar shows two duplicated queries: https://sfault-image.b0.upaiyun.com/220/984/2209840587-5a3e5ccccec87_articlex SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamA''') Duplicated 2 times. F:\myproject\myapp/views.py in index(11) home_stat = Stat.objects.get(match=match, team=match.home_team) SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamB''') Duplicated 2 times. F:\myproject\myapp/views.py in index(12) away_stat = Stat.objects.get(match=match, team=match.away_team) how to fix this? -
Django RegexValidator pattern for ZZ-99-ZZ-9999
Trying to make a regex pattern in pattern ZZ-99-ZZ-9999 (2 capital character-2 numbers-2 capital character-4 numbers) bus_number_regex = RegexValidator(regex=r'^\W{2}-?1?\d{2}-?1?\W{2}-?1?\d{4}$',message="Bus number must be entered in the format: 'ZZ-99-ZZ-9999'"." ZZ must be in Capital.") -
How can I run function asynchronously to make calculation parallelly on Heroku with Django app?
I have to run function 500 times with different arguments on Heroku in my Django app at a specific time. I need to do it in the shortest period of time. I noticed that when I use Heroku Scheduler every task is running parallelly and asynchronously and each of them has own worker. So for example 10 functions ran in this way will calculate results as there would be only 1 ran function. As I have mentioned I need to run 500 function with different arguments. I could create 500 Heroku schedulers and ran it separately but it seems to me that it's not supported by Heroku or maybe I am wrong? If so maybe someone know how it could be solved in another way? -
cant deploy django to ehost shared cpanel
i have a hosting package on ehost.com and i am trying to deploy a django application on it and i am having many problems first was that the django version i used is 2 and the pip version on ehost servers is with python 2.7 which is not compatible with django 2 then when trying to deploy a django 1.11 app which is compatible with python2.7 i followed all the instructions in the ehost django with fast cgi guide and the server doesnt execute the index.fcgi file it just returns the text in the file and the website support concerning these issues are not really helping -
Django ORM - Filter by GenericRelation across multiple models
Filtering on Django GenericRelations has been implemented 4 years ago via https://code.djangoproject.com/ticket/22207 and supports now to filter from the related model: class Issue(models.Model): project_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=False, null=True) project_id = models.PositiveIntegerField(blank=False, null=True) project = GenericForeignKey('project_content_type', 'project_id') class GitlabProject(models.Model): issues = GenericRelation( Issue, related_query_name='generic_project', content_type_field='project_content_type', object_id_field='project_id', ) and then: issues = queryset.filter(generic_project__offers__members__in=[request.user]) We cannot use just project__offers_members - it would fail, as Django does not reversely resolve Generic Foreign Keys. However what happens if we have another project model with the same related_query_name? class JiraProject(models.Model): issues = GenericRelation( Issue, related_query_name='generic_project', content_type_field='project_content_type', object_id_field='project_id', ) I have tried setting the GenericRelation with the same related_query_name on all the different project models (i.e. Gitlab Project, Jira Project, etc.). However that results in Django picking up only the 'first' project model. The generic relation to all subsequent project models are ignored and as a result, issues that have instances set that do not belong to the 'first' project model are ignored and not part of the queryset. I think Django should either support this or issue a warning or error (possibly when executing the makemigrations command), when multiple GenericRelations have the same related_query_name value set. How can one filter efficiently across issues that have … -
Temporary views are not supported in CouchDB
I'm building a web app using Django and couchdb 2.0. The new version of couchdb doesn't support Temporary views. They recommend using Mongo query but I couldn't find any useful documentation. What is the best approach or library to use couchdb 2.0 with Django? -
Access via ForeignKey to the image field of parrent model in QuerrySet [Django]
I have this simplified model.py: class Product(models.Model): name = models.CharField() description = models.CharField() class ProductImage(models.Model): product = models.ForeignKey(Product,) photo = models.ImageField(upload_to="product_images/") is_main = models.BooleanField(default=False) An Product can have many ProductImage, but only ProductImage which has field is_main=True shall be rendered in a template together with all field of Product. The following data set from the views.py: products = Product.objects.all() So now I would want to do something like this in the template: {% for product in products %} <img class="card-img-top" src="{{ product.productimage_set.filter(is_main=True).photo }}" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">{{ product.name }}</h4> <p class="card-text">{{ product.description }}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> But obviously that's not possible. Not from the template directly, at least. What is the proper way to get all the fields of Product and its image with attribute is_main=True inside the template? -
Django upload video with automatic thumbnails generation
I want to upload mp4 and mov videos to my django website with automatic thumbnail generation. Thumbnails can be jpg or png that will save in ImageField and video to FileField. thumbnail = models.ImageField() video = models.FileField() I am using Python 3.6.3, Django 1.11.8 and dropzone. Please suggest me how to create a video upload page similar to youtube. Is there any opensource plugin available to achieve this ? -
Django newbie, struggling to understand how to implement a custom queryset
So I'm pretty new to Django, I started playing yesterday and have been playing with the standard polls tutorial. Context I'd like to be able to filter the active questions based on the results of a custom method (in this case it is the Question.is_open() method (fig1 below). The problem as I understand it When I try and access only the active questions using a filter like questions.objects.filter(is_open=true) it fails. If I understand correctly this relies on a queryset exposed via a model manager which can only filter based on records within the sql database. My questions 1) Am I approaching this problem in most pythonic/django/dry way ? Should I be exposing these methods by subclassing the models.Manager and generating a custom queryset ? (that appears to be the consensus online). 2) If I should be using a manager subclass with a custom queryset, i'm not sure what the code would look like. For example, should I be using sql via a cursor.execute (as per the documentation here, which seems very low level) ? Or is there a better, higher level way of achieving this in django itself ? I'd appreciate any insights into how to approach this. Thanks Matt … -
Resolved url function not equal to class based view `as_view()` method?
I have the following test: def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual( found.func, views.HomePageView.as_view() ) gives this error: AssertionError: <function HomePageView at 0x107d65620> != <function HomePageView at 0x107d97400> -
How correctly to set up autocomplete_fields?
Trying to set up autocomplete_fields for ForeingKey in Django admin. I don't understand how correctly to set it up. I read the docs but there is not much information about autocomplete_fields, not enough for me at least. admin.py class AdminSettings(admin.ModelAdmin): filter_horizontal = ('english_word', 'russian_word', 'turkish_word') list_display = ['circassian_word', 'letter'] autocomplete_fields = ('circassian_word',) search_fields = ['circassian_word__circassian'] models.py class Word(models.Model): circassian_word = models.ForeignKey(Circassian, blank=True, null=True, on_delete=models.CASCADE, verbose_name='Адыгэбзэ') letter = models.ForeignKey(Alphabet, null=True, on_delete=models.CASCADE, verbose_name='Буква') audio = models.FileField(upload_to='audio', blank=True, verbose_name='Озвучка') turkish_word = models.ManyToManyField(Turkish, blank=True, verbose_name='Türkçe') english_word = models.ManyToManyField(English, blank=True, verbose_name='English') russian_word = models.ManyToManyField(Russian, blank=True, verbose_name='Русский') Error message Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10d07b9d8> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 410, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'psalale.admin.AdminSettings'>: (admin.E037) The value of 'autocomplete_fields[0]' refers to 'circassian_word__circassian', which is not an attribute of 'psalale.Word'. System check identified 1 issue (0 silenced).