Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value from key when sending a dictionary to jinja
I send my dictionary - content - to a template which looks like this. Inside content is multiple dictionaries. One of them is named like_dict which looks like this : {1: 18} {2: 14} {3: 15} and another is named info which holds my user id. I use this code to sort it: {% for x in info %} {% if x.id in like_dict %} <p> the value is: {{ like_dict.x.id }} </p> {% endif %} {% endfor %} Everything seems to be working, except the part within the paragraph tags. When I replace x.id with the number of my ID (like this: like_dict.1 ) it prints '18' just fine. When I leave it as I have it in the example (like_dict.x.id), it finds x.id in like_dict, but only prints 'the value is:' without stating the dictionary value. When I try to does this - like_dict[1] - I get an error for using brackets. Can anyone direct me towards how I would go about printing only the value when the key matches my ID? -
Group query results in Django template
I'm trying to group some results from a query in a Django template? I've tried regroup with no success. I have a tags model that has a parent tag like below: class BoardTags(models.Model): name = models.CharField(max_length=150, null=True) description = models.TextField(default='', null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) parent_tag = models.ForeignKey('self', null=True, blank=True) def __str__(self): return self.name I'm using this widget 'tags':forms.CheckboxSelectMultiple() to try get this result: The parent tag would be the 'Topics' and inside the nav tab I would like to have the checkboxes for the various tags that share that parent tag. Any ideas on how to do this? -
using postgis and multi tenancy with django
i have to create an app that uses multi tenancy separated by country [ie: colombia.myapp.com, usa.myapp.com, etc] and i want to use the geoDjango module with PostGIS. For my multi tenant i'm using django-tenant-schemas, but both solutions change the engine of the postgres database. PROBLEM: it's there a way to use two separated engines over the same database in django? or connect to the same database with the two engines without generate a conflict in the database and work with both Multi Tenancy and GeoDjango? -
Updating Django model field using an action button in a template
This is my first Django project and I have got it 95% of the way there. I've set up two models; student and checkin history. I have a view that passes checkin history and a form which allows a student to check in. The template then renders the checked in students. If I update the checkout field using the admin page the student no longer appears on the main page, which is what I want. However I am stuck in how to use the webpage template to update the check out field in the model. Image of Project Model.py from django.db import models from django.utils import timezone # Create your models here. class Student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=254) student_id = models.IntegerField(max_length=6) birth_date = models.IntegerField(max_length=6, default=None) photo = models.ImageField(null=True, blank=True, default='default.jpg') @property def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name class History(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE) # check_in = models.DateTimeField(default=timezone.now) check_in = models.DateTimeField(auto_now_add=True) check_out = models.DateTimeField(null=True,blank=True) @property def duration(self): if self.check_out is None: return str(timezone.now() - self.check_in)[:-10] else: return str(self.check_out - self.check_in) class Meta: verbose_name_plural = "History" ordering = ['-check_in'] def __str__(self): return f"{self.student.full_name} - {self.duration}" views.py from django.shortcuts import render from .models import History, Student … -
Unable to redirect traffic using Djangae
I am attempting to use djangae to serve static files only. In addition, I want to route all traffic to an index.html. When I visit http://localhost:8000 I get a 500 error. When I visit http://localhost:8000/static/index.html, I get the correct file. What am I doing wrong? My urlpatterns are as follows: ... from . import views ... urlpatterns = ( ... url(r'^', views.home), ) I have tried r'^$', r'^.*$', and '', but I do not get any difference in the outcome. views.py: from django.shortcuts import redirect def home(request): return redirect('/static/index.html', permanent=True) 500 Error File "/usr/lib/python2.7/site-packages/pytz/__init__.py", line 493, in <module> for l in open(os.path.join(_tzinfo_dir, 'zone.tab')) File "/git_repos/djangae/proj/sitepackages/dev/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 260, in __init__ raise IOError(errno.EACCES, 'file not accessible', filename) IOError: [Errno 13] file not accessible: '/usr/share/zoneinfo/zone.tab' -
How can the output of Django {% static %} Template Tag be serialized into a JSON object?
My goal is to serialize the output of the Django Template Tag {% static 'my/file.png' %} from the HTML templates into a JSON object for reference in a custom.js file. However I am receiving this error in Chrome Console: Uncaught SyntaxError: Unexpected token / in JSON at position 0 at JSON.parse (<anonymous>) Console Debugger shows the output of the {% static %} tag, which is the expected value of the absolute path of an image: /static/img/my_image.png I understand that there may be an issue with escaping the {% static %} tag output - and that this is raising the apparent syntax error displayed in Chrome Console. I say this because my understanding is that the string to be parsed is not valid for the purposes of the method used, JSON.parse(). That is, the JSON.parse() method referenced in the code below takes an argument, and that argument is the output of the {% static %} tag in this case - and that argument is not a valid input for the JSON method as far I as I understand. From this, my intuitions tells me that perhaps the {% static %} tag output can be escaped - and that this modified value … -
Updating data in Bokeh plot client side using Django channels websocket
I'm trying to update a Bokeh plot in Django when new data is received via a websocket implemented with Django Channels. The aim is to stream new data received over the websocket without having to refresh the browser. My django view creating the bokeh plot is: #in views.py def sensor(request): plot = figure(title= 'title' , x_axis_label= 'X-Axis', y_axis_label= 'Y-Axis', plot_width =900, plot_height =500 source = ColumnDataSource(data=dict(x=[], y=[])) plot.line('x', 'y', source=source, legend= 'f(x)', line_width = 2) script, div = components(plot) return render(request,"sensor.html",{'div':div,'script':script}) The JQuery associated with the websocket is the following (I receive the message as JSON formatted text): //In a script tag in sensor.html $(function() { var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var endpoint = ws_scheme + '://' + window.location.host + window.location.pathname var ws = new WebSocket(endpoint); ws.onopen = function(e) { console.log("open", e); }; ws.onmessage = function(e) { console.log("message", e); var new_data = jQuery.parseJSON(e.data).data); // UPDATE BOKEH ColumnDataSource WITH new_data }; }); My problem is that I have no idea how to update the Bokeh ColumnDataSource via JQuery. The closest I've found is using Bokeh CustomJS Callbacks, but I don't see any way of connecting them with the websocket onmessage event, and accessing data collected via … -
django {%url%} for {%include%}
When I try to render this template: {% include "mylistitem.html" with text="foo" btn_text="bar" href="{% url 'register' %}" %} It generates the following error: TemplateSyntaxError: Could not parse the remainder: '"{%' from '"{%' Nowhere in the docs I found that expressions couldn"t be nested. How could I make this work? -
change the way django show stocked data in database in admin page
so i have this attribute that contains an image enter image description here so my question is , how can i instead of showing the picture url , show the picture it self . Here's my model : class Person(models.Model): nom = models.CharField(max_length=255) prenom = models.CharField(max_length=255) age = models.DecimalField(max_digits=3, decimal_places=1) photo = models.ImageField(upload_to='persons') def __str__(self): return str(self.id) -
Django run on the wrong port
Currently pushing a wagtail cms - Django app to a clever cloud server. Django is using the wrong port. nginx: 2019/02/12 20:44:52 [error] 1869#0: *1 connect() failed(111:Connection refused) while connecting to upstream, client: 127.0.0.1, server: _, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:9000", host: "localhost:8080" I have created a .init file (at the settings folder with base.py,production.py, dev.py) with [uwsgi] http = 0.0.0.0:8080 master = True processes = 2 threads = 2 module = myapp.wsgi:application the result is the same. The same app is going well on heroku. I never got this error before -
Getting POST request from an HTML form into a Django database
i'm looking to implement a simple HTML form that passes a bunch of data to a Django backend which then stores it and displays it on another page. Unfortunately i can't seem to hook the back and front ends together. I'm relatively new to Django and this is the only bit really giving me grief The HTML being used: <form action="{% url 'jobs:send' job_id%}" method="POST"> {% csrf_token %} <label>Job ID</label> <input type="number" id="job_id"> <br> <label>Store</label> <select> {% for store1, store2 in STORE_CHOICES %} <option value="{{ store1 }}">{{ store2 }}</option> {% endfor %} </select> <br> <label>Department</label> <select> {% for dept1, dept2 in DEPARTMENT_CHOICES %} <option value="{{ dept1 }}">{{ dept2 }}</option> {% endfor %} </select> <br> <label>Team Member</label> <input type="text" id="team_member"> <br> <label>Support Member</label> <select> {% for supp1, supp2 in SUPPORT_CHOICES %} <option value="{{ supp1 }}">{{ supp2 }}</option> {% endfor %} </select> <br> <label>Job Details</label> <textarea type="text" id="job_details" rows="4"></textarea> <br> <label>Job Status</label> <select> {% for status1, status2 in STATUS_CHOICES %} <option value="{{ status1 }}">{{ status2 }}</option> {% endfor %} </select> <br> <label>Feedback Given</label> <textarea type="text" id="feedback_given" rows="4"></textarea> <br> <input type="submit" value="Send"> Below is my views.py file. I get the impression this is where my problem is but i can't seem to pass … -
how to use an uploaded image in django
I want to upload an image and then edit it but I do not know how to keep the uploaded image in different parts now I am using global variable but I need another way because if different user work with my app at the same time it can not distinguish the images def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) # Create your views here. def Edit(request): if request.method=='POST': form=picform(request.POST , request.FILES) if (form.is_valid()) : global anghezi anghezi=pic.objects.create(**form.cleaned_data) global epic epic=anghezi.pic nam=anghezi.name anghezi.save contex={"item":anghezi} return render(request,'edit.html',contex) def show(request): global epic im = Image.open(epic.url[1:]) return render(request,'show.html',{"im":epic}) def share(request): global anghezi anghezi.shar=True anghezi.save() p=pic.objects.filter(shar=True).order_by("uploaded_at") print(p) return render(request,'share.html',{'p':p}) -
Should Wildcard imports be avoided with Django models?
Obviously we want to avoid wildcard imports whenever we can when it comes to dependencies and such, but what about when it comes to an abundance of Django models? For instance for any given application I have maybe 10 or so models with fairly long names for context on their nature. It'd be very ugly to have an extremely long import line for this application. from stores.models import * vs from stores.models import Store, Provider, PhoneLine, CircuitConfiguration, Circuit, Server, LifeSafety This project contains 6 applications total, each with 7-12 models, so I just want to be sure to organize things in the most Django way. -
Ajax datatables get csv file with filters
I have a Datatables with filtering on 12 collumns. But me need's send all filters on BackEnds for response with csv file. I stacked on sending GET request on backs. i have similary trigger, but this is ajax and i dont recieve a file (because ajax) transactions_table.fnFilter('export', 0); this is trigger. Can i may implementing this method similarry - window.location.href('/some_url')? thanks a lot -
How to get docstrings from decorated functions in Python with autodoc?
There is a officially known problem with sphinx autodoc that when your function is decorated, its docstring won't show up in the generated docs. From the autodoc home page: If you document decorated functions or methods, keep in mind that autodoc retrieves its docstrings by importing the module and inspecting the doc attribute of the given function or method. From Python 2.5, functools.wraps() can be used to create well-behaved decorating functions. So, using the the functools.wraps() does work. def decorator_func(say_hello_func): """Docstring for decorator_func""" @wraps(say_hello_func) def wrapper_func(hello_var, world_var): """Docstring for wrapper_func""" return say_hello_func(hello_var, world_var) return wrapper_func @decorator_func def say_hello(hello_var, world_var): """Docstring for say_hello function. Args: hello_var (str): hello_var world_var (str): world_var Returns: str: concatenation of the strings """ print hello_var + " " + world_var producing (with poor formatting pasted) say_hello(hello_var, world_var) Docstring for say_hello function. Parameters: · hello_var (str) – hello_var · world_var (str) – world_var Returns: concatenation of the strings Return type: str However, there are cases when you have a 3rd party package from which you can take a decorator. However, it is impractical to modify the source of the package adding functools.wraps() everywhere in their source code - the work you've done will be gone after the … -
How to modify views.py and urls.py to enable an endpoint to Django app?
In my Django app I want to modify urls.py in order to add an end-point users: from rest_framework import routers # ... router = routers.DefaultRouter() router.register(r'api/users', ???) urlpatterns = [ path('admin/', admin.site.urls), path(r'', include(router.urls)), path(r'api/', include('rest_framework.urls', namespace='rest_framework')) ] However I don't know how to modify views.py to enable an endpoint. Should I create a class inside views.py? from django.http import HttpResponse import pandas as pd import datetime import json def index(request): #... response_data = {} response_data['prediction'] = y_pred response_data['probability'] = round(y_prob,2) response_json = json.dumps(response_data) return HttpResponse(response_json) -
Django: How to add 2 days to an existing date entered by user
I am trying to add a a payment due date 2 days after the event class Payment(models.Model): event_date = models.DateField() payment_due_date = models.DateField() class Meta: ordering = ["payment_due_date"] def payment_due_date(self): event_date = self.event_date return event_date + datetime.timedelta(days=2) Pycharm gives me a error highligting Expected type 'timedelta', got 'DateField' instead more... (Ctrl+F1) how can I fix this issue -
Django redirect user only once in session
I need to redirect the user only once, depending on the user agent. In middleware.py I have: class UserAgentDetectMiddleware(object): def __init__(self, get_response=None): if get_response is not None: self.get_response = get_response def __call__(self, request): self.process_request(request) return self.get_response(request) def process_request(self, request): request.user_agent = SimpleLazyObject(lambda: get_user_agent(request)) if request.user_agent.is_pc: request.template_prefix = '' else: request.template_prefix = 'mobile_' in views.py : class UserAgentIndexView(TemplateView): template_name = 'index.html' def get_template_names(self): try: template_name = os.path.join(self.request.template_prefix + 'index.html') except TemplateDoesNotExist: template_name = 'index.html' return [template_name] def get_context_data(self, **kwargs): ... def render_to_response(self, context, **response_kwargs): ... So, if users device is PC, template_name is index.html, otherwise mobile_index.html. But now if users device is mobile, django redirects user to mobile version of the page every time. But user should have ability to go to the desktop version of the site. How to fix it? Thanks for your time and help. -
Create CSRF token in Django view
I have a particular form that is created dynamically, from a database, which I want to use in a Django template. The problem is that it requires a csrf token to be embedded. So inside my view I'd like to create this token so that I can insert it into the form there. However, I don't have any luck. This is working, partially: from django.middleware import csrf token = request.META.get('CSRF_COOKIE', None) if token is None: token = csrf._get_new_csrf_key() request.META['CSRF_COOKIE'] = token request.META['CSRF_COOKIE_USED'] = True The first part works well -- if a token is present, it's used. However, if the token is None, and _get_new_csrf_key() is called, then it doesn't work the first time - I have to refresh the page before it works. What would be the right way to create a token inside a view? -
How To Customize Django LoginView
I am trying to figure out how to customize the django LoginView based on whether or not it's the user's first time logging on for the day. I have my LoginView currently set up so that it defaults to the LOGIN_REDIRECT_URL = "book:author" in my settings.py file. This works flawlessly. When a user logins in and is successfully authenticated, they are redirected to "book:author" as I would expect. What I'm trying to do is if this is the first time the user has logged in for the day, direct them to one URL, and if it's any other login iteration for the day, redirect them to a different URL. I have read about various methods on how to do this, to use messaging as opposed to conditional URL redirect to using the NEXT parameter and I'm trying to figure out which is the best and most secure and proper way of going about this. Here is my default LoginView...( Nothing fancy ) class LoginView(LoginView): template_name = 'registration/login.html' form_class = AuthenticationForm And then it redirects based on my settings.py file definition... LOGIN_REDIRECT_URL = "book:author" What is the best way to redirect for first login of the day to different URL? Thanks … -
Cannot run psql or access postgresql db despite postgres server active on localhost
I am having trouble getting postgres up and running for my Django app, which is currently running mysql db. I am trying to add a new user and database to the postgres server, but am unable to. I have ssh tunneled into a server on my network which holds my django app and the postgres server. I believe something has gone wrong in the installation/setup of postgres, because whenever I run "psql template1" or "createuser", I get the following error: psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? However, I believe postgres is running, because when I run "sudo service postgresql status", I receive the following message: postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Tue 2019-02-12 09:45:52 EST; 10min ago Process: 3585 ExecStart=/bin/true (code=exited, status=0/SUCCESS) Main PID: 3585 (code=exited, status=0/SUCCESS) Tasks: 0 Memory: 0B CPU: 0 CGroup: /system.slice/postgresql.service I have tried adding local all all trust to the first non-commented line of my pg_hba.conf, and of course resterted the server. "Which psql" returns "/usr/bin/psql". Other important things in my postgresql.conf file I've tried (not in order): … -
How to solve CORS issue in the Django-React app?
I am building an application with Django and a front-end/JavaScript technology such as React. I use Gunicorn server with Django. When sending HTTP requests from the front-end application, using the fetch API, to the back-end API built with Django REST framework the web browser throws an error related to the Same Origin Policy. I updated settings.py as suggested here (using django-cors-headers): import os from corsheaders.defaults import default_headers ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http//:localhost:8000', ) CORS_ALLOW_HEADERS = default_headers + ( 'Access-Control-Allow-Origin', ) But still I get the same errors. How can I solve the problem? (I am running my app on docker) -
Django doesn't display database content
I have defined models and views. I would like to display Project existing from database. However script is not displaying any content. Where's the problem? Please take a look into definition of model, views and html template of file trying to display projects from database with use of for loop. models.py from django.db import models from bifrost.models import CustomUser # Create your models here. # Model Projektu class Project(models.Model): PROJECT_TYPE = ( ('SCR', 'Scrum'), ('KAN', 'Kanban'), ) project_key = models.CharField(max_length=8, primary_key=True) project_name = models.CharField(max_length=160) project_type = models.CharField(max_length=10, choices=PROJECT_TYPE, null=True) date_created = models.DateField(null=True) # Definicja nazwy modelu w Adminie Django def __str__(self): return self.project_name views.py from django.views.generic import ListView from django.shortcuts import render from .models import Project # Create your views here. class ProjectListView(ListView): model = Project template_name = 'project-list.html' contect_object_name = 'projects_list' def projectslist(request): projects = Project.objects.all() return render(request, 'project_list.html', {'projects': projects}) project-list.html template {% extends 'base.html' %} <h1 class="h3 mb-2 text-gray-800">{% block title %}Projects{% endblock title %}</h1> {% block content %} <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">List of Projects</h6> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Project Key</th> <th>Name</th> <th>Type</th> <th>Created</th> </tr> </thead> <!-- … -
NoneType object is not iterable django
I have a signal inside my django app where I would like to check if either or both fields in my model has been updated, so I can then proceed and compute the display_price before saving my model. I'd also like that when either the price or tax_rate is updated, the display_price value gets computed once more. My model looks like this... class Product(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() tax_rate = models.PositiveIntegerField() display_price = models.PositiveInteger() inputed_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) Inside my model admin I have the following method... def save_model(self, request, obj, form, change): update_fields = [] if not obj.pk: obj.inputed_by = request.user elif change: obj.updated_by = request.user if form.initial['tax_rate'] != form.cleaned_data['tax_rate']: update_fields.append('tax_rate') if form.initial['price'] != form.cleaned_data['price']: update_fields.append('price') obj.save(update_fields=update_fields) super().save_model(request, obj, form, change) My signal looks like this... @receiver(post_save, sender=Product, dispatch_uid="update_display_price") def update_display_price(sender, **kwargs): created = kwargs['created'] instance = kwargs['instance'] updated = kwargs['update_fields'] checklist = ['tax_rate', 'price'] if created: instance.display_price = instance.price+instance.tax_rate instance.save() elif set(checklist).issubset(updated): instance.display_price = instance.price+instance.tax_rate instance.save() I get the error 'NoneType' object is not iterable The error seems to come from the line set(checklist).issubset(updated). I've tried running that line specifically inside the python shell and it yields the … -
How to swap two items in a list in nested data using Django Rest Framework
I'm trying to swap two items in a list, and would like to know the best way to do it. I have working code but I would like to find a better solution. I'm using Django 2.0.10 with Django Rest Framework. I have nested data where Lists contain a limited number of Items. Each item has an order, which is an integer and must be unique within that list, and each list can only have a fixed number of values. It is assumed that all lists always have their maxiumum number of items. I want to allow the user to move items up and down in the list, which means swapping two items. The simplest way to do this would be to modify the 'order' attribute of each item, but I can't see how to do this given that all valid order values are already in use. I can't give item 1 the order 2 and save it, because there is already an item 2. And there is no temporary value I can assign during the swap operation. So, what I'm doing instead is this: create a deep copy of each item assign the new order to each copy delete …