Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
net::ERR_INSECURE_RESPONSE in Chrome after update, but never before, SSL is secure
I know this is currently a frequent question but I haven't found anything addresing my version of it. I am sending ajax GET request to a django server that runs on C9 IDE and they are getting canceled since the last Chrome update to v56. I have always closely monitored js errors, there never has been one like it. When i checked my SSL on SSL Labs it's everything green and secure. In Chrome Security the page is marked as Secure with Valid certificate, Secured Resources but with obsolete connection settings: The connection to this site uses a strong protocol (TLS 1.2), a strong key exchange (ECDHE_RSA with P-256), and an obsolete cipher (AES_256_CBC with HMAC-SHA1). This is the only vulnerability that I found, could this be the reason why my ajax request get canceled? If so, how do I fix this? Or perhaps, do I miss something? This is not my area of expertise at all ... -
Initialize user django so he has default settings values
I am using Django + Angular 2 . I am creating a user fine but he does not have the default values i want... Model class Settings(models.Model): user = models.ForeignKey('auth.User', related_name='settings', on_delete=models.CASCADE) bolean1 = models.BooleanField(default=False) boolean2 = models.BooleanField(default=False) boolean3 = models.BooleanField(default=False) string1 = models.CharField(max_length=100, default='No description') Serializer class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ('id', 'bolean1', 'bolean1', 'bolean3', 'string1') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password' ,'settings', 'image') extra_kwargs = {'password': {'write_only': True}} class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Views class SettingsValues(generics.ListAPIView): serializer_class = SettingsSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): queryset = Settings.objects.all() queryset = queryset.filter(user=self.request.user.id) return queryset class RegisterUser(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = CreateUserSerializer The problem is that when i create a new user he does not have default values,e.g boolean 1, boolean 2 etc. i must go to django admin create new setting and choose the user. Any idea ? -
In Django, the PostgreSQL specific function ArrayAgg doesn't support multiple fields?
Does ArrayAgg only support single field? I notice the sql command generated by ArrayAgg in django doesn't have parentheses inside ( array_agg(...) ), which means it can only handle single field. I reckon array_agg((...)) can support multiple fields. -
Use django classes outside of Django in normal module
I would like to use Django classes outside of Django framework, like in Jupyter or in any module. From this using django model outside of the django framework, I have seen this import django import sys import os sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor")) os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings' django.setup() django.contrib.gis.geos It seems there are issues with GAL and geos packages.... -
Django interactiveshell returns model objects in object form and not as string
This code is from models.py in my App called article from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField('date published') likes = models.IntegerField() def __unicode__(self): return self.title I've added 3 objects into the db like this >>> from django.utils import timezone >>> a = Article(title = "Test 1", body = "blah blah blah " ,pub_date=timezone.now(),likes=0) >>> a.save() >>> a.id 1 >>> a = Article(title = "Test 2", body = "blah blah blah " ,pub_date=timezone.now(),likes=0) >>> a.save() >>> a.id 2 >>> a = Article(title = "Test 3", body = "blah blah blah " ,pub_date=timezone.now(),likes=0) >>> a.save() >>> a.id 3 >>> Article.objects.all() <QuerySet [<Article: Article object>, <Article: Article object>, <Article: Article object>]> whenever i called Article.objects.all() method it returns me the title in object form. From the documentation the unicode method must return me the actual title in the string form. I'm new to Django and i've tried alot changing the unicode method but nothing seems to work. Thanks you in advance here is the output I am getting from article.models import Article >>> Article.objects.all() <QuerySet [<Article: Article object>, <Article: Article object>, <Article: Article object>]> and the output i want <QuerySet … -
How to build TextField version control in Django?
I'm looking for a way to implement stackexchange-like question editing system. Any ideas how to do that? Required features are browsing versions of TextField and git-like "diff" for displaying changes between versions. -
Not naive timezone when querying django
I have deleted all timezone-naive entries out of my Sqlite-DB. So now they remaining entries have a datefield like this: 2016-09-04 13:28:16+00 When I now run my query like this: result = Feedentry.objects.filter(date_published__gt=timezone('Europe/Berlin').localize(datetime(2016, 8, 31, 17))) First I receive no error, but as soon as I want to access the result (or len(result)) I receive the following error: raise ValueError('Not naive datetime (tzinfo is already set)') Any ideas how to solve it or what I did wrong? -
Django TextField version control system
Is there any Django apps to handle TextField changes with the edit history? Something like stack exchange question edit history works. -
Error 'OrderedDict' object has no attribute 'pk' django rest + react
Im trying to add a comment to my db, but getting error 'OrderedDict' object has no attribute 'pk' The part of react.js code handling the POST request: addComment() { let url = this.props.post_url axios.post('/api/comments/', { post: url, user: "http://127.0.0.1:8000/api/users/1/?format=json", text: document.getElementsByName(url)[0].value, csrfmiddlewaretoken: document.getElementsByName("csrfmiddlewaretoken")[0].value}, ) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); } My serializers.py: from django.contrib.auth.models import User from rest_framework import serializers from .models import Post, Comment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'url') class CommentSerializer(serializers.HyperlinkedModelSerializer): #user = UserSerializer(many=False, required=False) class Meta: model = Comment fields = ('id', "post", "user", 'text') read_only_fields = ('id', "user") def create(self): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user class PostSerializer(serializers.HyperlinkedModelSerializer): #user = UserSerializer(required=False) comments = CommentSerializer(many=True, required=False, read_only=True) class Meta: model = Post fields = ('id', 'title', "user", "url", "comments", 'text') read_only_fields = ('id', "url", "comments") def save(self): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user My views.py from django.contrib.auth.models import User from api.serializers import UserSerializer from rest_framework import viewsets from .models import Comment, Post from .serializers import CommentSerializer, PostSerializer from django.http import Http404 from rest_framework.response import Response from rest_framework import status class … -
Cannot resolve added property of model in views
In my views.py file, I filter objects from a model, and I add some properties to the objects to use them later in templates. matches = Match.objects.filter(season=season_name).order_by("match_date") team_list = Team.objects.filter(id__in=team_ids) for team in team_list: home_matches = matches.filter(home_team=team) away_matches = matches.filter(away_team=team) team.sf = len(Shot.objects.filter(match__in=matches, team=team)) team.sa = len(Shot.objects.filter(match__in=matches, opponent_team=team)) team.pdo = ((team.f / team.sf) + (1 - (team.a / team.sa))) * 1000 team.xpdo = ((team.xgf / team.sf) + (1 - (team.xga / team.sa))) * 1000 For example, in my team model, fields sf, sa, pdo and xpdo does not exist. I calculate those fields on views and use them in a table in my template. There is no problem until here, actually. What I am trying to do is dumping query set as JSON and passing it the template to use in JavaScript. context["teams_json"] = json.dumps(list(team_list.values_list( "team_name", "pdo", "xpdo")), cls=DjangoJSONEncoder) When I run the server, I get the following error: FieldError at /leagues/turkey2017/ Cannot resolve keyword 'pdo' into field. Choices are: away_team, home_team, id, opponent_team, passmaplineup, passmappass, player_stats_opponent_team, player_stats_team, shooter_team, team_dark_color, team_light_color, team_name I see that choices are combination of original fields in my Team model and ForeignKey fields in other models such as this field in Shot model: opponent_team = … -
Django Rest Swagger 2.11: render input UI
I read this post and do as the answers, but on the Swagger web UI, there is no any input fields for my APIs. I'm using Django 1.10, DRF 3.5.4, django-rest-framework 2.11. Here are some snippets from my code Model.py from django.conf import settings from django.db import models from api.v1.managers.place_type import PlaceTypeManager class PlaceType(models.Model): placeTypeManager = PlaceTypeManager() objects = models.Manager() name = models.CharField(unique=True, db_index=True, max_length=64, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.BooleanField( verbose_name=u'Status', default=False, choices=settings.STATUS_CHOICES, ) class Meta: db_table = 'place_type' serializers.py from rest_framework import serializers from api.v1.models.place_type import PlaceType class PlaceTypeSerializer(serializers.ModelSerializer): class Meta: model = PlaceType fields = '__all__' views.py class PlaceTypeView(APIView): permission_classes = [permissions.AllowAny, ] serializer_class = PlaceTypeSerializer def get(self, request, *args, **kwargs): print("Success!") -
django form is valid() fails
I am trying to create a registration form using django, when I submit my form the is valid() function fails and I am not sure why. I have my registration and login page all on one html page, although, I have called all the field names different names, eg login_username. forms.py class SignUpForm(forms.Form): username = forms.CharField(label='Username', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Username'})) conUsername = forms.CharField(label='Confirm Username', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Confirm Username'})) firstName = forms.CharField(label='First Name', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Firstname'})) lastName = forms.CharField(label='Last Name', max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter LastName'})) email = forms.CharField(label='Email', max_length=220,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Email','type':'email'})) conEmail = forms.CharField(label='Confirm Email', max_length=220,widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'Confirm Email','type':'email'})) password = forms.CharField(label="Confirm Password", max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','type':'password','placeholder':'Enter Password'})) conPassword = forms.CharField(label="Confirm Password", max_length=20,widget=forms.TextInput(attrs={'class': 'form-control','type':'password','placeholder':'Confirm Password'})) views.py def SignUp(request): regForm = SignUpForm() form = LoginForm() if request.method == 'POST': if regForm.is_valid(): username = regForm.cleaned_data('username') print username confirm_username = regForm.cleaned_data('conUsername') first_name = regForm.cleaned_data('firstName') last_name = regForm.cleaned_data('lastName') email = regForm.cleaned_data('email') confirm_email = regForm.cleaned_data('conEmail') password = regForm.cleaned_data('password') confirm_password = regForm.cleaned_data('conPassword') #try: #user = User.objects.get(username=request.POST['username']) #return render(request, 'index.html',{'error_message':'username must be unique'}) #except User.DoesNotExist: #user = User.objects.create_user(request.POST['username'], password=request.POST['password']) #login(request, user) #return render(request, 'index.html') else: return render(request,'index.html',{'username_error':'usernames didnt match','form':form,'regForm':regForm}) else: return render(request, 'index.html',{'form':form,'regForm':regForm}) index.html <form class="regForm" method="POST" action="{% url 'signup' %}"> {% csrf_token %} {{username_error }} <div class="row"> <div class="col-md-2 col-md-offset-8"> <div class="form-group"> {{regForm.error_message.username}} {{ … -
django rest framework - serializing related object fields to a flat json dict
The DRF docs describe a way to create nested serializers that can produce dicts like this: { "field1": "val1", "field2": "val2", "related_obj": { "related_obj_field_1": "val1", "related_obj_field_2": "val2", } } but what if I want to create a flat dict that would include all related object fields at the same level as the parent object fields? Like so: { "field1": "val1", "field2": "val2", "related_obj_field_1": "val1", "related_obj_field_2": "val2", } -
Retrieving RSS xml News data using Jquery/Ajax in Django
I am trying to do the following: I need to download the headlines from BBC and CNN using Ajax and jquery in Django. I tried first to download the data in javascript but I am getting a 'Access-Control-Allow-Origin' so i worked out I needed to do this through the backend in django. this needs to be done synchronously so that the browser doesn't have to be refreshed to redownload the data. The requirements for my program: Build a web application that displays, side by side, the headlines from both BBC and CNN, using their RSS (XML) feeds. You application should use jQuery’s support for Ajax. The Django backend should download the news from: • http://feeds.bbci.co.uk/news/rss.xml • http://rss.cnn.com/rss/cnn_topstories.rss and serve those to the client upon the ajax request for a news update So far i have the following: from django.shortcuts import render import requests def index(request): context = {} return render(request, 'home/Newshome.html', context) def submit(request): xml_news = requests.get('http://rss.cnn.com/rss/cnn_topstories.rss') news = xml_news.content return render(request, 'home/Newshome.html', {'news': news}) <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> $(document).ready(function() { $.ajax({ type: "GET", url: "http://rss.cnn.com/rss/cnn_topstories.rss", dataType: "xml", success: function upon_success(xml) { $(xml).find('item').each() } }); }); </script> </head> <body> <h1>Top News: BBC versus CNN</h1> {% for item … -
Using Django ORM to retrieve recent rows
In SQL, if I wanted to query a table for data from the most recent 10 minutes (regardless of timezones and such), I'd simply do (using postgresql parlance): select * from table where creation_time > now() - interval'10 mins'; Is there an equivalent way to do something like this using the Django ORM, disregarding what timezone settings one has set for the app? Would be great to get an illustrative example here. -
Django Nginx: Why doesn't my app follow MEDIA_ROOT?
I have a Django project with the following static and media settings in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/') MEDIA_URL = '/media/' I have it running with Nginx and Gunicorn but when I upload an image using the admin page, the MEDIA_ROOT setting is not respected.. It actually makes a media directory in a different folder. What could be causing this? -
In centos - No module named lazy_object_proxy while executing prospector library for python
After installing prospector by using pip install prospector, I execute this command. prospector --version `I get this error Traceback (most recent call last): File "/home/ec2-user/ingestion/acadenv/bin/prospector", line 7, in <module> from prospector.run import main File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/prospector/run.py", line 8, in <module> from prospector import blender, postfilter, tools File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/prospector/tools/__init__.py", line 7, in <module> from prospector.tools.pylint import PylintTool File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/prospector/tools/pylint/__init__.py", line 6, in <module> from pylint.config import find_pylintrc File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/pylint/config.py", line 48, in <module> from pylint import utils File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/pylint/utils.py", line 39, in <module> from astroid import nodes, Module File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/astroid/__init__.py", line 54, in <module> from astroid.nodes import * File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/astroid/nodes.py", line 39, in <module> from astroid.node_classes import ( File "/home/ec2-user/ingestion/acadenv/local/lib/python2.7/dist-packages/astroid/node_classes.py", line 24, in <module> import lazy_object_proxy ImportError: No module named lazy_object_proxy Moreover I have executed pip install lazy_object_proxy but this does not solve the problem also. -
how to filter in django admin inlines
`class StudentsTeacher(admin.TabularInline): form = StudentsTeacher model = StudentsTeacher class Teacher_Admin(admin.ModelAdmin): inlines = (StudentsTeacher,) I want add a queryset in StudentsTeacher select with a filter,but it doesn't work , inlines always dispay all ` -
Сannot make Python request from Django hosting
I want to make a site that will get some information from authorised page. There is a web-page with form where I enter cookies and some other data. Using them I want to get text of web page, but I can get it only if made get-request with my cookies. So when i make this request using python shell everything is good - I get text of authorised page. p = requests.post('https://lalala.com/public140466996',headers={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.92 Safari/537.36 Vivaldi/1.6.689.34","Cookies":"somecookies","Host":"lalala.com"}) But when I try to make it on hosting web server using Django I get a response with not authorised page def index(request): if request.method =='POST': data = SearchForm(request.POST) if data.is_valid(): group = data.cleaned_data.get('group') remixsid = data.cleaned_data.get('remixsid') post_number = data.cleaned_data.get('post_number') comment = data.cleaned_data.get('comment') p = requests.post('https://lalala.com/public140466996',headers={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.92 Safari/537.36 Vivaldi/1.6.689.34","Cookies":"somecookies","Host":"lalala.com"}) return HttpResponse(p.text) Could you help and explain why i have this problem? Maybe hosting don't add cookies or add something that allowed? -
Representing an App decision flow as a mind map
I am attempting to build a web application to build an app with. Basically, it will work like a mind map, each step is a page, and each page will have options in the page to select. Some pages will lead to another page, whereas some options in a page will lead to another page. This would be represented as follows in my models: class Option(models.Model): key = models.CharField(max_length=256) value = models.CharField(max_length=256) def __unicode__(self): return self.value class Item(models.Model): key = models.CharField(max_length=256) value = models.CharField(max_length=256) image = models.ImageField(upload_to="builder/item", null=True, blank=True) options = models.ManyToManyField(Option, blank=True) goto = models.ForeignKey("Page", null=True, blank=True) def __unicode__(self): return self.value class Page(models.Model): survey = models.ForeignKey(Survey) title = models.CharField(max_length=256) items = models.ManyToManyField(Item) parent = models.ForeignKey("Page", blank=True, null=True) I want to build these relationships in a visual way, the user would add a new page, add items to the page, and from each option choose a next page (if applicable) or just next page from the current page (this would be a next arrow on the footer bar of the app). All this would be like a mind map. Sort of how its done in x I looked at gojs but this does not really do what I want. Could … -
Fab Speed Dial not working with django {% verbatim%}
I am trying to use ng-repeat over list of image coming from my controller to show as md-fab-actions which cause actions button always opened or expanded, means mouse click is not working. The commented code of html works fine without ng-repeat, means expands and collapses well on mouse click. The angular controller code shows the list of images for which I want to use ng-repeat. -
How to handle view throwing manual exception in django in unit-testing?
I have made a django application and am writing tests for it. In one of my views I'm manually throwing an exception: raise Http404('Not authorised') While writing test for that using django's built-in test framework(based on unittest). TL;DR: Is there way to write test such that it makes sure that the view is indeed returning Http404. ( assertEqual(response.status_code, 404 doesn't work) -
SQL table doesn't exist error even though it does
When I run 'show tables' in mysql, I get these: +-------------------------------------+ | Tables_in_classscanner | +-------------------------------------+ | ... | | djcelery_crontabschedule | | djcelery_intervalschedule | | djcelery_periodictask | | djcelery_periodictasks | | djcelery_taskstate | | djcelery_workerstate | | ... | +-------------------------------------+ The 'djcelery_periodictask' is clearly shown and when running: select * from <any_of_the_above_tables> it works and successfully prints empty set or the data. But, for only the "djcelery_periodictask" table, I am getting a table doesn't exist error even though it clearly does as shown from the show tables command. Does anyone know why I am having this problem? I am running both both django celery 3.1.17 and celery 3.1.17. -
heroku django could not connect to server on db txn
I deployed my app on heroku, but when I do some DB operation, this is what I get: Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I am using Postgres and defined all details in config vars: DB_NAME=xx DB_USER=xx DB_PASSWORD=xx DB_HOST=127.0.0.1 DB_PORT=5432 and the part of code: if request.method == 'POST': form = form_signup(request.POST) if form.is_valid(): full_name = form.cleaned_data['full_name'] username_email = form.cleaned_data['username_email'] password = form.cleaned_data['password'] user = User.objects.create_user(username_email,username_email,password) return HttpResponse("Done") What should I do? -
Not working .add( ) function in ManyToMany Relation of Python3 Django
now I'm designing data modeling with ManyToManyField in Django. I would like to make each sessions have various instruments, i.e) A have a bass. B have a drum. So, I tested next codes from django.test import TestCase from Session.models import Instrument from Applicants.models import MyUser from Session.models import Session class InstTest(TestCase): def setUp(self): i1 = Instrument.objects.create(name='bass') i1.save() i2 = Instrument.objects.create(name='guitar') i2.save() i3 = Instrument.objects.create(name='drum') i3.save() u1 = MyUser.objects.create(email='a@gmail.com', nickname='A') u2 = MyUser.objects.create(email='b@gmail.com', nickname='B') s1 = Session.objects.create(players=u1) s1.save() s1.instruments.add(i1) s2 = Session.objects.create(players=u2) s2.save() s2.instruments.create(name='drum') def test_example(self): bass = Instrument.objects.get(name='bass') guitar = Instrument.objects.get(name='guitar') user = MyUser.objects.get(nickname='A') player = Session.objects.get(players=user) self.assertEqual('bass', bass.name) self.assertEqual('A', player.players.nickname) # My problem is in this line self.assertEqual('bass', player.instruments.name) and this is result in Pycharm /home/user/vEnv/bin/python /home/user/pycharm-2016.3.2/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 40507 --file /home/user/pycharm-2016.3.2/helpers/pycharm/django_test_manage.py test BandMaker.tests.InstTest.test_example /home/user/PycharmProjects/Project Testing started at --:-- PM ... warning: Debugger speedups using cython not found. Run '"/home/user/vEnv/bin/python" "/home/user/pycharm-2016.3.2/helpers/pydev/setup_cython.py" build_ext --inplace' to build. pydev debugger: process 4984 is connecting Connected to pydev debugger (build 163.10154.50) Creating test database for alias 'default'... Failure Traceback (most recent call last): File "/home/user/PycharmProjects/project/BandMaker/tests.py", line 31, in test_example self.assertEqual('bass', player.instruments.name) AssertionError: 'bass' != None Destroying test database for alias 'default'... Process finished with exit code 1 I tried to …