Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why doesn't django update form repopulate my fields with existing data
This is the template that should update existing model. I have looked through multiple tutorials but I still don't have a clue why my form's fields aren't prepopulated. Does anybody have any idea what's wrong? My form: class UpdateSiteForm(forms.ModelForm): class Meta: model = Site fields = ('name', 'description', 'URL',) my model: class Site(models.Model): name = models.CharField(max_length=255,unique=True) description = models.TextField(default='') URL = models.URLField(default=None) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None) my template: {% extends 'base.html' %} {% block content %} <div class="updatesite"> <h2>{{site.name}} Update-page</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Update</button> </form> </div> {% endblock %} my views.py def updatesite(request,id): site = get_object_or_404(Site, id=id) dev = request.user if request.method == 'POST': form = UpdateSiteForm(request.POST,instance=site,initial=site) if form.is_valid(): form.save() return redirect('userhome') else: form = UpdateSiteForm() return render(request,'updatesite.html',{'site':site, 'form': form}) -
Set Environment Variables for Django on Dreamhost and Passenger WSGI
I'm trying to set an environment variable for Django that will not be in the source, in this case an email password. This is the example I'm trying to emulate: server: /etc/systemd/system/gunicorn-superlists-staging.ottg.eu.service [Service] User=elspeth Environment=EMAIL_PASSWORD=yoursekritpasswordhere WorkingDirectory=/home/elspeth/sites/superlists-staging.ottg.eu/source The example uses nginx and gunicorn, but I'm attempting a setup with Dreamhost, Linux and Passenger wsgi. Here is my file structure: . |-- \ ~ |-- __pycache__ |-- database |-- etc |-- passenger_wsgi.log |-- passenger_wsgi.py |-- passenger_wsgi.pyc |-- public |-- source |-- static |-- superlists |-- testGoat |-- tmp `-- virtualenv superlists is where the project is located. So, how should I go about setting the Environment Variables in this case? -
Ammending Django Views/Models for Cart Quantity
I have a Django cart project which adds and removes products from the cart. I can't seem to workout how I can add a quantity amount to the cart. I know I will need to add a quantity field to the model. But where do I change the logic - on the actual model or the view? Models.py (including manager) from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from catalogue.models import Product User = settings.AUTH_USER_MODEL # Create your models here. class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) # quantity = models.IntegerField() total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def pre_save_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': … -
Nginx can't download files bigger than a few MB's (403 forbidden)
Something really strange is happening. Whenever i try to download a file that is bigger than a few MB's, it returns a 403 forbidden message. This is my sites-enabled conf: server{ listen 80; server_name braduletfumat.go.ro; location = /favicon.ico {access_log off; log_not_found off;} location /static/{ root /var/www/BrdWeb/Bradulet/; } location / { include proxy_params; proxy_max_temp_file_size 0; proxy_pass http://unix:/var/www/BrdWeb/Bradulet/Bradulet.sock; } location /protected/{ internal; proxy_max_temp_file_size 0; alias /var/www/BrdWeb/Bradulet/; } } And the nginx conf: user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; client_max_body_size 4G; } I am using django and X-Accel-Redirect for serving the files. Before, it returned an … -
Getting all objects with equal M2M fields
I am looking for a way to filter for all objects of the same type that have the same querysets for a M2M field. class Comment(models.Model): user = models.ForeignKey(User, related_name='comment_user') content = models.CharField(max_length=5000, null=True) private_to = models.ManyToManyField(User, null=True, related_name='private_to') Given a comment object, I want to retrieve all other comments who have an equal M2M field (i.e. if the private_to field returns User 1 and User 2 for the comment, it will find all the other comments that contain exactly both of those users in the private_to field.) Is there a concise, built-in way to do this? -
XlsxWriter exported file sometimes can't be opened by Numbers
This is a server rendered file, so it's saved to a Django HttpResponse with {"in_memory": True} During QA testing, sometimes the file can't be opened by Numbers. It says "calendar.xlsx" can't be opened right now. The file format is invalid. Yet it opens in LibreOffice just fine. No one here uses Windows so I haven't tested Excel yet. What info can I gleam from the file that will shed more info on this? -
HOW to create a multi-step form using ModelForm is django
I am attempting to create a multistep modelform because I want to save the data. I am using the formtool called FormWizard, however I am having difficulty using it for a model form Instructions User clicks on create patient link User opens patient form User inserts patient data User submits form if form is invalid: redisplay form with error if form is valid: move to next form enter symptom data submit form if form is invalid: redisplay form with error if form is valid: move to next form enter disease data submit form if form is invalid: redisplay form with error if form is valid: User is redirected to general form that has patient + symptom + disease information. THIS is the view that will create the multi-step model form class ConsultationCreate(SessionWizardView): instance = None def get_form_instance(self, step): if self.instance is None: self.instance = Patient return self.instance template_ = 'data/multi_form.html' def done(self, form_list, **kwargs): self.instance.save() def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] logr.debug(form_data[0]['NIS']) logr.debug(form_data[1]['identity']) logr.debug(form_data[2]['identity']) return form_data This is the error it produces : ValidationError at /patient/create ['ManagementForm data is missing or has been tampered.'] This is the code ================================================================== urls.py from django.conf.urls import url from data.views import … -
Is there a way to run tests in Django without creating database?
I'm getting an error in a simple functional test that I suspect is related to creating a large database. The error is ConnectionRefusedError: [Errno 111] Connection refused It takes sometime until database is created and to test if the error is related to this, I would run the test without creating the test database. Is it possible to run tests with python manage.py test functional_test.py skipping the database creation? -
uploading csv to database fails on cells that are null
Django 2.0 PostgreSQL 10 It is crucial that my app allows users to upload data in bulk, for which they can upload a csv file. However for any field that is non-string, if a cell on the csv file is Null then it returns the following error: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] This exception was copied in the case of a empty cell under the Date column, however it's the same for int and float. The exception is straightforward. However according to the csv documentation, the value None is written as the empty string although this is stated under the csv.writer section and not under csv.reader. I'm having a hard time understanding why the ORM is not converting empty strings to None or Null values that the database does understand, and as stated in my models.py, it accepts. models.py: class Control(models.Model): date = models.DateField(default=date.today, null=True, blank=True) kilos = models.FloatField(null=True, blank=True) views.py: class ControlFileUpload(View): def get(self, request): return render(request, 'csv_upload.html') def post(self, request): file = request.FILES['csv_file'] _control_bulk_data_upload(file) #imported from utils.py return render(request, 'csv_upload_success.html') utils._control_bulk_data_upload: import csv, datetime from app.models import Control def _control_bulk_data_upload(csv_file): path = default_storage.save("{}_{}".format(datetime.utcnow(), csv_file.name), ContentFile(csv_file.read())) with open(path) as csvfile: reader … -
Python - Check if user is in team or not
I have a model that stores teams and members. I want to check if a requested user is in this team or not. How do i do that? Model class TeamPlayer(models.Model): team = models.ForeignKey(Team, related_name='players', on_delete=models.CASCADE) player = models.OneToOneField(User, related_name='player', on_delete=models.CASCADE) approved = models.BooleanField(default=False) Template {% if request.user in object.players.all %} <a href="{% url 'teams:leave' pk=object.id %}" class="btn btn-warning">Leave</a> {% else %} <a href="{% url 'teams:join' pk=object.id %}" class="btn btn-success">Join</a> {% endif %} View is just simple DetailView. -
Model forward declarations
I'm writing configuration dictionaries into my models. I need to access the forwarded declaration of model declared below the model im configuring right now. For example class FirstModel(models.Model): TYPE_MODEL = { 'type1': SecondModel, 'type2': ThirdModel } some_field = models.CharField( choices=( ('type1', 'type 1 display'), ('type2', 'type 2 display') ) ) def do_some_with_config(self): model = self.TYPE_MODEL.get(self.some_field) ... do something with model ... class SecondModel(models.Model): ... its own fields ... class ThirdModel(models.Model): ... its own fields ... Is here any better approach to do this than moving the FirstModel below the ThirdModel or is it generally a good idea to have these dicts with configuration in the model? -
when i removed the last line from code the error is gone but it doesn't provide required output Django 1.8
from django.contrib import admin Register your models here. from .models import SignUp class SignUpAdmin(admin.ModelAdmin): list_display = ["str","timestamp","updated"] class Meta: model = SignUp admin.site.register(SignUp, SignUpAdmin) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: : (admin.E108) The value of 'list_display[2]' refers to 'updated', which is not a callable, an attribute of 'SignUpAdmin', or an attribute or method on 'newsletter.SignUp' -
django dynamic formset how to find id of a dynamic created form
I use django dynamic formset javascript, I want to do use ajax on each form. However I can't find a way to get the id of a newly created dynamic form. html {% for forms in formset %} {{ forms.id }} <tr class="dynamic"> <td style="width:100px">{{ forms.stock.errors }} {{ forms.stock}} </td> <td style="width:100px">{{ forms.inventory.errors }} {{ forms.inventory}} </td> my ajax $(document).ready(function(){ {% for forms in formset %} $("#{{forms.stock.auto_id}}").change( function(){ var symbol = $("#{{forms.stock.auto_id}} option:selected").text(); $.ajax({ url: "{% url 'inventory:get_position' ptinventory_obj.id date %}", type: "GET", data: { 'product': product }, datatype: 'json', success: function(data) { $("#{{forms.inventory.auto_id}}").html(data.price); }}); }); {% endfor %} }) forms.inventory.auto_id stays the same for all new forms so any changes on stock.nothing is shown. I looked at the source from chrome and can see the ide changes for the input field for each form...but the {{forms.inventory.auto_id}} is clearly not the right tag.Please help... -
How to create detail path in Django
I want to create detail path in Django. I've create a categories and subcategories directory and after that I putting in subcategory the post. I want to create my path like localhost/category/subcategory/detail_page.html In that moment my app creating the path like localhost/detail_page.html How to do it? my views.py is: from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): kategorie = Kategoria.objects.filter(parent=None).order_by('name') firmy = Firma.objects.all().order_by('publish')[:5] context = {'kategorie': kategorie, 'firmy': firmy} return render(request, 'ogloszenia/index.html', context=context) def detale_firmy(request, slug): detale_firmy = get_object_or_404(Firma, slug=slug) return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<slug>', views.detale_firmy, name='detale_firmy'), ] **index.html** {% for kategoria in kategorie %} <li> <b>{{kategoria.name}}</b> {% if kategoria.children.count > 0 %} <ul> {% for sub in kategoria.children.all %} <li>{{ sub.name }}</li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul> </div> <div class="col-2"> Ostatio dodane:<br> {% for firma in firmy %} <strong>{{firma.title}}</strong><br> <a href="{% url 'detale_firmy' slug=firma.slug %}"><img src="http://free.pagepeeker.com/v2/thumbs.php?size=m&url={{firma.www}}"/><br></a> -
How to show math expressions retrieving from database in JQuery?
I have a math expression like this which I am storing to the mysql database: Test = 10.0 A = 12.0 B = 03.0 -------25.0 But when I retrieve it from the database and show it to my html template it looks broken. Like: Test = 10.0 A = 12.0 B = 03.0 -------25.0 How can I manage this situation? How to show them as like when I am giving input to the database??? Is there any way to manage it with JS or JQuery something??? -
Create a Custom History in Django showing specific field changes
Heyho, in Django i want to create a history view of my model 'application' which shows a table with the columns: Who (changed), When, which field, old Value, new Value I found the django-simple-history app which stores every version of a model instance in a new model. Actually excactly what i need, but i do not know, how to get the fields of a historical object and especially just the fields which changed comparing two sequenced historical objects. Has anybody an idea or maybe a complete new approach for that? Thanks a lot! -
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode
I getting this error in my Service Worker. I have a page that changes dynamically with user usage. I do not want to cache my requests. Can someone help me to change my fetch event but still allow me to have a progressive webapp? sw.js {% load static from staticfiles %} 'use strict'; this.addEventListener('install', function(event) { event.waitUntil( caches.open('myapp-v1.0.0.2').then(function(cache) { return cache.addAll([ "/", ]); }) ); }); self.addEventListener('push', function(event) { var body_content = JSON.parse(event.data.text()); var title = body_content.title; var options = { body: body_content.text, icon: body_content.icon, badge: body_content.icon, data: { url: body_content.url } }; event.waitUntil(self.registration.showNotification(title, options)); }); self.addEventListener('notificationclick', function(event) { event.notification.close(); event.waitUntil( clients.openWindow(event.notification.data.url) ); }); self.addEventListener('fetch', function(event) { event.respondWith(fetch(event.request)); // or simply don't call event.respondWith, which // will result in default browser behaviour }); self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.filter(function(cacheName) { // Return true if you want to remove this cache, // but remember that caches are shared across // the whole origin }).map(function(cacheName) { return caches.delete(cacheName); }) ); }) ); }); -
Illegal instruction: 4 when running Django
I made clean install of Django v1.11.10 now. When I run python manage.py runserver everything works fine. But when I try connect to Postgres database, I install package pip install psycopg2, modify DATABASES varibale and after running runserver command it fails with Illegal instruction error: Performing system checks... System check identified no issues (0 silenced). Illegal instruction: 4 What is it? How to get log error? I use Mac OS 10.11.6, PostgresApp (tried on v9 and v10 server to check error source). Python 3.6.4 (via virtualenv). DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'sirjay', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } -
What's the best way to add custom HTML in the middle of a form with many fields?
I have a model with 40+ fields and a ModelForm for interacting with it. In my template I'm doing {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label }} {{ field }} </div> {% endfor %} I want to customize the final HTML - insert separators after some fields, a div after another and so on. What's the best way to do this? I thought of two ways and am wondering if I missed something more elegant: The obvious one - instead of iterating over fields in the form, manually put all fields and whatever HTML I desire between them. The downside is that this duplicates the work of listing all fields in the model and requires manual adjustments if I ever change the set of the fields I want. Do something like this: for field in form render field if field.name in fields_i_want_to_put_a_br_after <br> if field.name in fields_i_want_to_put_a_div_after <div> -
django rest framework- how can I pass query params to foreign key serializer?
For my application, I have Locations, and Events given by the following (simplified) models: class Location(models.Model): name = models.CharField(max_length=64) class Event(models.Model): location = models.ForeignKey(Location) date = models.DateField() In my API, I have an endpoint: /api/locations/ which returns all locations, and each location has its events embedded within it, e.g.: [ { 'id': 1, 'name': 'Location 1', 'events': [ {'id': 1, 'date': '2018-01-01'}, {'id': 2, 'date': '2018-01-14'} ] }, { 'id': 2, 'name': 'Location 2', 'events': [ {'id': 3, 'date': '2017-12-28'}, {'id': 4, 'date': '2018-01-10'} ] } ] my serializers look like: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('id', 'date',) read_only_fields = ('id',) class LocationSerializer(serializers.ModelSerializer): events = EventSerializer(many=True) class Meta: model = Location fields = ('id', 'name', 'events',) read_only_fields = ('id',) Using ViewSets, I would like to add a filter to this call, with a max_date, and min_date parameter, e.g.: /api/locations/?min_date=2018-01-01&max_date=2018-01-15. Which should return only locations that have events between those two dates, AND should only return the events for each location between those two dates. In the example data above, both locations would return, Location 1 would have both events listed, but Location 2 would only have the second event in its list. In my ViewSet, I … -
Removing djcelery dependency from django project
I am Using django 1.10, celery 3.1.25 and django-celery==3.2.1, i want to remove django-celery from my project as now celery is compatible with django and it doesn't need djcelery. When i remove djcelery from Installed_apps in settings.py file and restart celery by supervisor restart celery command, it gives me error- "Unknown command celery". i have removed all the settings, what else do i require more to remove djcelery. with djcelery in settings celery is working fine. Thanks in advance. -
Filter dictionary list by text in string
I have a list of dictionaries and need to filter them by a list of strings. Right now I have this: projects = [{u'CustomerName': u'abc', u'Projectname': u'Contract A full'}, {u'CustomerName': u'bcd', u'Projectname': u'Contract A medium'}, {u'CustomerName': u'cde', u'Projectname': u'Contract B full'}, {u'CustomerName': u'def', u'Projectname': u'Contract B medium'}] filter = ['B', 'full'] return [p for p in projects if p['ProjectName'] in filter] The result I need is: [{u'CustomerName': u'abc', u'Projectname': u'Contract A full'}, {u'CustomerName': u'cde', u'Projectname': u'Contract B full'}] However it returns nothing. Only if I specify the entire string: filter = ['Contract A full', 'Contract B full'] Thank's for the help. -
Django DateTimeField can't validate ISO 8601 format
Django DateTimeField can't validate ISO 8601 format forms.py from django import forms class ImageForm(forms.Form): updatedAfter = forms.DateTimeField() createdAfter = forms.DateTimeField() views.py class ImageView(View) def get_form(self): return ImageForm(data=self.request.GET or None) def get(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): ... Here is my request: http://127.0.0.1:8001/images/?updatedAfter=2011-10-05T14:48:00.000Z&createdAfter=2011-10-05T14:48:00.000Z -
Django falsely claims "There is no unique constraint matching given keys for referenced table"
If I add the following class to my model, all works fine on migration. class BeursCheck(models.Model): order = models.IntegerField(default=None) painting = models.ForeignKey(Painting, related_name='beursCheck',primary_key=True) However, if I add this field.. mturk_assignment = models.ForeignKey( 'mturk.MtAssignment', null=True, blank=True, related_name='+', on_delete=models.SET_NULL, unique=True ) It fails with error django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "mturk_mtassignment" This field relates to MtAssignemnt, which has a unique key. This related answered even says so. class MtAssignment(MtModelBase): id = models.CharField(max_length=128, primary_key=True) -
how to autofll fields on run time in django
i want to create a salesorder model form ... model.py class Salesorder(models.Model): salesorderid=models.CharField(max_length=100, primary_key=True) distributororder=models.ForeignKey(Distributor) sales_representative=models.CharField("Sales Representative",max_length=50) discount=models.CharField("Discount",max_length=50) status=models.CharField(max_length=15,choices=sale_status, default='Un Paid') sub_total=models.PositiveIntegerField() paid=models.PositiveIntegerField() balance=models.PositiveIntegerField() productsale=models.ForeignKey('product.Product') date = models.DateField() view.py def salesorder_create(request, template_name='sales/salesorder_form.html'): form = SalesOrderForm(request.POST or None) if form.is_valid(): form.save() return redirect('index.html') return render(request, template_name, {'form':form}) template <div class="form-group"> <h3>salesorderid</h3> {{form.salesorderid}} <h3>distributororder</h3> {{form.distributororder}} <h3>sales_representative</h3> {{form.sales_representative}} <h3>discount</h3> {{form.discount}} <h3>status</h3> {{form.status}} <h3>sub_total</h3> {{form.sub_total}} <h3>paid</h3> {{form.paid}} <h3>balance</h3> {{form.balance}} <h3>productsale</h3> {{form.productsale}} <h3>date</h3> {{form.date}} </div> i want when user enter sub_total and paid field the balance field autofill like balance = total -paid please help how do that