Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Tokenauthentication
I am implementing django backend for my android application in which I want to implement TokenAuthentication for my users. My android users signup by providing their mobile numbers in android app. When they signup I want to provide them a Token, so that they use whole app features by using that Token further. I have read the django-restframework TokenAuthentication document.It shows how to authenticate users of built in admin users (request.user). I have separate model for my android users. I want to assign a token for each mobile number. I have coded everything without authentication it is working fine. Now trying to attach TokenAuthentication. How to do it? -
Cannot properly check model type of an instance
Cannot figure out, why "if statement" returns incorrect value next_step_type = type(next_step)() # this returns 'Quiz' which is correct # if statement returns step_type_letter = 't' which is not correct if next_step_type is "Quiz": step_type_letter = 'q' else: step_type_letter = 't' -
Add fields from User to a customModel, in django admin
In django-admin, I try to add specifics fields from User django class, in a cutom Model Practitionner by using the Inline system. This code represents the idea, but it is not valid because the User has no foreign key to Practitionner : class UserInline(admin.StackedInline): model = User class PractitionerAdmin(admin.ModelAdmin): inlines = [UserInline] admin.site.register(Practitioner, PractitionerAdmin) I can't do the reverse because I have an other model Patient, that use User model too, and they need to be at two distinct places. The two custom classes have a OneToOne relation to User. Thanks in advance. -
Django: broken migrations
I am trying to setup a Django app locally in a new machine but migrations seem to be totally broken. They need to be performed in a particular order, which worked in the first machine I set the environment in a couple months ago, but now there are inconsistencies (although I am pretty sure no new migrations were generated). So the only solution I can think of is exporting the database from the old machine, where it is working, to the new one. Would that work? This would not solve the broken migrations issue, but at least I can work on the code till there's a proper soltuion. -
No module named selenium even after installing it
I have installed selenium using "pip install selenium" on mac. Also created a file functional_tests.py . It's content are from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title when I run this script using "python3 functional_tests.py" , I get no module named selenium . Please help ! -
Huge white space in pdf using Weasyprint
I am using Weasyprint in my Django application to create a pdf report of a set of orders. After I render the template in pdf format using Weasyprint, almost the entire first page is blank, besides the page header I set, and a header starting the list, but than the list starts on the second page even though there is plenty of space on the first page for that list to start. Im not super familiar with Weasyprint. Does anyone know of css that Im missing that might cause this issue in Weasyprint ? HTML <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> </head> <body> {% if productInfo %} <div id="report-wrapper"> <div class="row-fluid report-row header-row report-border"> <div class="span4 cell"> <h4 style='margin-left: 0;'>Job Name: {{ productInfo.meta.job_name }}</h4> </div> <div class="span7"> <div class="row-fluid table-condensed" style="padding-top: 0px; margin-top: 0px;"> <div class="span2 cell">Job ID: <h5>{{ productInfo.meta.job_id }}</h5></div> <div class="span6 cell">Customer: <h5>{{ productInfo.meta.customer }}</h5></div> <div class="span4 cell">Report Date: <h5>{{ productInfo.meta.report_date|date }}</h5></div> </div> </div> </div> <div class="row-fluid report-row header-row report-border" style="border-bottom: none;"> <div class="span12 cell" style="text-align: center; font-size: 22px; border-bottom: 3px solid black;"> <h4>Orders Shipped to Organization</h4> </div> <div class="span12"> <div class="row-fluid"> <div class="span2 cell">Style</div> <div class="span2 cell">Color</div> <div class="span1 cell">Size</div> <div class="span1 cell text-right">Qty</div> <div class="span2 cell … -
compare values of a dict in a forloop of a django template
I need compare values of a dict items inside a loop for in a django template. {% for room in hotel.RoomRS %} <p class="precio-old">1000,99€</p> <p class="precio-new">{{ room.RoomRates.TotalAmount }}</p> <p class="noche">120€ / noche</p> {% endfor %} This code return some integers values. I need compare it and choose the smallest one -
Is there an equivalent of Rails' DatabaseCleaner in Django?
I'm using django.test.TestCase for my tests as recommended here but the objects created during my tests persist in the database. Is there something similar to Rails' DatabaseCleaner in Django? -
Django Admin List_display change background color of cell
Trying to change the background color if status = closed. When I try the code below the result is shown in html instead of an actual color. ##Mode.py from django.template.defaultfilters import truncatechars # or truncatewords class TimeStampModel(models.Model): created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Created') updated = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name='Modified on') class Meta: abstract = True class Task(TimeStampModel): minor = 'MINOR' normal = 'NORMAL' important = 'IMPORTANT' critical = 'CRITICAL' SEVERITY = ( (minor, 'Minor'), (normal, 'Normal'), (important, 'Important'), (critical, 'Critical'), ) low = 'LOW' high = 'HIGH' PRIORITY = ( (low, 'Low'), (normal, 'Normal'), (high, 'High'), ) new = 'New' in_progress = 'In_Progress' needs_info = 'Needs Info' postponed = 'Postponed' closed = 'Closed' STATUS= ( (new, 'New'), (in_progress, 'In Progress'), (needs_info, 'Needs Info'), (postponed, 'Postponed'), (closed, 'Closed'), ) subject = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, help_text="Business purpose of the application") manager = models.ForeignKey(User, on_delete=models.CASCADE) severity = models.CharField(max_length = 100, choices=SEVERITY, default=normal) priority = models.CharField(max_length = 100, choices=PRIORITY, default=normal) status = models.CharField(max_length = 100, choices=STATUS, default=new) def __str__(self): return "{}".format(self.subject) class Meta: ordering = ('severity',) @property def short_description(self): return truncatechars(self.description, 35) ---- Admin.py | 22 normal = 'NORMAL' from .models import Task | 23 important = 'IMPORTANT' from django.contrib import admin | 24 … -
Django: psycopg2 import error
I was having a very weird bug when trying to run migrations in my freshly installed Django app and narrowed it down to the module imports. I found out django.db.backends.postgresql_psycopg2.base wasn't being imported so I checked my pyscopg2 installation by going to the Python console and trying import psycopg2. Indeed there was an error with this module: from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: DLL failed: The specified module could not be found. I tried uninstalling psycopg2 with pip and installing it again, and several different versions, but I always got the same error. I installed win-psycopg(psycopg2-2.6.2.win-amd64-py2.7-pg9.5.3-release.exe) from here. I am using Django 1.4.22, Python 2.7.8 64 bits and Windows 7 64 bits. -
Django : UnicodeEncodeError when saving simple form only in old browser and computer
I am using a mac OSX, and I have no characters problem on my mac, nor on recent windows computer we have at work. My client must have an old windows computer with a old firefox version, somehow when she is typing characters in the form it is not sending utf-8 characters and django generate a 500 error. The application development is done but we need users with old computers to also be able to use the application ... This error was caused when submitting a django form with post request. views.py def create(request): if request.method == 'POST': form = CollegeForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Collège ajouté avec succès.") return HttpResponseRedirect('/gestion/') else: form = CollegeForm() return render(request, 'administration/college/new.html', {'form': form}) html header <!DOCTYPE html> <html> <head> {% load static %} <meta charset="utf-8"> form in template <form action="{% url 'administration:college_create' %}" enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_p }} <input id="add_college" class="btn btn-success" type="submit" value="Ajouter" /> </form> forms.py class CollegeForm(ModelForm): class Meta: model = College fields = ['libelle', 'annee', 'composante', 'campagne_vote', 'campagne_cand', 'fin_cand', 'fin_vote', 'arrete'] exclude = ['closed', 'campagne_vote', 'campagne_cand'] labels = { 'libelle': 'Nom', 'annee': 'Année', 'composante': 'Composante', 'campagne_vote': 'Campagne de vote', 'campagne_cand': 'Campagne de candidature', 'fin_cand': 'Date de … -
django mssql setup : error initializing DB
I try to plug a django project (Python 3.5.2 and Django 1.10.2) to a SQLServer DB using django_mssql package, but it fails when it creates the django internal tables. Here is what I put in settings.py DATABASES = { 'default': { 'NAME': 'my_db', 'ENGINE': 'sqlserver_ado', 'HOST': 'my_server', 'USER': 'my_user', 'PASSWORD': 'super_secret_password', 'PORT': '', 'OPTIONS': { 'provider' : 'SQLNCLI11' }, } } and when I try to launch any migrate (even without any model defined), I get : python manage.py migrate (lot of logs here....) django.db.utils.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microso ft SQL Server Native Client 11.0', "The object 'UQ__auth_use__F3DBC57228A1A130' is dependent on column 'username'.", None, 0, -2147217900), None) Command: ALTER TABLE [auth_user] ALTER COLUMN [username] nvarchar(150) NOT NULL Parameters: [] Indeed, the table exists, the username column is nullable, but of course we cannot alter it since a unique constraint exists on this column. The script should drop the constraint, alter the column, recreate the constraint. Or not create the constraint so early in the script. I tried on SQLServer 2008 and 2014, same thing happen. I tried using provider SQLOLEDB and SQLNCLI11, same thing happen. I searched a long time but didn't find anybody having seen this issue. I'm … -
In Django views, how do I render get requests
In Django I am writing a view which processes a GET request from a page index.html and renders the request to another page match_listing.html. The page index.html has a number of checkboxes to modify the data displayed on match_listing.html. At the moment my code interrogates the GET request to determine the value of each of the checkboxes and then adds these to the context rendered to the page match_listing. This approach is clearly "unpythonic" and unsatisfactory. Can anyone suggest how I might be able to improve my code? from django.shortcuts import render from .models import Pl1516 from .parse import parse_load def index(request): if not request.GET.get('hometeam'): return render(request, 'main/index.html') else: hometeam_filter = request.GET.get('hometeam') ht_filter = request.GET.get('HT') htr_filter = request.GET.get('HTR') ftr_filter = request.GET.get('FTR') matches = Pl1516.objects.filter(hometeam=hometeam_filter) if matches.count() < 19: parse_load(hometeam_filter) context_dict = {'ht_filter': ht_filter, 'ftr_filter': htr_filter, 'htr_filter': htr_filter, 'matches' : matches} return render(request, 'main/match_listings.html', context_dict) -
django - lazy loading of django views
I have a situation when my model needs to call a view which is normally called otherwise (traditionally by users, like a regular view), and this view needs to call this model's method. If I go about this directly, it will result in an import cycle. Even if I somehow resolve this cycle, I have a feeling that it's not very good to import views into models, and it will bite me in the *** later anyway. So, is there a way to somehow indirectly import a view into a file? THe best I could come up with is a combination of reverse/resolve: def enter(self, botrequest): url = reverse( 'get_child_categories', kwargs={ 'parent_pk': 1, 'limit': 2, 'offset': 3 } ) match = resolve(url) match.kwargs.update({'botrequest': botrequest}) state = match.func(*match.args, **match.kwargs) return True, state But maybe there is a cleaner way? Something like view = magical_view_import('appname.viewname') -
Django: syncdb or manage throws ImproperlyConfigured exception
I finally managed to set up all the packages listed in requirements.txt so it was time to set up the database and running some migrations that were given to me. Since it's an older version of Django (1.4.22), first I needed to execute python my_settings_file.py syncdb. However an exception was thrown (this is also the same error appearing when running migrate instead of syncdb so it should be the same underlying issue): django.core.exceptions.ImproperlyConfigured: ImportError django.contrib.sitemaps: DLL load failed: The specified module could not be found I could not make anything helpful out of the trace, but here it is: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 443, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 261, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 69, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module __import__(name) File "C:\Python27\lib\site-packages\south\management\commands\__init__.py", line 10, in <module> import django.template.loaders.app_directories File "C:\Python27\lib\site-packages\django\template\loaders\app_directories.py", line 23, in <module> raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) I am not entirely sure, but I think last time I set up this environment locally I had this ImproperlyConfigured issue and the workaround was … -
Django with django cms and i18n Why custom template 404 return 200 or 302
I have already read subjects about this problem and I'm quite sure I respect the common practices about it. My custom 404 (dynamic) page from my template is correctly rendering but with different http response: 302 FOUND 301 MOVED PERMANENTLY Apparently I can't have a proper 404 NOT FOUND. my urls: handler404 = 'myApp.views.custom_page_not_found' My view: def custom_page_not_found(request): current_site = Site.objects.get_current() cms_page_not_found = _get_page_by_untyped_arg('404', request, current_site) if cms_page_not_found: language = get_language() request._current_page_cache = cms_page_not_found slug = '' with i18n.force_language(language): if not cms_page_not_found.is_home: slug = cms_page_not_found.get_path(language, True) or cms_page_not_found.get_slug(language, True) response = details(request, slug) try: response.render() response.status_code = 404 return response except: pass return page_not_found(request) So as you can see it's quite the complicated one as I have to deal with the correct 404 page, depending on the language. I'm with Django==1.7.7 and django-cms==3.1.4. If any one has an idea to improve that or to point out what the problem could be, it would be awesome! -
error running python manage.py on ubuntu
Please help, I am fairly new to django. I am using virtualenv (which has django installed) I have used this command to create a new project django-admin startproject projectname and consequently used the code cd projectname. But when I run python manage.py I get this error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' this is how my manage.py file looks like: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firstdjango.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) -
Undo of delete in the database with exclude
I was solving a bug and I wrongly launch this piece of code models.AACAreaTile.objects.exclude(id__in=keep_tiles_id).delete() That it result in delete all that kind of object. Any way to undo this? -
Django - Filter QuerySet only in admin-list and not in admin detail page
In the Django admin list view, i want to hide products without a name. I just excluded them in the get_query_set() method. def get_queryset(self, request): qs = super(ProductAdmin, self).get_queryset(request) return qs.exclude(name=None) This is working perfect, but i want to be able to access products without a name in the admin detail page (with a direct link). When it try this, i have an error, because it filters the product out of the queryset: http://127.0.0.1/product/123 product object with primary key u'123' does not exist. Is there a workaround for this problem? -
Add a set of related models to serializer output in django w djange-rest-framework
So I am just getting familiar with django and django-rest-framework. I have a model of Jobs that have an owner, and I want to add the list of jobs a user owns to the user endpoint. I tried to do it like this, as the tutorial of the django rest framework says: class UserSerializer(serializers.ModelSerializer): jobs = serializers.PrimaryKeyRelatedField(many = True, queryset = Job.objects.all()) class Meta: model = User fields = ('id', 'username', 'jobs') But for some reason, when I want to view the users, I recieve AttributeError at /users/ 'User' object has no attribute 'jobs' The documentation about the PrimareyKeyRelatedField looks just like this. Do I maybe have to do something with the user model? What works is the following: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'job_set') but I don't like that solution as I want to have more control about how the list is presented (maybe change the ids to complete json objects or rename the attribut name from 'job_set' to 'job) I really don't now what I am overseeing... -
Missing context on nested serializer in DRF
I'm experiencing a weird problem where one of my serializers is not getting the context and thus failing. First, the viewset, I've implemented a list method where I'm filtering orders based on some criteria that is dependent on nested relations in the model. class OrdersInAgendaViewSet(OrderMixin, viewsets.ReadOnlyModelViewSet): queryset = Order.objects.all() serializer_class = OrderInAgendaSerializer permission_classes = ( CanManageOrder, ) def list(self, request): final_orders = set() qs = super(OrdersInAgendaViewSet, self).get_queryset() # Get only orders that have lines with products that have no rentals objects for order in qs: accommodations = False lines = order.lines.all() for line in lines: if line.product.rental: accommodations = True break if not accommodations: final_orders.add(order.pk) qs = qs.filter(pk__in=final_orders) serializer = self.serializer_class(qs, many=True) return Response(serializer.data) And now the main Serializer for this ViewSet class OrderInAgendaSerializer(serializers.ModelSerializer): lines = LineForAgendaSerializer(many=True, read_only=True) customer = CustomerInOrderSerializer(many=False, read_only=False) notes = OrderNoteSerializer(many=True, read_only=True) class Meta: model = Order fields = ( 'id', 'date_placed', 'status', 'payment_status', 'email_billing', 'notes', 'customer', 'lines', ) extra_kwargs = {'date_placed': {'required': False}} As you can see I'm using 3 more serializers on this one, the one that is failing is LineForAgendaSerializer: class LineForAgendaSerializer(serializers.ModelSerializer): product = ProductForAgendaSerializer(many=False, read_only=True) customers = serializers.SerializerMethodField() class Meta: model = Line fields = ( 'starting_date', 'ending_date', 'product', 'customers', 'rents', ) … -
How to run a command in python with all the privilege
Currently i am working on a project and i am using django-kronos for scheduling so, when user schedule a task i am running a script and end of the script i need to run python manage.py installtasks this is help to insert the tasks in crontab. script is working fine when i execute in terminal but when i integrate it with my django app, it's throwing an error IOError: Read crontab nobody: You (nobody) are not allowed to use this program (/usr/bin/crontab) I really curious to know about which cause this problem? or did i miss anything? -
Python Django- How do I get file path from an input file tag in a form?
I just need the file path. This is what I came with so far: index.html: <form enctype="multipart/form-data" action="{% url 'polls:search_for_match' %}" method="post"> {% csrf_token %} <label for="file_path"></label> <input type="file" class="form-control" id="file_path" name="file_path" > <button type="submit" class="btn btn-default" >Analyze!</button> </form> view.py def searchMatch(request): form_class = Query if request.method == 'POST': form = form_class(request.POST, request.FILES) **file = request.FILES['file_path']** last_restarts = request.POST.get('restarts' , '') with zipfile.ZipFile(file) as z: ..... forms.py class Query(forms.Form): file_path = forms.FileField() the problem is in this line: file = request.FILES['file_path'].read() I don't get the file path, only the file name. Thanks a lot! -
Perform different operations using same template file for two different buttons
I have two buttons in my browser, which has the same template. A Popup is opened upon clicking these two buttons. The Popup has an input text field which has to display different values with respect to the click of the button. I'm using common template, view and controller for both the buttons. The code in my template file looks like: <td><input type="text" class="col-md-10" maxlength="256" ng-if="title1" ng-show="'{{reviewtit}}'" ng-model="arform.revtitle" required/></td> <td><input type="text" class="col-md-10" maxlength="256" ng-init="'{{reviewtit}}'" ng-model="arform.revtitle" > {{reviewtit}} </td> In the above code, title1 is a value I get from controller and {{reviewtit}} is a value from views. I need these two values to be displayed when respective type of button is clicked. Which is the best way to do this? I surfed quite a bit about specifying an ng-if here in the template or creating a custom API. Nothing seems to workout. Is there any easier way? Right now I'm able to see only the 'title1' value which I generate from the controller. The other button doesn't even show the input field. New approaches welcome. Thanks. -
Django Form request not saving data to db
I am using a django form in atemplate to save data entered to database. In my view after the request is made, the response is redirected correctly but the data is not saved to db. I might be missing something. but am unable to find it even after a lot of debugging. here is what has been done so far: views.py: from .models import testmodel def testview(request): if request.method== 'POST': form=MapForm(request.POST) if form.is_valid(): test1=request.POST.get('t1') print meaningid1 test2=request.POST.get('t2') print meaningid2 pobj=testmodel(test1=test1,test2=test2) mapobj.save() return HttpResponse('Successful') after this the response message "Successful" is seen from template: <form action="/testview/" method="post"> {% csrf_token %} {{form.as_p}} <input type="text" name="t1" value='' id='t1'/> <br><br><br> <input type="text" name="t2" value='' id='t2'/><br> <input type="submit" value="Submit" /> </form> from forms.py: from .models import testmodel class MapForm(forms.ModelForm): class Meta: model = testmodel fields = ['test1','test2'] after the data is entered in form it is going to page /testview and showing message on page. but from backend data is not been saved to db. Can some one suggest what could be done Thanks