Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse M2M query in Django-template
I would like to fetch the names of the speakers in the template. I marked it with xxxx. How can I do this? Thank you so much for helping out. My files: models.py class City(models.Model): name = models.CharField(max_length=100) class Speaker(models.Model): name = models.CharField(max_length=100) url = models.URLField(max_length=100) city = models.ManyToManyField(City, blank=True) views.py def home(request): cities = City.objects.all().exclude(speaker__isnull=True) return render(request, "index.html", {"cities":cities}) index.html {% for i in cities %} {{ i.name }},xxx{{ i.speaker.name }}xxx<br> {% endfor %} -
Django python 3 " python: can't open file 'manage.py': [Errno 2] No such file or directory".
I have installed only python 3 and django latest version but still this error is coming " python: can't open file 'manage.py': [Errno 2] No such file or directory". -
How to put application/x-mpegURL in source in videojs
I'm not JavaScript guy but I have project with js and plugin VIDEOJS (Video.js v4.6.4 Copyright 2014 Brightcove, Inc. https://github.com/videojs/video.js/blob/master/). I recived an error: video.dev.js:1384 VIDEOJS: ERROR: (CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED) The video could not be loaded, either because the server or network failed or because the format is not supported. I know that solved of this problem can be put: <source src="video/test.m3u8" type="application/x-mpegURL">. but my question is, how to do this. -
Angular 4 GET 403 response
I write an app in Angular 4 that calls a REST API (DJANGO). The code is as followed: export class ForecastUnitService { private path = 'forecastunit/'; private options; constructor (private http: Http, private c:CentralService) { this.options=this.c.createOptions(); } getForecastUnits(): Observable<ForecastUnit[]> { return this.http.get(this.c.createURL(this.path),this.options) .map(this.extractData) .catch(this.handleError); } ... } I add options that contains an authorization header, but still I get a 403 forbidden. However when I try the call with cUrl or Postman or in swagger, with the same token I get results. So first tought, the headers aren't correct but when I log options I get: {"method":null,"headers":{"Authorization":["**Correct Token**"],"Content-Type":["application/json"]},"body":null,"url":null,"withCredentials":null,"responseType":null} So that is not the problem, when I look in the response from Chrome I see the following: {"detail":"Authentication credentials were not provided."} So again no credentials, but I really passed them, what is going wrong? -
fetching data from aiml in views.py
Is it possible to get the response from an aiml file through the views.py file in django?. I am providing a string and i want to get the response from aiml. Maybe it happens because when i run server it is unable to know where the aiml file is. the views.py file is as followed: import aiml import os from django.http import HttpResponse from django.shortcuts import render def aimlResponse(request, question): kernel = aiml.Kernel() if os.path.isfile("bot_brain.brn"): kernel.bootstrap(brainFile="bot_brain.brn") else: kernel.bootstrap(learnFiles="std-startup.xml", commands="load aiml b") kernel.saveBrain("bot_brain.brn") art = kernel.respond("hello") return HttpResponse(art) please help. And thanks in advance -
How to access Python class in another folder when building Django management command?
I'm trying to turn a Python script into a Django management command. My script is in an application folder called sites. Folder structure: project |--sites |scanner.py |--management |__init__.py |--commands |__init__.py |getdeals.py I'm trying to have getdeals.py run as a management command. It finds objects in my Site model and then uses them to create an instance of the SiteDeals class, which is in the scanner.py file. getdeals.py: from django.core.management.base import BaseCommand from sites.models import Site class Command(BaseCommand): help = "Scans all sites for deals" def handle(self, *args, **options): site_set = Site.objects.all() for site in site_set: scraper = SiteDeals(site) When I run python manage.py getdeals it says NameError: name 'SiteDeals' is not defined. I thought of taking the code from handle and writing it as a main() function in scanner.py, and then accessing it from getdeals.py, but can't work out how to access it that way. How do I access SiteDeals from the scanner.py file, given that it is in another folder from my management/commands folder, so that I can pass my objects to it? -
How to save a second form data after taking input instead of redirecting to the first form in Django?
I just started learning Django and am currently making a site for getting some personal information from the user which is split over two forms on two pages. The first form takes the email, phone number and after verifying it goes to the second form which takes more personal information. In the end I need to save both this information into ONE TABLE only so I am also passing the first form data into the second page to be stored in hidden inputs and then all of it should conceptually be stored in my DB. But when I submit the second form it simply redirects to the first form instead. Please help as I need it to save the form and redirect finally instead of going back to the first form!! This is my views.py file : # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from django.views.generic import TemplateView from register.forms import ContactForm, InfoForm # Create your views here. def register(request): return render(request, 'register/register.html') class RegisterView(TemplateView): template_name = 'register/register.html' def get(self, request): form = ContactForm() args = { 'form': form } return render(request, self.template_name, args) def post(self, request): form = ContactForm(request.POST) if form.is_valid(): email … -
Django. How to EXCLUDE one-to-many or many-to-many fields from query?
I have a sample model like this: class FooBar(models.Model): name = models.CharField ... age = models.IntegerField ... cats = models.ManyToManyField ... dogs = models.ManyToManyField ... As u can see, there is 2 many-to-many fields (cats, dogs) Then (somewhere else in my code) I have serializer function which converts given model into JSON. Eg. make_json(foobar_instance) will produce smth like this: { "id": "9999", "name": "John Romero", "age": "55", "cats": "[421, 5423, 53252]", "dogs": "[213, 44124, 321, 753]" } BUT I don't need that "cats" and "dogs" fields in my result JSON and I don't want to charge database with additional queries for resolving that many-to-many relations. So, how I can tell Django: Man, exclude that cats and dogs fields from result - I don't need that thing. Eg. FooBar.objects.filter(....).SKIP('cats', 'dogs')... Is that possible? Thank you! -
wscelery monitoring tool super function error
I'm trying to follow https://wscelery.readthedocs.io/en/latest/examples.html the link with django. No problem starting or using celery commands: celery wscelery --allow-origin=.* from terminal gives the error: File "/Library/Python/2.7/site-packages/wscelery/events.py", line 71, in __init__ super().__init__() TypeError: super() takes at least 1 argument (0 given) I know what this error means, but I can not use Python3. Wscelery pip link: https://pypi.python.org/pypi/wscelery Requirements Python >= 3.4 Is there anyone using wscelery with python2? -
DB objects not rendering in extended Template, Python/Django
I am having problems rendering a sidemenu with database objects in extended templates. The menu is rendering in home.html, but then if I access to another page the query does not execute. Home.html: {%extends 'base.html'%} {%block section%} <nav class="navbar navbar-default sidebar" role="navigation"> <div class="container-fluid"> {% include 'firewall/menu_elementos.html' with firewalls_list=firewalls switches_list=switches routers_list=routers %} </div> </nav> <main> <nav class="navbar navbar-default topbar"> <a href ="{%url 'home'%}">Home</a> | <a href ="{%url 'add-host'%}">Añadir Host</a> </nav> <section> {%block sectionhome%}{%endblock%} </section> </main> {%endblock%}} menu_elemenots.html: {%load staticfiles %} <div class="collapse navbar-collapse" id="bs-sidebar-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> Firewalls <span class="caret"></span> </a> <ul class="dropdown-menu forAnimate" role="menu"> {%for firewall in firewalls_list%} <li class="dropdown-item"> <a href="{%url 'firewall_detail' firewall.pk%}">{{firewall.name}}</a> </li> {%empty%} <li class="dropdown-item">No hay firewalls introducidos.</li> {% endfor %} <li class="dropdown-item"> <a href="{%url 'add-firewall' %}">Añadir firewall</a> </li> </ul> </li> <li class="dropdown "> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> Switches <span class="caret"></span> </a> <ul class="dropdown-menu forAnimate" role="menu"> {%for switch in switches_list%} <li class="dropdown-item"> {{switch.name}} </li> {%empty%} <li class="dropdown-item">No hay switches introducidos.</li> {%endfor%} <li class="dropdown-item"> <a href="{%url 'add-switch' %}">Añadir switch</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> Routers <span class="caret"></span> </a> <ul class="dropdown-menu forAnimate" role="menu"> {%for router in routers_list%} <li class="dropdown-item"> {{router.name}} </li> {%empty%} … -
Django jquery-ui Autocomplete with database 2.0
I'm sorry to dig up a subject (this one : Django jquery-ui Autocomplete with database) but it's old so there are maybe some modifications since this one. I want to do the exact same thing than malisit, I tried the exact same code than his one, but I still got problems. My model is 'Klient' (here is my models.py) : from django.db import models import pandas as pd from django.core.files import File import datetime class Klient(models.Model): id_klient = models.AutoField(primary_key=True) nom_klient = models.CharField(max_length=42) prenom_klient = models.CharField(max_length=42) argent = models.FloatField(default=0.0) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date ajout") associations=models.TextField(null=True) historique_transactions=models.FileField(default='/Users/antoinepradier/Desktop/site/site_kfet/site_K/historique/historique_transactions.xlsx') def __str__(self): return(self.nom_klient+' '+self.prenom_klient) Here is my html file (accueil.html) : <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all"/> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> <input id="n" type="text" name="n"/> My accueil.js is as follows : <script> $(document).ready(function(){ $( "input#n" ).autocomplete({ source: "{% url "autoco" %}", minLength: 2 }); }); </script> My view : def autoco(request): term = request.GET.get('term') bslk = Klient.objects.filter(nom_klient__istartswith=term) res = [] for b in bslk: dict = {'id':b.id, 'label':b.__unicode__(), 'value':b.__unicode__()} res.append(dict) return HttpResponse(json.dumps(res)) And finally my url : url(r'^autoco/$', views.autoco, name='autoco'), When I start typing the letters of a "Klient" nom_klient, nothing appears... Can someone help me to make it works? Thanks in advance! -
Django rest-auth registration. How to return user_id with the key when using token authentication
I am using Djando rest_auth.registration. My corresponding entry in urls.py is url(r'^rest-auth/registration/', include('rest_auth.registration.urls')) My authentication class is rest_framework.authentication.TokenAuthentication This rest API call works perfectly well. When I register via this API I get the below response. { "key": "3735f13cd69051579156f98ffda338a2d7a89bb5" } I also want to include the user_id field in the response. How do I go about doing that. I tried extending the method get_response_data from class RegisterView(CreateAPIView): but unable to do so. Can someone please advise the best practice to achieve this. Code would be ideal. Thanks. -
Get objects filtered by value of another table
I have the following model which links a user to his session: class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) session = models.ForeignKey(Session) Now I want to get all active sessions from the given user. How can I do the following SQL in Django 1.10? SELECT * FROM django_session WHERE session_key IN (SELECT session_id FROM usersys_usersession WHERE user_id = 1) AND expire_date > now() -
Django break if statement after first hit
I have a bunch of forloops and if statements in my django. How can I break an if-statement after first "true"-value? |slice:"1" does not work on if-statements. -
Django group based User Access Control
In my Django admin i added new field called privilage class along with groups and user permissions . so, my user table having privilage_class based on i am giving access to multiple groups. each groups having user_permissions. I made admin setup but permissions was not implemented . what to do beyond? for eg: user having priv class executive Privilege class if executive he having access to multiple groups-> Assets Billing etc Each groups carries user permissions (URL), Assets -> assets related URL Billing -> related URLs etc... setup has been done. but dont know how to apply permission. i know difficult to understand but pro will understand. so kindly help me regarding this. i am using django and DRF as well Thanks in advance! -
Django Channels Not working
I have been following Django channels tutorial, but I am stuck on why my application is not working. Whenever I change the database through the django ORM, I am not getting any updates on my browser. routing.py from channels import route_class from values.consumers import Secondmultiplexer channel_routing = [ route_class(Secondmultiplexer, path='^/stream2/?$') ] models.py from django.db import models from channels.binding.websockets import WebsocketBinding class SimpleStock(models.Model): ticker = models.CharField(max_length=30, primary_key=True) current_price = models.FloatField(default=0) class SimpleStockBinding(WebsocketBinding): model = SimpleStock stream = "stocks" fields = ["ticker", "current_price"] @classmethod def group_names(cls, instance): return ["stocks-updates"] def has_permission(self, user, action, pk): return True consumers.py from channels.generic.websockets import WebsocketDemultiplexer from .models import SimpleStockBinding class Secondmultiplexer(WebsocketDemultiplexer): consumers = { "stocks": SimpleStockBinding.consumer, } groups = ["binding.values"] index.html {% extends "base.html" %} {% block title %}Databinding Example{% endblock %} {% block header_text %}Databinding Example{% endblock %} {% block content %} {% endblock %} {% block extra_body %} <script> $(function () { var second_path = "/stream2/"; console.log("Connecting to " + second_path); var secondWebSocketBridge = new channels.WebSocketBridge(); secondWebSocketBridge.connect(second_path); secondWebSocketBridge.listen(); secondWebSocketBridge.demultiplex('stocks',function(payload, streamName) { console.log(payload); }); }); </script> {% endblock %} -
Django1.8 and Mongoengine NameError: name 'IntegerField' is not defined
I am using mongoengine with Django 1.8 and my project needs to connect to one instances of MongoDB while another with sql.But i am getting this error- command prompt- python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/html/admin_python/admin_app/models.py", line 212, in <module> class location(Document): File "/var/www/html/admin_python/admin_app/models.py", line 213, in location user_id = IntegerField(blank=True, null=True) NameError: name 'IntegerField' is not defined my setting.py file- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'admin_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', }, } from mongoengine import connect connect( db='pom', username='admin', password='root', host='mongodb://admin:root@localhost' ) so First i decided to complete all work related to mongodb then i will move on to sql.This is the code for model of mongodb database my model.py file - class location(Document): user_id = IntegerField(blank=True, null=True) name = CharField(max_length=100) loc_lon = FloatField(blank=True, null=True) timestamp = IntegerField(blank=True, null=True) activity = StringField() lot_lat = FloatField(blank=True, null=True) batter_status = StringField() address … -
Defining an Abstract model with a ForeignKey to another Abstract model
I'm trying to build two abstract classes called SurveyQuestionBase and SurveyResponseBase that will serve as templates to quickly define new concrete Models for implementing specific surveys on our website. The issue I am having is in enforcing that the SurveyResponseBase model, when made concrete, should define a ForeignKey to a concrete model of SurveyQuestionBase. Django does not allow us to define ForeignKeys to abstract classes so I cannot, for instance, do this: question = models.ForeignKey(SurveyQuestionBase) Neither can I have it as None or app_label.ModelName for similar reasons. One hacky fix is to create a new concrete model SurveyQuestionConcrete and make the ForeignKey point to this: question = models.ForeignKey(concrete_model), combined with validation to ensure this model is replaced. Is there a cleaner way to achieve the same thing? All I need to do is ensure that when someone defines a concrete model from SurveyResponseBase they include a ForeignKey to a concrete model defined from SurveyQuestionBase Here's the full code: from __future__ import unicode_literals from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models # Implementation borrows from: https://github.com/jessykate/django-survey/ class SurveyQuestionBase(models.Model): TEXT = 'text' INTEGER = 'integer' RADIO = 'radio' SELECT = 'select' MULTI_SELECT = 'multi-select' ANSWER_TYPE_CHOICES = ( (INTEGER, … -
Using a class as a part of another class in django models
Assume I am writing an app to change configurations in a machine. I have 3 created tables as below. Machine configuration shows the current state of configurations for our machine. Users can create their tickets and request for changes of the configurations. RequestDetails will be the table to keep the proposed cofigurations plus some extra info such as the name of the requestor, date etc. These classes are just a simple examples, in the real model I would have nearly 600+ fields=configuration presented in class MachineConfiguration. I should have EXACTLY THE SAME fields in RequestDetails class too. I was wondering there is a way NOT TO REPEAT MYSELF when defining class RequestDetails when it comes to all the fields that exist in MachineConfiguration model? I want to write it in a way that if I changed anything in MachineConfiguration table, the same change would apply to RequestDetails table too. Thanks in advance for the help. class RequestTicket(models.Model): subject=models.CharField(max_length=50, null=False, blank=False) description=models.TextField(null=False, blank=True) class MachineConfiguration(models.Model): field_1 = models.CharField(null=False,blank=True) field_2 = models.CharField(null=False, blank=True) field_3 = models.CharField(null=False, blank=True) class RequestDetails(models.Model): tracking_number=models.ForeignKey('RequestTicket') field_A=models.DateField(null=True, blank=False) field_B=models.TextField(null=True, blank=False) field_1 = models.CharField(null=False, blank=True) field_2 = models.CharField(null=False, blank=True) field_3 = models.CharField(null=False, blank=True) -
observable to return many json objects from server will contain all at once or iterate through?
I'm using angular 4 and typescript I have created an api endpoint that will return a array of json objects. My question refers to capturing the json inside a variable designed to hold an array of javascript objects. Will the observable return a list of json objects to where I can just set the variable in my typescript code to that array? And if so how. Or do I have to iterate through the list of json objects and append them to the array variable? Notice no code, as I am confused as to when I use interaces, when I use constructors and the alike. I would like to see how this is done. I am still learning -
django admin multi-sort without clear checkbox
I want when user sort the displayed data without clear the already selected checkbox. At present, user selected one data with checkbox selected, when user sorted the data by click another column head, the selected checkbox was cleared. How can I avoid the checkbox from clear? class statsdata(models.Model): timestamp = models.DateTimeField() Name = models.CharField(max_length = 30) val1 = models.FloatField() val2 = models.FloatField() val3 = models.FloatField() class statsdataAdmin(admin.ModelAdmin): list_display = ('Name', 'val1', 'val2', 'val3') admin.site.register(statsdata, statsdataAdmin) -
def_context_data for ImageField
I need to show on main page my new application for showing 2 images. I have to assign it only to the view of the main page for use in my 'base.html'. models.py: from django.db import models from django.utils.translation import ugettext_lazy as _ class MainPageImages(models.Model): left_img = models.ImageField(_('Left image'), upload_to='media/%Y/%m/%d') right_img = models.ImageField(_('Right image'), upload_to='media/%Y/%m/%d') views.py: def get_context_data(self, **kwargs): comment_initial_data = { 'content_type': ContentType.objects.get_for_model(self.model).id } reply_initial_data = { 'content_type': ContentType.objects.get_for_model(Comment).id } comment_form = CommentForm(initial=comment_initial_data) reply_form = CommentForm(initial=reply_initial_data) context = super(IndexView, self).get_context_data(**kwargs) context['comment_form'] = comment_form context['reply_form'] = reply_form return context Can you help me? I need edit that function and add my new app for use in templates. All the best, Dinson -
How can I change Backsapce functionality?
I'm designing a web application with django. in this app user can ask their question. if they click on submit button the question would send and redirect to another page. but when user click on Back button in browser, then again the question web page appears with previous content and if user click on send button again the question would send for the second time. Now, how can I define that after asking a question when user click on Back button another template appears for them. This is my View: def ask(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): userID = request.session.get('mainSession', 0) user = msignup.objects.get(id=userID) msignupInstance = msignup.objects.get(pk=userID) question = Question() question.user = user question.title = form.cleaned_data.get('title') question.description = form.cleaned_data.get('description') id=int(question.field)) question.save() return redirect('/questions/allquestions') else: return render(request, 'questions/ask.html', {'form': form, }) else: form = QuestionForm() return render(request, 'questions/ask.html', {'form': form, }) and this is my template: {% for ali in form.visible_fields %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.label }}" class="col-sm-4 control-label">{{ ali.label }}</label> <div class="col-sm-10"> {{ ali }}<br> {% for error in field.errors %} <label class="control-label">{{ error }}</label> {% endfor %} </div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-offset-0 col-sm-10"> <button … -
Password Widget and Password Hashing in Django Admin
I am new in Python coding and now trying to learn Django. Right now i am using django 1.11.3 version. So i have learned the basic thing in Django and created an app. In my app, i have created a student model which include an password field. What i have noticed is, in Admin module password field is stored in simple text. So i need help to hash the password field in admin module. I need md5 hashing. So can u guys help me. Is there any method to solve this? This is what i have tried. My Model class student(models.Model): name = models.CharField(max_length=100) age = models.CharField(max_length=2) dob = models.DateField() father_name = models.CharField(max_length=100) username = models.CharField(max_length=25,null=True) password = models.CharField(max_length=100,null=True) def __unicode__(self): return self.name My Admin from django.contrib import admin from django import forms from .models import student admin.site.register(student) class studentAdmin(admin.ModelAdmin): formfield_overrides = { student.password: {'widget': forms.PasswordInput}, } -
Multiple databases (mongoengine and sql ) with django 1.8
I am using mongoengine with Django and within my project need to connect to one instances of MongoDB while another with sql .How my databse section of setting.py should be like ? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'admin_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', }, } from mongoengine import connect connect( db='pom', username='admin', password='root', host='mongodb://admin:root@localhost' )