Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form with sections
I am creating form for editing user option in my aplication. I want the form to look like this and this how my model looks like class AboutSomeOption(models.Model) chosen_option = models.SomeKindofField() field1 = models.CharField() field2 = models.CharField() field3 = models.CharField() field4 = models.CharField() field5 = models.CharField() emailAuthenticatedUser = models.OneToOneField(EmailAuthenticatedUser, one_delete = models.CASADE) The user can choose only one option(A, B or C). If he choose for example A. I want him to have the ability to fill the boxes associated with only option A . What is more I want to validate the fields associated with only option A. I want to save in the model information about choosen option. My model contains ForeignKey to user because each user must have the ability to edit form with options. How do I do that? -
Remove Django app name from path with custom domain Heroku
I have a Django app running on Heroku and just got a custom domain set up for it. I would like to be able to remove the app name from the path (www.customdomain.com/app-name). I have tried working with urls.py to give it an empty string regex and map that to my App's urls.py but that will only work with the index page. Any suggestions would be appreciated, thanks! -
Django with PythonAnywhere -- Operational Error no such table
I am trying to run my django project on PythonAnywhere and keep getting the error "OperationalError at / no such table: analysis_predictions" when I go to my site. I am using sqlite3 and python 2.7. It seems like this is a common error and I have followed a bunch of instructions to try to fix it including adding the full file path to my database settings. When I try to run python manage.py migrate in the pythonanywhere bash console I get the error "OperationalError unable to open database file". Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':'/Users/Dahlia/learning_python/scifairserver/db.sqlite3', } } Pythonanywhere console: img1 Current site: img2 -
Django Doesn't Serve STATIC_ROOT in DEBUG
I'm using Python 3.5 and Django 1.10 to run a development server: ./manage.py runserver 0.0.0.0:8000 In my settings.py I have: DEBUG = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' And an app directory, with a static subdirectory for its static files: proj/ proj/ ... app/ static/ a.txt ... static/ b.txt Pretty standard. However: Django doesn't serve the STATIC_ROOT when DEBUG = True. It returns app/static/a.txt for /static/a.txt alright, but not static/b.txt for /static/b.txt. Changing settings.py to read: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] Works - but then I have to comment out STATIC_ROOT (otherwise Django complains it can't be in STATICFILES_DIRS). Now, I can't just "use a different external static directory", e.g. static2, because I'm using django-sass-processor, which compiles .sass files into .css files, and puts these .css files in the STATIC_ROOT (which, as I've said, is inaccessible). Things I've tried: Settings up NGINX to serve that directory (like in a production environment). Works, but there just has to be another way. Configuring django-sass-processor to write the .css files into said "different external static directory", e.g. static2, and including it in STATICFILES_DIRS. Again, works, but it just can't be that complicated! Manually adding static files URLs in urls.py: if settings.DEBUG: urlpatterns β¦ -
Can't route reset email link to password reset view
I'm developing a password reset via email in django. I have already sent the email containing the password reset link correctly, the problem is that when the user clicks the password reset link in the email, is being redirected to the "send reset link to mail" instead of the "input new password link". Url's are as following: url(r'^login/$', views.Login, name='login'), url(r'^register/$', views.Register.as_view(), name='register'), url(r'^reset_password', views.ResetPasswordRequestView.as_view(), name="password_reset"), url(r'^reset_password_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', views.PasswordResetConfirmView.as_view(), name='reset_password_confirm'), The template that the user uses to input his email is this one (is used inside a base templated and striped for the sake of brevity): <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> The views that handle the send password reset link: class ResetPasswordRequestView(FormView): template_name = 'authentication/password_reset.html' success_url = 'login' form_class = PasswordResetRequestForm def get(self, request, *args, **kwargs): form = PasswordResetRequestForm() return render(request, 'authentication/password_reset.html', {'form': form}) def post(self, request, *args, **kwargs): ''' A normal post request which takes input from field "email" (in ResetPasswordRequestForm). ''' form = self.form_class(request.POST) form_email = '' if form.is_valid(): form_email = form.cleaned_data["email"] if self.validate_email_address(form_email): # uses the method written above ''' Verifies that the submited email is valid and gets its asociated user. If it is registered an email will be β¦ -
djanog 1.9 how to automatically update context in views
i have context that passes a value, that value is changing as the time goes. is there anyway i can update and send the value to the test.html automatically so the user do not need to refresh the page all the time to see the new value? def detail(request): LAST_DATA = request_data() context = { 'LAST_DATA': LAST_DATA, } return render(request,'index.html',context) if it is not possible in views can i use javascript in any way? -
How to display parent/child model data in django admin
I have invoice as the parent model and invoice details as the child model. Like to display the parent/child details in the Invoice model admin. Target is to list Invoices and related invoice details in admin. Invoice admin to list invoices Invoice 1: Invoice 2: Once on invoice admin, click on an invoice and list Invoice detail in a list_display Invoice 1: -details 1 ..... -details 2 .... ps. I know this is possible using a view and template. But I am not there yet. -
Django can't quite get the right path
I have this view here: from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.template import loader from django.views.generic import ListView class IndexView(ListView): def get(self, request): template_name = loader.get_template('home/blog.html') return render(request, template_name) return HttpResponse(template_name.render(request)) So if I remove return render(request, template_name) everything will be working properly but now when I trying to use return render(request, template_name) I get these error: <django.template.backends.django.Template object at 0x7f13916f46d8> places where Django tried to find the template: django.template.loaders.app_directories.Loader: /home/marton/documents/github/fmi-fall-2016/django/click_bait/miranda/home/templates/<django.template.backends.django.Template object at 0x7f13916f46d8> (Source does not exist) django.template.loaders.app_directories.Loader: /home/marton/documents/github/fmi-fall-2016/django/click_bait/env/lib/python3.4/site-packages/django/contrib/admin/templates/<django.template.backends.django.Template object at 0x7f13916f46d8> (Source does not exist) django.template.loaders.app_directories.Loader: /home/marton/documents/github/fmi-fall-2016/django/click_bait/env/lib/python3.4/site-packages/django/contrib/auth/templates/<django.template.backends.django.Template object at 0x7f13916f46d8> (Source does not exist) What should I do? Now is the time to say that eversince I have started this project I have had problem with paths, half an hour ago for some reason Django was searching in my virtual environment's folder. -
Django Rest Framework Cache Headers
I'm trying to cache some of my DRF api calls in a CDN. I need the following headers Cache-Control:public, max-age=XXXX This is pretty easy when you're using traditional django templating, you just add the @cache_page() @cache_control(public=True) decorators, but for DRF, I can't find anything similar. There's quite a bit about in mem caches, which I already have up, but I'd really like to get the CDN to take that load off my server all together, I'd like to cache the resulting queryset. I'm also using modelViewSets if that matters for anything: class EventViewSet(viewsets.ModelViewSet): serializer_class = EventViewSet permission_classes = (permissions.IsAuthenticatedOrReadOnly,) pagination_class = pagination.LimitOffsetPagination filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter,) filter_class = EventFilter search_fields = ('name','city','state') def get_queryset(self): -
Delete a Picture & thumbnails with sorl.thumbnail (Django)
I am working with Python 2.7, Django 1.9 and sorl.thumbnail. I cannot manage to create a view to delete in one time the original picture file, the Picture entry in the database, the thumbnail pictures generated by sorl.thulbnail, and the thumbnail_kvstore entry in the database. Here is my Picture model: class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=100, blank=True) user = models.ForeignKey(User, null=True, blank=True) exiflnglat = models.PointField(dim=3, geography=True, blank=True, null=True) objects = models.GeoManager() def __str__(self): return self.slug @models.permalink def get_absolute_url(self): return ('upload-new', ) And here is my view: from sorl.thumbnail import delete def deletepicnthumbs(request, pk): allpicfromuser = Picture.objects.filter(user=request.user) pictodelete = allpicfromuser.get(id=pk) delete(pictodelete) return redirect(adddetails) This view does not delete anything.. What I am doing wrong ? Thanks a lot -
Using Right Join and WHERE IN Clause
Consider these models class SearchableText(models.Model): searchable_text = models.TextField() class SearchTerm(models.Model): searchabletext = models.ForeignKey(SearchableText, on_delete=models.CASCADE) term = models.CharField(max_length=100) I want to write equivalent of this sql statement using django orm Select SearchableText.* right join SearchTerm on SearchTerm.searchabletext=SearchableText.id where SearchTerm.term in ("term 1","term 2","term 3") I also want to order the result based on number of matched terms, but I guess it would entitle another question. -
Django elasticsearch transport error no query found
I followed tutorial on: http://krzysztofzuraw.com/blog/2016/haystack-elasticsearch-part-two.html http://www.techstricks.com/django-haystack-and-elasticsearch-tutorial/ Everything works fine but when i try to query something from the search box it shows no result found and in the console this error appears. INFO base GET http://127.0.0.1:9200/haystack/_mapping [status:200 request:0.015s] INFO base PUT http://127.0.0.1:9200/haystack [status:400 request:0.018s] INFO base PUT http://127.0.0.1:9200/haystack/_mapping/modelresult [status:200 request:0.023s] WARNING base GET http://127.0.0.1:9200/haystack/modelresult/_search?_source=true [status:400 request:0.005s] Failed to query Elasticsearch using '(a)': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') Traceback (most recent call last): File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 71, in _wrapped return func(*args, params=params, **kwargs) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/init.py", line 569, in search doc_type, '_search'), params=params, body=body) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/transport.py", line 327, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 124, in perform_request self._raise_error(response.status, raw_data) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 122, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') ERROR elasticsearch_backend Failed to query Elasticsearch using '(a)': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') Traceback (most recent call last): File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 71, in _wrapped return func(*args, params=params, **kwargs) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/client/init.py", line 569, in search doc_type, '_search'), params=params, body=body) File "/home/alamin/.virtualenvs/msnb2/lib/python3.5/site-packages/elasticsearch/transport.py", line 327, in perform_request status, headers, data β¦ -
Why django not able to extend project level template?
This is my directory: myproject/ βββ frontpage β βββ __init__.py β βββ __init__.pyc β βββ admin.py β βββ admin.pyc β βββ migrations β β βββ __init__.py β β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ templates β β βββ intrafish β β βββ index.html β βββ tests.py β βββ views.py β βββ views.pyc βββ myproject β βββ __init__.py β βββ __init__.pyc β βββ settings β β βββ __init__.py β β βββ __init__.pyc β β βββ base.py β β βββ base.pyc β β βββ development.py β β βββ development.pyc β β βββ production.py β βββ urls.py β βββ urls.pyc β βββ wsgi.py β βββ wsgi.pyc βββ manage.py βββ requirements.txt βββ templates βββ base.html I am trying to extend base.html inside index.html in frontpage app. My base.html: {% load i18n %} {% load url from future %} {% load staticfiles %} {% block header %} {% endblock %} My index.html: {% extends "base.html" %} My wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "makemeacurry.settings") application = get_wsgi_application() My manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "makemeacurry.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) I definitely feel that it is because I segregated my settings in different β¦ -
Django Rest : Serializing object with One-to-One Relationship
I'am trying to insert a new student record which have a onetoone relationship with the Account model but i've got this exception even if the record is inserted in the database. /***error****/ Exception Type: AttributeError Exception Value: type object 'Student' has no attribute 'account_id' /***db shell****/ sqlite> select * from students ; 1|first grade I also can see the new record in the admin interface but i don't know why the account field take the null value. request :api/v1/students/ { "count": 1, "next": null, "results": [ { "grade": "first grade", "account": null } ], "previous": null } Here is my student model and manager : class StudentManager(models.Manager): def create_student(self, account, grade, **extra_fields): """ Creates and saves a Student Account with the given userId and grade """ account = get_object_or_404(Account, id=account) now = timezone.now() if not grade: raise ValueError('Grade must be specified') student = self.model(account=account, grade=grade, ) student.save(using=self._db) return student class Student(models.Model): objects = StudentManager() account = models.OneToOneField(Account, to_field='id', on_delete=models.CASCADE, primary_key=True,) grade = models.CharField(_('grade'), max_length=255, blank=True, help_text=_('student grade')) class Meta: db_table = "students" verbose_name = _('student') verbose_name_plural = _('students') Account is a model that inherits from the AbstractBaseUser. Here is the Student serializer : class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student β¦ -
How to use AutoSlug in Django
I want to use seo friendly URL's for my shopping site developed on Django 1.10. I would like to know how can i easily use slug for my category and products pages instead of pk. I have heard about AutoSlug which use product name as slug, please let me know how can i use this. Below is my code which is currently using id as the URL models.py from django.db import models class Category(models.Model): category_name = models.CharField(max_length=250) slug = models.SlugField() category_image = models.CharField(max_length=1000) def save(self, *args, **kwargs): super(Category, self).save(*args, **kwargs) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=250) product_description = models.TextField(max_length=5000) product_mrp = models.CharField(max_length=100, default='mrp') product_price = models.CharField(max_length=100) product_image = models.CharField(max_length=1000) product_image1 = models.CharField(max_length=1000) product_image2 = models.CharField(max_length=1000) product_brand = models.CharField(max_length=1000, default='brand') urls.py from django.conf.urls import url from django.contrib import admin from . import views app_name = 'shopping' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^(?P<pk>[0-9]+)$', views.CategoryView.as_view(), name='category'), url(r'^(?P<pk>[0-9]+)$', views.ProductView.as_view(), name='product'), views.py from django.shortcuts import render, get_object_or_404 from django.views import generic from .models import Category, Product def index(request): all_category = Category.objects.all() context = {'all_category': all_category} return render(request, 'shopping/index.html', context) class CategoryView(generic.DetailView): model = Category template_name = 'shopping/category.html' class ProductView(generic.DetailView): model = Product template_name = 'shopping/product.html' -
Fill a form after autocompletion, using django
For editing existing/creating new database records, I would like to have an autocompleting widget, that after inserting the name of the item to insert, if the item already exist in the database, fill the other fields of the form with the database values, so that they can be edited; otherwise, if the entry do not exist in the database, allow to insert the items from scratch. I have already implemented the autocomplete using diango-autocomplete-light. How can I intergrate this solution for fill the other fields as well? Otherwise, is there any alternative solution that can work this way? -
Django ModelForm for updating model doesn't save Image and throws an error
I use Django 1.8.15 and python 2.7.12. I have a model: class Page(models.Model): title = models.CharField(max_length=255,) description = models.TextField(blank=True,) img = models.ImageField(upload_to="img/", blank=True, null=True) ... def save(self, *args, **kwargs): try: this = Page.objects.get(id=self.id) if this.img != self.img: this.img.delete(save=False) except: pass super(Page, self).save(*args, **kwargs) ModelForm for updating my model: class PageForm(forms.ModelForm): class Meta: model = Page fields = ('title', 'description', 'img') view: def page_update_view(request, template, id): mypage = get_object_or_404(Page, id=id) context_dict = {} form = PageForm(instance=mypage) if request.method == "POST": form = PageForm(request.POST, request.FILES or None, instance=mypage) if form.is_valid(): form.save() return redirect('page_update', id=id) else: print(form.errors) context_dict["form"] = form return render(request, template, context_dict) Form in the template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="update" /> </form> When I save form without image it works fine. But when I upload an image there is always an error: Exception Type: OSError Exception Value: [Errno 22] Invalid argument Part of traceback: File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "C:\mysite\mysite\pages\views.py" in page_update_view 588. form.save() File "C:\Python27\lib\site-packages\django\forms\models.py" in save 459. construct=False) File "C:\Python27\lib\site-packages\django\forms\models.py" in save_instance 105. instance.save() File "C:\mysite\mysite\pages\models.py" β¦ -
Django: Contribute to third party app django-lazysignup
I want to contribute to django-lazysignup a django third party app. I tried so far the following steps I set up a regular django app named custom-user I used virtualenv and install required library on virtualenv I fork and clone the github repository of django-lazysignup I run the sudo pip install -e /path/to/folder/django-lazysignup command I am trying to run command python manage.py makemigrations on custom-user project but it showing ImportError: No module named 'lazysignup'. Any help will be appreciated -
How to add custom key to Django Allauth email confirmation link
I have a Django project with the django-allauth app. I provide with registration form in different places on the website and need to know which one was used. I think that I need to add extra key to email confirmation link and in this case I will be able to distinguish between them. Is it possible to achieve such behavior? -
Django Custom User Model Login System
I've created a custom user model (AbstractBaseUser) so that user could login into my website. The problem is that I want to keep using Django's default user and authentication system for the admin so that staff could easily log in and manage stuff. I saw a lot of tutorials but all of the instruct to change the setting AUTH_USER_MODEL, but if I change that I won't be able to keep using Django's default user. Is there any solution for this? Thanks in advance. -
Best practice so a database supports to query different entries with some common attributes
This is an abstract description of my problem without any specific technology/framwork. I would like to know what the best practice is to model the following (toy) example: Suppose I am selling toys. I have f.e. teddy bears and small elephants and zebras. They share the following attributes: price number of eyes fluffyness-rating name description So I would like to create a table "toy" that stores this information and makes it easy, f.e. to query the 10 cheapest toys. I also want to store the animals explicitly, with all the information I get from the manufacturer, let's say their weight, or how many colors they have. This includes information that is only given for a subset of animals, f.e. the elephants have a "number of tusks", while the zebras do not. There are two reasons for that: I might be using some of the common information (f.e.: weight) in the toys table at a later point. maybe I am going to run a different service that only lists animals with tusks. My problem is: I would like to use reference fields, so a toy only has references to some of the fields in one table, f.e. the zebra table. If β¦ -
Python Django Oscar Run Issue
I am trying to run the "python manage.py runserver" command but every time terminal shows the error. I have executed the following commands I have installed mysql also but still i got error. Help is appreciated in advance. Thank You. Here is my Manage.py """ Django settings for emporium project. Generated by 'django-admin startproject' using Django 1.9.10. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os from oscar.defaults import * from oscar import OSCAR_MAIN_TEMPLATE_DIR from oscar import get_core_apps location = lambda x: os.path.join( os.path.dirname(os.path.realpath(__file__)), x) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '_mg*0yn@x+6)oug^&r9&$eev7@b4un6h8j(+4y1(v9trme##pf' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'compressor', 'widget_tweaks', ] + get_core_apps() SITE_ID = 1 MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'oscar.apps.basket.middleware.BasketMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ] ROOT_URLCONF = 'emporium.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ β¦ -
Django: Static/Media Files different server
I have concern with Media files in Django. I am just wondering why some of the tutorials recommends to have a different Server instance for media? What are the benefit for this? Does it have a big impact or change of speed of my site? If I'm going to have a different server for media, what would be the specs(# of RAM, Disk Space, etc.)? Same question goes for Postgre. Currently my application is running in GCE. Python 2.7,Django 1.8 with nginx and uWSGI Compute Engine instance : n1-standard-2 (2 vCPUs, 7.5 GB memory) -
How to pass along get parameters in Django?
Lets suppose a user enters your page and navigates through some pages: start_page > a_page > another_page > finish_page Assuming a GET parameter was set when the navigation started in the first page (start), how do I carry on passing this parameter through the other pages? I don't want to hard code the parameter in any of these pages because each of them could have a lot of links, leading to other pages. Should it be accomplished through a middleware? -
How to integrate ionic 2 with Django
I've worked with Django for web apps but now i have to implement it in my mobile application that is use django as the backend for my application. Can anyone please suggest how to integrate django with ionic 2 ?