Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize NotFound exception --- Django REST Framework
Assume a minimal application with a person model, a ModelSerializer and a corresponding ReadOnlyModelViewSet. Only one entry exists in the database so when requesting /person/1 the response correctly is: { "name": "RandomName1" } When requesting /person/2 the response is: { "detail": "Not found." } I want to customize this. Even though I read the documentation it is not clear how I can customize this. -
No module named foo.settings Django Import Error
I'm gettings a Django import error after just cloning a repo for the first time, and I've looked at all previous questions and can't figure out what my problem is... Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named foo.settings But I have my settings.py file in the foo directory? Project app1 app2 foo settings.py wsgi.py urls.py app3 manage.py I am really confused. Here is my manage.py # !/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hieta.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) -
How to create a filter bar in template? Django
I'm not asking for the html, but the django implementation. Within my model I have four categories for my car model: make, year, mileage and cost. The user can select multiple categories and it'll filter the results on the page. Will the filter bar a form similar to a search bar? I'm not sure how this would be implemented. Any ideas on how I can get started? -
Django - running code on every startup but after database is migrated
I thought there was an easy answer to this in recent versions of Django but I can't find it. I have code that touches the database. I want it to run every time Django starts up. I seem to have two options: AppConfig.ready() - this works but also runs before database tables have been created (i.e. during tests or when reinitializing the app without data). If I use this I have to catch multiple types of Exceptions and guess that the cause is an empty db: def is_db_init_error(e, table_name): return ("{}' doesn't exist".format(table_name) in str(e) or "no such table: {}".format(table_name) in str(e) ) try: # doing stuff except Exception as e: if not is_db_init_error(e, 'foo'): raise else: logger.warn("Skipping updating Foo object as db table doesn't exist") Use post_migrate.connect(foo_init, sender=self) - but this only runs when I do a migration. I've settled for option 2 so far as I don't like the flakey try/except but it often trips me up when I'm developing locally because I need to remember to migrate to run my init code. -
installing and running django on windows 8
I am a complete newbie in Web Development, I am currently a Preschool Teacher and trying to switch careers. I am enrolled in Interactive Web Design 221 well I was I had to drop the class because I could not seem to figure out how to properly install and configure Django, Selenium, and Geckodriver for Windows 8. I have uninstalled and reinstalled Python, Django, Selenium several times but I still can't get Django to run when I type from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert'Django' in browser.title Traceback (most recent call last): File "functional_tests.py", line 6, in assert 'Django' in browser.title AssertionError This doesn't work and $ django-admin.py startproject superlists this command doesn't work either. As I said I am a complete newbie at this stuff, and I am not sure why this doesn't work. A step by step instruction on getting all of this installed properly with the correct paths and to make sure I am installing the correct versions. -
Python logging works in shell, but not in views
I have been following the Django Logging docs but haven't been able to produce logs. All of this is within a virtualenv. My views.py file contains import logging logger = logging.getLogger(__name__) def index(request): logger.debug('Index page') return render(request, 'app/index.html') In settings.py I have: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/pathtologfile/debug.log', }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } No logs are appearing in the log file from views.py when I navigate to the index page. However, if I use the django shell to execute the following commands the log will show up in the log file: >>>import logging >>>logger = logging.getLogger(__name__) >>>logger.debug('shell') How can I get logs from view.py (or any file for that matter)? I have tried the following with no result: Ensured log levels are all set to debug Tried naming logger 'root' or '' Tried 'disable_existing_loggers': False and True Tried answers on http://stackoverflow.com/questions/tagged/django-logging Tried setting full write permission on the log file Is there anything wrong with my settings? Any where to even start looking at to debug this? -
Django Master to Child table with customization
I have master to child tables, need a solution to render it with below condition. Master Table Fields:- Person product categ price image field1 field2 Child Table (User customised):- User Product categ customprice customfield1 customfield2 Query:- totalrecords = Master.objects.filter(Person=person1).filter(categ=catogory1) enabledrecords = Child.objects.filter(user=user).filter(categ=categ1) product in child is foreign key from Master. In template I will extract the master fields(in for loop) but if price and customfields exists in child then I need to take child object using product relation, otherwise populate these from master table. Here the confusion comes, {% for obj in totalrecords %} if obj.id in enabledrecords (using product forign key) then Get en_obj from enabledrecords__product {{obj.id}} {{en_obj.id}} {%if en_obj.customprice%} {{en_obj.customprice}} {%else%}{%obj.price%}{%endif%} -->do same for other customfields if obj.id not in enabledrecords {{ obj.id }} <p> Product not customized click here to customise </p> Please advice. -
Django rest framework and php "API JMeter testing"
I have created same API in python (DRF) and PHP both are working well but when I check on JMETER with load, DRF API response is not good In 1 second for 800 user, PHP API work fine but Django Rest Framework API fail for 153 users. Is there any execution time or memory concept? Thanks! -
Django show and save form fields
I'm a django beginner and i'm trying to make a form with a foreignkey to user and a booleanfield for each user presented in models. I've made it in django admin. Now i want to make it shown on the website and for the players that i check the checkbox to update on django admin. When i'm trying to make them with ModelForm it shows a dropdown for Players. I want them to be shown like this: checkbox - player checkbox - player checkbox - player models.py class Player(models.Model): player = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, related_name='jucator') selected = models.BooleanField(default=False) def __str__(self): return u'%s' % self.player forms.py from django.forms import ModelForm from football_app.models import Player class SelectedForm(ModelForm): class Meta: model = Player fields = ['selected', 'player'] views.py def check_user(request): data = dict() data['players'] = Player.objects.all() if request.method == 'POST': form = SelectedForm(request.POST) if form.is_valid(): (how should i write here to update the django admin booleanfield for each user) else: form = SelectedForm() data['form'] = form return render(request, 'checkbox.html', data) -
Django how to get multiple context_object_name for multiple queryset from single view to single template
I want to run multiple queryset from single view. I have done for single get_queryset and single context_object_name to pass into index.html template : class IndexView(generic.ListView): template_name = 'doorstep/index.html' context_object_name = 'all_hotels' def get_queryset(self): return Hotel.objects.all().order_by('rating').reverse()[:3] Now, i need to run this queryset Hotel.objects.all().order_by('star').reverse()[:3] from same IndexView and pass context_object_name from this querset to same template_name. I get the value as {% for hotel in all_hotels %} in the template -
How to get the name of the file from the filefield?
I know this question has been asked a lot of times but I am not able to find a nice solution to this. Here is my model: class Song(models.Model): song_title = models.CharField(max_length=200, null=False, blank=False) audio_file = models.FileField(default='', null=True,blank=True) @property def filename(self): return os.path.basename(self.audio_file.name) def __str__(self): return self.song_title I have done all this, but I am still not able to get the file name.So in the admin page, I uploaded a new song with the name : song.mp3. In the admin panel , it shows like this : Currently: ./song.mp3 I need to get the name song.mp3 , how can I do so? I tried doing this in the python shell: d = Song.object.get(pk=1) d.audio_file.name but it only shows this : '' -
Django. Import model in settings.py
I know, that somebody asked the question already here. But the answers doesn't solve my problem. I need the names of all objects of one model. So how could I solve this? I want something like this: from app_name.models import User User_list = list(User.objects.values_list('username', flat=True)) -
Merging two databases in Django through serialization
On a django application, i'm planning to have multiple databases that don't know each other (they won't even have a network communication between them). These databases will use the same schema, and each have their own data. I wish, at regular intervals, to be able to merge the data between some of these databases through serialization/deserialization. However, this means some of the data being merged might use the same primary keys, which will cause problem during deserialization. Obviously, the data structure is reasonably complex, with many foreign keys relationship. And unfortunately, many tables have no obvious natural keys. I'm currently considering to scan through all the objets during deserialization, to change their primary keys, and update all foreign keys. What is the best way to do this "automatically" through django? And is there some obvious pitfalls of this method? -
Tabbed_admin didn't work with django-jet
i found a way to divide my fields into tabs, and there is a Tabbed Admin, but it not working with Django-jet (1.0.4). In console written that the $(...).tabs() not a function... Is it possible to somehow Tabbed Admin and Django-Jet be friends? Tabbed admin and Django-Jet conflicting -
How do I add two applications/pages onto my Django-site?
I have been trying twice now to add a second application onto my Django-site, whereas it results in some kind of errors. I have followed instructions from youtube which has been of great help but now I am stuck at adding a second page. My first one is working just fine. This is my main url.py: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^table/', include('table.urls')), url(r'^', include('login.urls')), ] This is my main settings.py: INSTALLED_APPS = [ 'login', 'table', .... This is my working page url.py: from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] This is my working page view.py: from django.shortcuts import render def index(request): return render(request,'login/login.html', {'content': ['username', 'password']} ) This is my non-working page url.py: from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name = 'index'), ] This is my non-working page view.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request,'table/table.html') Thus far I have thought of the index(request) being an issue since they are both having the name "view" and same function name...? And I have no idea where to look on … -
Is it possible run makemigrations with deleted schema?
My all SQL schema was deleted cause of windows10 initialization. So, I wanna run makemigrations with already existing django project code(with so many lines......). But "python manage.py makemigrations" not works with error 'Table doesn't exist'... Is there some methods overcome these situations ??? -
Multiple Django apps sharing the same URL patterns
I have multiple apps that share almost the same URL patterns, defining almost the same views. Currently i have a urls.py for each app to serve its routing. What i want to do is to group the similar patterns into a single shared_urls.py file then use it in those apps. To make it easy to understand, suppose (just an example here) i have a blog app and an archive app. They both define a pattern and view for /post, /comment and /user. So instead of each of them having its own urls.py defining the same pattern, i want to define these patterns in one place then use it in each of the apps, while loading the correct app view. Current Vs Wishing Current project urls.py url(r'^blog/', include('blog.urls')), url(r'^archive/', include('archive.urls')), blog urls.py url(r'^post/', views.post()), url(r'^comment/', views.comment()), url(r'^user/', views.user()), archive urls.py url(r'^post/', views.post()), url(r'^comment/', views.comment()), As you see the two apps share almost the same patterns but each has its own implemented view. Wishing project urls.py url(r'^blog/', include('blog.urls')), url(r'^archive/', include('archive.urls')), shared_urls.py #How to bind with the correct app's view! url(r'^post/', views.post()), url(r'^comment/', views.comment()), blog urls.py url(r'^user/', views.user()), url(r'', include(shared_urls)), archive urls.py url(r'', include(shared_urls)), -
how to find file extension in case of file list?
How can i find extension of list of files .I am currently using os.path.splitext which is not working.Please suggest any other method in case of file list. My code goes here: files = request.FILES.getlist('media') for f in files: p = os.path.splitext(f)[1] print p it shows the error 'InMemoryUploadedFile' object has no attribute 'rfind'. Thanks in advance -
CSRF verification failed. Request aborted. in django ajax post,nothing work, what to do?
Ajax code <script type="text/javascript"> $(document).ready(function(){ $("#join-form").on('submit', function(e){ e.preventDefault(); var email = $("#id_email").val() var name = $("#id_name").val() var data = {}; data.email = email data.name = name var csrf_token = $('#join-form [name="csrfmiddlewaretoken"]').val(); data["csrfmiddlewaretoken"] - csrf_token; $.ajax({ method: "POST", data: data, url: "subscribe/add/", csrfmiddlewaretoken: csrf_token, success: function(data){ console.log("ok"); email.val('') name.val('') }, error: function(data){ console.log('error'); }, }); }); }); </script> this code of views.py def subscribe(request): if request.method == 'POST': email = request.POST.get('email') name = request.POST.get('name') forms = Subscribers(email=email, name=name) forms.save(commit=False) response_data['email'] = forms.email response_data['name'] = forms.name return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) this is my form <form method="POST" id="join-form" action="" enctype='multipart/form-data' class="form-group" > {% csrf_token %} <div class="form-group" > {% if forms.errors %} <span> {{ forms.errors }} </span> {% endif %} <label>Ваш Email: </label> {{ forms.email }} </div> <div class="form-group"> <label>Ваше Имя: </label> {{ forms.name }} </div> <input type="submit" value="Подписаться" class="btn bg-gray gbbg" role="button"/> </form> i try add this but not working, who say me try it, say go fff**** youself i try add this but not working, who say me try it, say go fff**** youself i try add this but not working, who say me try it, say go fff**** … -
Django/Celery - can't see debug logs while running python manage.py runserver
I recently integrated celery==3.1.0 with out companies django project. Please find below the directory structure and few of the code details. website/ apps/ app1/ forms.py models.py tasks.py urls.py views.py app2/ forms.py models.py tasks.py urls.py views.py __init__.py settings/ base.py <- contains base settings celery.py local.py <- contains dev/prod settings, imports all settings from base.py __init__.py urls.py wsgi.py website/apps/__init__.py: from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from website.settings.celery import app as celery_app website/settings/celery.py: from __future__ import absolute_import from django.conf import settings from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings.local') app = Celery('website.apps') app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS) # @signals.setup_logging.connect @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) website/apps/app1/tasks.py: from __future__ import absolute_import from celery import shared_task @shared_task def add(x, y): return x + y celery settings in website/settings/base.py: BROKER_URL = 'amqp://guest:guest@localhost//' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYD_HIJACK_ROOT_LOGGER = False CELERYD_LOG_FILE = None CELERY_REDIRECT_STDOUTS = False CELERYD_LOG_LEVEL = 0 Currently, I have set DEBUG=True on my machine. After running python manage.py runserver, I do not see any debug logs on the console. I just see the requested url and the served static files. Prior to celery setup, … -
How do I add pagination to my index.html ?
Here are my codes(it works fine): #views.py class IndexView(generic.ListView): template_name = 'index.html' context_object_name = 'home_list' queryset = Song.objects.all() paginate_by = 1 def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['all_artists']=Artist.objects.all() context['all_songs']=Song.objects.all() context['all_albums']=Album.objects.all() return context base.html(which is extended by index.html): #base.html {% block content %}{% endblock %} {% block pagination %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page={{ page_obj.previous_page_number}}">Previous</a> {% endif %} <span class="page-current"> Page {{page_obj.number}} of {{page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <a href="{{ request.path }}?page={{page_obj.next_page_number}}">Next</a> {% endif %} </span> </div> {% endif %} {% endblock %} And my index.html: {% extends 'base_generic.html' %} {% block title %}<title>Listen to songs </title>{% endblock %} {% block content %} <h3>Best Songs</h3> {% for song in all_songs %} <ol> <li><a href="{% url 'music:song_detail' song.id %}">{{song.song_title}}</a> <img src="{{song.song_logo}}" heigt=112, width=114/> <br></li> </ol> {% endfor %} <h3>Best Albums</h3> {% for album in all_albums %} <ul> <li title="{{album.album_title}}"> <img id="img_{{album.id}}" src="{{album.album_logo}}" heigt=112, width=114 /> <p><a href="{% url 'music:album_detail' album.id %}">{{album.album_title}}</a></p> </li> </ul> {% endfor %} {% endblock %} So when I compiled this, I got this window : Image here But in all pages, it stays the same.What I want is to display 1 song per page.Help … -
Django social authentication client id is not provided
I am implementing social authentication in stackoverflow using this tutorial I got the following error when clicking the link <li><a href="{% url "social:begin" "stackoverflow" %}">Login with Stackoverflow</a></li> Application Login Failure An error occurred while login into an application. Error Details error description: client_id not provided this is the configuration i tried SOCIAL_AUTH_STACKOVERFLOW_CLIENT_ID = '9999' SOCIAL_AUTH_STACKOVERFLOW_OAUTH2_KEY = 'xxxxxxxxxxxxxxxxxxxxx' SOCIAL_AUTH_STACKOVERFLOW_OAUTH2_SECRET = 'yyyyyyyyyyyyyyyyyyyyy' Anyone tell me what is the problem with my configurations? -
Django Error while installing graphite
I am following Graphite tutorial to install graphite on my ubuntu system, as soon as I try to run this command sudo graphite-manage syncdb this exception is thrown django.core.exceptions.ImproperlyConfigured:django.db.backends.postgresql_psycopg2 isnot an available database backend.Try using django.db.backends.XXX, where XXX is one of:ubase, umysql, uoracle, usqlite3 Error was: No module named postgresql_psycopg2.base I did some search to find out the cause and tried this but its still persisting, can anybody help please -
Ajax is not rendering the page for my comment form
kindly help me to solve the problem of not rendering or updating the page after using the ajax call on my comment form. The content remains in the content box and not updating the page. base.html: $("#comment-form").submit(function(event) { event.preventDefault(); // var url= $(this).attr('action'); $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function(response){ alert(response); }, error: function(e){ console.log(e); } }); }); post_detail.html: {% extends 'base.html' %} {% block title %}{{ post.title }}{% endblock %} {% block content %} {{ post.title }}<br> Published by {{ post.user }}<br><br> {{ post.content|linebreaks }}<br> {% if post.user == request.user %} {% endif %} <hr> <h1><b>Comments</b></h1> {% for comment in comments %} <blockquote> <p>{{ comment.content }}</p> <footer>via {{ comment.user.username }} | {{ comment.timestamp|timesince }} ago | <a class="reply-btn">Reply</a></footer> <div class="replied-comments" style="display:none;"> <blockquote> {% for child_comment in comment.replies.all %} <p>{{ child_comment.content }}</p> <footer>via {{ child_comment.user.username }} | {{ child_comment.timestamp|timesince }} ago</footer> {% endfor %} </blockquote> <form method='POST' action='.'> {% csrf_token %} {{ comment_form.as_p }} <input type='hidden' name='parent_id' value='{{ comment.id }}'></input> <input type='submit' value='Reply' class='btn btn-default'> </form> </div> </blockquote> <hr> {% endfor %} <form method='POST' action='.' id="comment-form"> {% csrf_token %} {{ comment_form.as_p }} <input type='submit' value='Post' class='btn btn-default'> </form> {% endblock %} post_detail view: def post_detail(request, slug): post = … -
Group joined data in django
Given the following models: class ErrorPhrase(models.Model): ... document = models.ForeignKey(to=Document, on_delete=models.CASCADE) text = models.CharField(max_length=256) start_index = models.PositiveIntegerField() correct_form = models.CharField(max_length=256, blank=True) class ErrorTag(models.Model): ... error_phrase = models.ForeignKey(to=ErrorPhrase, on_delete=models.CASCADE) error = models.CharField(max_length=1, choices=error_choices) category = models.CharField(max_length=1, choices=category_choices) type = models.CharField(max_length=2, choices=type_choices) I want to retrieve all the ErrorPhrase entries with their associated ErrorTags. I have used the values function like below: error_phrases = ErrorPhrase.objects.values( "id", "text", "start_index", "errortag__error", "errortag__category", "errortag__type") But this way I get one row of data for each of different ErrorTags of a particular ErrorPhrase object. For example: { "errortag__error": "S", "errortag__type": "WO", "errortag__category": "S", "text": "test", "id": 40, "start_index": 463 }, { "errortag__error": "T", "errortag__type": "OO", "errortag__category": "P", "text": "test", "id": 40, "start_index": 463 }... I'm looking for a way to group the data by ErrorPhrase fields ("id", "text", "start_index") and get all the ErrorTags of a particular ErrorPhrase object in a group. Something like this: { "text": "test", "id": 40, "start_index": 463, "error_tags": [{ "errortag__error": "S", "errortag__type": "WO", "errortag__category": "S"}, { "errortag__error": "T", "errortag__type": "OO", "errortag__category": "P"}] },... Can I do it in one query using Django QuerySet API ?