Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-filter: add "All" filter option for AllValuesFilter with LinkWidget
Filtering with an AllValuesFilter on a many-to-many field and displaying this via LinkWidget, I don't get an All filter option, as with the django admin list_filter. I've found Add Any & None Handling to ChoiceFilter (and subclasses) and various other related issues, but I don't get the solution... In this specific case, I'm filtering on categories for a Django Wagtail Page model: # models.py # wagtail imports # ... # modelcluster imports, eg. # from modelcluster.fields import ParentalKey, ParentalManyToManyField class CategoryRegion(models.Model): title = models.CharField(max_length=200,) class NewsPage(Page): categories_region = ParentalManyToManyField( "core.CategoryRegion", blank=True, ) -- # filters.py import django_filters from django_filters.widgets import LinkWidget class NewsFilter(django_filters.FilterSet): categories_region = django_filters.AllValuesFilter( name="categories_region__title", label="Categories: Region", widget=LinkWidget(), ) class Meta: model = NewsPage fields = ['categories_region',] Any hints? -
Select related of selected related
Say I have a relationship (by foreign key) like this: Model 1 → Model 2 → Model 3. Can I follow foreign key relationship with select_related() more than one level deep? I.e. not only from Model 1 to Model 2 but also from Model 2 to Model 3? -
How to download a file securely using django rest framework? I am making using of Oauth2
I am creating a Django rest api and making use of Oauth2 for authentication and token generation. I need information about downloading any file using REST api securely. How can i achieve this. Below is my serialized data and i want to download the "document" i.e "link_mh6f7d3.db" using get request securely. { "id": 5, "file_name": "sqlite3", "file_descripton": "upload sqlite3 dump file", "completed": true, "upload_time": "2017-05-08T12:57:59.457859Z", "document": "http://xxx.xxx.x.xx:9000/media/Documents/link_mh6f7d3.db" }, currently i am requesting like this: http://127.0.0.1:8000/media/Documents/link_O1JBJGR.db [but this is not secured] Please shed some light on this topic. Thanks, Shash -
Django - Unexpected result from .values and .annotate
I'm trying to count the number of occurrences of the different product names in a table. I would like the result to be something like this: Laptop 10 Mice 15 And so on, yet instead I get: 2 10 1 15 Any ideas what could be wrong? This is my models.py: class ProductNoSerial(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category) def __str__(self): return self.name class ProductNoSerialInstance(models.Model): STATUS_CHOICES = ( ('in_inventory', 'In Stock'), ('given_out', 'Given Out'), ('repair', 'Repair') ) name = models.ForeignKey(ProductNoSerial) owner = models.ForeignKey(Employee, blank=True, null=True) it_dep = models.ForeignKey(ItDep) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') def __unicode__(self): return self.name This is my view.py: def InventoryList(request): count_query = ProductNoSerialInstance.objects.values('name').annotate(count=models.Count('name')) context = { 'inventory_list': count_query } return render(request, 'inventory_list.html', context) And finally my inventory_list.html: <p><b>List of inventory<b></p> <table> {% for item in inventory_list %} <tr> <td> {{ item.name }} </td> <td> {{ item.count }} </td> </tr> {% endfor %} </table> I've tried these suggestions, but without any luck. Any ideas what might be wrong? I figured the problem could be caused by the fact that name is a ForeignKey? -
Search engine for python on shared hosting
I'm currently in the process of building a website in which the user can query a book name and get a result from a mysql database of around 30,000 books. I've finished building the database and now i'm looking for a good search engine implementation for python. Initially i though of using Elasticsearch, but i currently have a very limited budget so i can only purchase shared web hosting and i read that Elasticsearch is too demanding for a shared hosting server. I also read I can use Haystack + Whoosh since im using Django, but I've also read whoosh is quite slow. What do you think I should use to supply the website quick and accurate search functionality? Thanks in advance! -
django sign up user in admin site with generated password
I am new to django, so please bare with me if I wrote something stupid: The problem: I would like to use django admin site User model to register new users. The default option offers you to register new username with password and password confirmation, which are required fields. My idea is to make few changes. I would like to keep username field and add email-field, however delete password and password confirmation. The principal idea is, I would register a user and he would receive an email with generated password. He would then be able to login with generated password and change the password. I am facing huge problems with templates, errors and most of all overriding the classes. I have spent many many hours checking django documentation, goolge and the best I could do so far is: admin.py from django.contrib import admin from django.contrib.auth import admin as upstream from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import Group, User from django.utils.translation import ugettext, ugettext_lazy as _ class UserAdmin(upstream.UserAdmin): fieldsets = ( (None, {'fields': ('username', 'password','email')}), (_('Personal info'), {'fields': ('first_name', 'last_name')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( … -
Design Material Design Lite Grid with cards to look like Google Keep
I am using Django in combination with Material Design Lite. I have accomplished a responsive layout where the cards that I generate scale with the width of the screen. This is a snippet of the rendered HTML with some cards removed to keep it readeable. <main class="mdl-layout__content"> <div class="mdl-grid"> <!-- Start of card !--> <div class="mdl-cell mdl-cell--4-col mdl-cell--4-col-phone "> <div class="stories mdl-card mdl-shadow--2dp"> <div class="mdl-card__title mdl-card--expand"> <h2 class="mdl-card__supporting-text">&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot;&quot;Lorem ipsum dolor sit amet, consectetur adipiscing e</h2> </div> <div class="mdl-card__title-text"> Tales </div> <div class="mdl-card__actions mdl-card--border"> <a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" href="/1/details">View details</a> </div> </div> </div> <!-- End of card !--> <!-- Start of card !--> <div class="mdl-cell mdl-cell--4-col mdl-cell--4-col-phone "> <div class="stories mdl-card mdl-shadow--2dp"> <div class="mdl-card__title mdl-card--expand"> <h2 class="mdl-card__supporting-text">&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et … -
I want to develop restful web service in python without using any framework. Any help will be appreciated. Thanks in advance
I am trying to develop rest api for learning purpose but without using any framework. How can I proceed with that. Any resource or suggestion you guys can provide me. Thanks -
How to use custom password validators beside the django auth password validators?
As the question above mentioned, I will trying to use a certain extra rule to validate a password during the registration process. The extra rule should be that a password is validate if it has at least one digit, one letter and one special character. My approach to solute this problem I've created a file named validators.py. from django.core.exceptions import ValidationError class CustomPasswortValidator: def validate(value): # check for digit if not any(char.isdigit() for char in value): raise ValidationError(_('Password must contain at least 1 digit.')) # check for letter if not any(char.isalpha() for char in value): raise ValidationError(_('Password must contain at least 1 letter.')) # check for special character special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]" if not any(char in special_characters for char in value): raise ValidationError(_('Password must contain at least 1 letter.')) My custom registration form looks like this: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegistrationForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) I don't get it how I tell django, that my custom password validator should be use beside the … -
OpenEDX-Insights - Token error: Invalid issuer
I have a devstack OpenEDX Dogwood.3 running. I installed Analytics as a FullStack (Ubuntu 12.04). I followed this link : https://openedx.atlassian.net/wiki/display/OpenOPS/edX+Analytics+Installation. But when I am trying to connect on analytics I have this error : File "/edx/app/insights/venvs/insights/local/lib/python2.7/site-packages/social/backends/open_id.py", line 341, in validate_and_return_id_token raise AuthTokenError(self, err) AuthTokenError: Token error: Invalid issuer Can anyone help me ? Thanks. -
Access to data in database by doing migrations
There are problem with Django migrations If I process 'python3 manage.py migrate' after standart django migrations was applied (auth, content_type etc), I see result: 'Permissions [per1, per2, ... ]' But if I process all migrations from scratch, I see result: 'Permissions []' from __future__ import unicode_literals from django.db import migrations def foo(apps, schema_editor): Permission = apps.get_model('auth', 'permission') print('Permissions', Permission.objects.all()) class Migration(migrations.Migration): dependencies = [ ..., ] operations = [ migrations.RunPython(foo, migrations.RunPython.noop) ] If I want do 'commit' manually, I get: 'Can`t be commit if atomic block is active' -
Django NoReverseMatch using templates (again)
Second time posting about NoReverseMatch. I just can't seem to understand the error good enough to find the error in my code. Last time it was because I did not give the fields in my url regex a name, but now that's not the issue. I understand that a million things can go wrong but for some reason I just can't seem to find it. The error is: NoReverseMatch at /david/Physics/a/ Reverse for 'information' with keyword arguments '{'category_name': 'Physics', 'information_name': 'Test info', 'subcategory_name': 'a'}' not found. 1 pattern(s) tried: ['david/(?P[a-zA-Z_]+)/(?P[a-zA-Z_]+)/(?P[a-zA-Z_]+)/$'] The template causing the error is: <h1>The items for {{ category }}/{{ subcategory }}</h1> {% if items %} <ul> {% for item in items %} <li><a href="{% url 'information' category_name=category subcategory_name=subcategory information_name=item %}">{{ item }}</a></li> {% endfor %} </ul> {% else %} <h4>No items for that subcategory</h4> {% endif %} views.py: from django.shortcuts import render, get_list_or_404, get_object_or_404 from django.http import HttpResponse from .models import Category, Subcategory, Information # Create your views here. def index(request): return render(request, 'basic_web/index.html') def search(request): return HttpResponse('Here you can search!') def browse(request): categories = Category.objects.all() context = {'categories': categories} return render(request, 'basic_web/browse.html', context) def view_category(request, category_name): category = get_object_or_404(Category,name__iexact=category_name) subcategories = get_list_or_404(Subcategory, parent=category) context = {'category': … -
Can't save data when posting form in Django
I'm following a Django tutorial to build a small site which you can add pages and category in the site, I defined a Page model as below: class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __str__(self): return self.title and defined a modelform as below: class PageForm(forms.ModelForm): title = forms.CharField(max_length=128, help_text="Please enter the title of this page") url = forms.URLField(max_length=200, help_text="Please enter the URL of the page") views = forms.IntegerField(widget=forms.HiddenInput(),initial=0) category = forms.ModelChoiceField(queryset=Category.objects.all(),help_text="Please choose a category for the page") class Meta: model = Page fields = '__all__' and views to add_page is: def add_page(request): if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): page = form.save(commit=True) print(page) # page.category = Category.objects.get(pk=int(request.POST.category)) page.views = 0 page.save() return index(request) else: print('error') form.errors else: form = PageForm() context_dict = {'form':form} return render(request,'rango/add_page.html',context_dict) But when I run the site and fill the information like this in the field: choose category 'HTML' in the select window fill 'w3c' in the name field fill 'http://www.w3cshools.com' in the url field and choose to 'create a page' but there's no response after clicking the button nor the data in the form is added into the database, I try to debug using … -
python django translation .mo files is blank
I am trying to create a project using for 2 languages german and English My Settings File LOCALE_PATHS = (os.path.join(BASE_DIR, 'app /locale'),) MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) How I am running this tool python manage.py makemessages -a This tool runs in debug mode processing locale en processing locale de python manage.py compilemessages This tool runs in debug mode processing file django.po in app/locale/de/LC_MESSAGES processing file django.po in app/locale/en/LC_MESSAGES File Location app/locale/de -rw-rw-r--. 1 root root 421 May 11 11:44 django.mo -rw-rw-r--. 1 root root 44K May 11 11:43 django.po I am not getting the desired translations, I feel might be something is going wrong in .mo file as the size is just 421bytes as comparted to .po file which is 44Kb -
Django: Use TinyMCE 4 in admin interface
After trying various ways to have TinyMCE as editor for my HTML content in Django administration I finally get it to work with this tutorial - https://github.com/ITCase-django/django-tinymce-4. However using this method I have to have Django 1.9 and "Grappelli" admin skin which I would rather avoid. I tried to remove it but it also removed TinyMCE. I also tried using HTMLField() from django-tinymce package, but this way got very crude editor with only handful of options (bold, italics, lists and that was that). Is there any "best-practice" to have Django (newest version) administration with full-fledged TinyMCE 4? -
django how to create iterable model instance with display __str__ values for foreign keys
I've been looking for a while but haven't found a solution to this one out of the box in Django. I am passing a model instance to the template and wish to show it as a read only table for users. I have tried many different approaches suggested on stackoverflow but nothing seems to achieve what I want which is the following: - Display all the fields in the Model instance to the user - Keep the template very genera so that when we change and move around the fields in the model, the display in the template will show the latest set of fields - For Foreign Key fields, display the str value from the related models to the user as this is more user friendly and not show the foreign_key_id value - Make this read only so it shows just the values or str values of the fields, and does not have drop-down choice boxes. Some of the approaches I have tried that don't quite get me there. Expect there is a good Django way to do this that I am not aware of: Approach 1 - Create a form for the data and render that in the … -
How can get data from database based on the url? Django
I have some semi-static pages in my Django app that get some information from the database (Page name, headline, etc..). Currently, for every page, I need to create a separate url in urls.py. from django.conf.urls import url from . import views urlpatterns = [ url(r'second', views.page, {'page_name': 'second'}), url(r'first', views.page, {'page_name': 'first'}) ] Is there a way I can get the page_name from the url and use that to decide what information to get from the database? I was trying something like this with page_name being a model field. url(r'^(?P<page_name>.*/)', views.page) -
What is the equivalent of `paramType: form` in the Core API of DJango Rest Swagger 2?
In the old django rest swagger, you can specify paramType: form in the docstring of the viewset and retrieve the parameter via request.data['param_x'], as follows: class FooViewSet(viewsets.ViewSet): """ Make something cool --- parameters: - name: param_x required: true paramType: form """ def list(self, request): param_x = request.data['param_x'] # do something cool... In the newer version, I usually use coreapi.Field to specify the properties of the parameters, and set the param type to the location argument key (e.g. core.api.Field(name='param_x', location='query')). All the available location value are discussed in the documentation. However, none of them seemed to be doing what I expected (not even location=form). How do you set the parameter type to form with the newer version of django rest swagger? I'm probably missing something here. -
Django adding an about page
I added an about page to my site, it should be a simple mission, but its not working. The main urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), url(r'^$', include('home.urls', namespace='home', app_name='home')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have a home app, this is home/urls.py: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^about/', views.about, name='about'), ] This is home/views.py: def about(request): return render_to_response('pages/about.html') I have the about.html in the home/templates/pages folder. The index page is being displayed fine, but when I an adding the link to the index page: <li> <a href="{% url 'home:about' %}">About</a> </li> I get the error: Reverse for 'about' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$about/'] And I went over the solutions on the site and couldn't find one for me. Thanks, Keren. -
ValueError: Incorrect timezone setting: TIME_ZONE
I want to reinstall openstack-dashboard, but encountered "ValueError: Incorrect timezone setting: TIME_ZONE". I can't find the configure file about 'TIME_ZONE'. How can i config 'TIME_ZONE'?Tanks a lot :) Thanks apt-get install openstack-dashboard Reading package lists... Done Building dependency tree Reading state information... Done openstack-dashboard is already the newest version (2:9.1.1-0ubuntu1). 0 upgraded, 0 newly installed, 0 to remove and 195 not upgraded. 2 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Do you want to continue? [Y/n] y Setting up openstack-dashboard (2:9.1.1-0ubuntu1) ... Collecting and compressing static assets... Traceback (most recent call last): File "manage.py", line 25, in execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/share/openstack-dashboard/openstack_dashboard/settings.py", line 377, in INSTALLED_APPS, File "/usr/share/openstack-dashboard/openstack_dashboard/utils/settings.py", line 111, in update_dashboards for key, config in import_dashboard_config(modules): File "/usr/share/openstack-dashboard/openstack_dashboard/utils/settings.py", line 44, in import_dashboard_config for key, submodule in six.iteritems(import_submodules(module)): File "/usr/share/openstack-dashboard/openstack_dashboard/utils/settings.py", line 29, in import_submodules submodule = import_module(name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/share/openstack-dashboard/openstack_dashboard/enabled/_9001_developer.py", … -
Django choicefield opacity or placeholder
I would like insert a placeholder to a ChoiceField and after change the opacity. Since I wasn't able to do it I try with another way... insert another choice into the list "('num_adult','Adult')" as fake placeholder (clearly if the user use this choice it will generate en error "chose adult number") but anyway I wasn't able to change the opacity of this first element. So how is possible put a placeholder or anyway take the control of the first element of choices to change the opacity? models.py: num_adu = models.CharField(max_length=1) form.py: n_adulti = (('num_adult','Adult'),('1','1'),('2','2'),('3','3'), ('4','4'),('5','5'),('6','6'), ('7','7'),('8','8'),('9','9')) numero_adu = forms.ChoiceField(choices=n_adulti, label="", initial='', widget=forms.Select()) class Meta: model = request_some fields = ['numero_adu '] I load {% load bootstrap3 %} and use {% bootstrap_form form %}. The following html code works good with all placeholder but not with choicefield: .form-control::-webkit-input-placeholder {opacity: 0.5; font-weight: bold; font-family: "Arial Black", "Times New Roman", Times, serif; font-size: 18px; color: #002699; } .form-control:-moz-placeholder {opacity: 0.5; font-weight: bold; font-family: "Arial Black", "Times New Roman", Times, serif; font-size: 18px; color: #002699; } .form-control::-moz-placeholder {opacity: 0.5; font-weight: bold; font-family: "Arial Black", "Times New Roman", Times, serif; font-size: 18px; color: #002699; } .form-control:-ms-input-placeholder {opacity: 0.5; font-weight: bold; font-family: "Arial Black", "Times New … -
Django Import/Export - No filter
I'm using the Django Import/Export module to export data from a Django project to different formats. I'm now trying to apply filters, which will depend on the logged date for exporting. Once looking this up, it appears as Django Import/Export should have a built in filter function, but this function is not shown in the admin page of my project. When currently exporting, all objects are exported. Does one have to activate this manually or should it already be there? If it should be there from the start, has anyone else had a similar issue where it's not showing and knows how to get it to show? -
A blog type menu in django
I am 99% certain that I did not use the correct name but I am trying to find information on how to create a menu that looks and behaves similar to a blog archive menu (just the correct name would already help me look in the right place). Specifically, the ability to click on a top level field and then get all it's children, see the following example: My intent is to create such a menu but then using fields from my database where an imaginary entry would be as follows: class foo(models.Model): a = models.CharField(max_length=200) b = models.CharField(max_length=200) c = models.CharField(max_length=200) The menu would than show all unique values of a as a top level (like the year in the example) and clicking on it would show all unique b values (like month in the example), clicking that would list all individual corresponding entries. -
Django redirect not working?
If a user wants to delete the post I want to return them back to their accounts page, however, with the code below it returns them back to the edit page where they can edith their posts. It doesn't delete the post? def airline_delete(request, id=None): instance = get_object_or_404(Airline, id=id) instance.delete() return redirect('upload_overview') url #account/upload/edit/ (Edit airline) url(r'^account/airlines/edit/(?P<id>[0-9]+)$', airline_update, name='airline_update'), #account/upload/delete/(Delete airline) url(r'^account/airlines/edit/(?P<id>[0-9]+)$', airline_delete, name='airline_delete'), How do I fix that? -
How to retrieve the result of a periodic Celery task?
I am using Celery 3.1 together with djcelery and the database result backend. I have got a few periodic tasks that run every 24h. I want to retrieve the result of one of those tasks from various places in the project (different applications) but I don't know how to get the right entry from the many objects in TaskMeta.objects.all() as I don't have the task_id. Is there a way to ask something like: "I want the result of the last entry corresponding to the execution of the periodic task <name_of_function>."?