Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels; ECHO example doesn't work
Consumers file def ws_message(message): # ASGI WebSocket packet-received and send-packet message types # both have a "text" key for their textual data. message.reply_channel.send({ "text": message.content['text'], }) Routing file from channels.routing import route from myapp.consumers import ws_message channel_routing = [ route("websocket.receive", ws_message), ] What I'm running. socket = new WebSocket("ws://" + window.location.host + "/chat/"); socket.onmessage = function(e) { alert(e.data); } socket.onopen = function() { socket.send("hello world"); if (socket.readyState == WebSocket.OPEN) socket.onopen(); It does nothing at all. I've seen other issues like this and they all said to downgrade twisted to 16.2. Well I did that but then runserver started to give me can't import IProtocol--- issues. Is there a fix to this, or should I just not use channels, and try something else? -
Django: Convert multiple ForeignKey to ManyToMany
I have a model History with one ForeignKey to a Task model and another ForeignKey to User model. I now realise that I could have originally set up a ManyToManyField from Task to User, using History as an intermediate table. Is there any advantage to switching from my current setup to the m2m version? -
Socket.io not working with nginx
I have a nicely working django website which is being served by gunicorn and nginx(as a proxy server), now i want to add chat mechanism in that website using socket.io and nodejs. The problem is that the chat works perfectly fine when i connect socketio directly to nodejs server(which is listening on port 5000) but when i try to use nginx to proxy the socketio request to nodejs it doesn't work. Here is my nginx file in /sites-enabled/ dir server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/static; } location / { include proxy_params; proxy_pass http://unix:/path/to/file.sock; } location /socket.io/ { proxy_pass http://127.0.0.1:5000; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } -
Django lightweight development Web server can't run for a long time
Django 1.11 I decided to demonstrate what I have done to my friends. I have paid for hosting, installed nginx and proxied the requests to Django. Then I went to the project directory and typed "python manage.py runserver". Well, this is for demonstration purposes. It is not a production. The problem is: in about half an hour the process disappeared. And nginx shows 502 Bad Gateway. When I run in Linux "ps aux | grep runserver", there is no development Web server running. So, it disappeared. Why the process disappeares? Where can I find any settings to regulate the life time of this process? -
How to reduce max_length of CharField in Django when data already exists in db
I have a CharField on a Django (1.9) model: alias = models.CharField(max_length=50) The app is being used and already has data, and there are objects using all 50 characters already. What is the simplest method to reduce the max_length of this field without getting complaints from my production database when I try to migrate? DB is postgresql if it makes a difference. -
Two background manager page use a little different base template
There are two user background manager page, one for staff to manage order, enterprise. one for normaluser to manage themself order or user center. So there are two url path: /staff_bg/ /user_bg/ But they are use the same base template, the only different is the header tabs is not same. For example: user_header.html {% extends "core/base.html" %} <header> <ul> <li>your orders</li> </ul> </header> staff_header.html {% extends "core/base.html" %} <header> <ul> <li>enterprise</li> </ul> </header> then: user_realted.html: {% extends "core/user_header.html" %} # focus here {% block body %} # something {% endblock %} then: staff_related.html {% extends "core/staff_header.html" %} # focus here {% block body %} # something {% endblock %} my solution: create core/middle.html: {% extends the_template_name %} then user_realted.html: {% extends "core/middle.html" %} # focus here {% block body %} # something {% endblock %} One way write custom template processor, base one request.path pass different the_template_name( "cms/user_header.html" or "core/staff_header.html" ) to middle.html, but I think it's dirty, and if code wrong, maybe normal user can see the staff tabs. another way: pass different the_template_name to middle.html, in every view. of course, it will change every view that already wrote. -
User location lat/lon from frontend
I am having some trouble understanding what I need to do to get the user lat/lon in order return results based on their location. To retrieve the user location I used the HTML5 geolocation javascript function. I am trying to get the user location when the page loads (unsure if this is proper), then return results based on the distance to the location. What is the proper way to achieve this? Anyway here is some code, let me know if additional details are needed. Model class Location(models.Model): # Fields ... latitude = models.FloatField(max_length=100, null=True) longitude = models.FloatField(max_length=100, null=True) geo_point = models.CharField(max_length=200, null=True) point = gmodels.GeometryField(srid=4326, blank=True, null=True) objects = gmodels.GeoManager() class Meta: ordering = ('name',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('location_detail', args=(self.slug,)) def get_update_url(self): return reverse('location_update', args=(self.slug,)) Views class LocationListView(ListView): model = Location class LocationCreateView(CreateView): model = Location form_class = LocationForm class LocationDetailView(DetailView): model = Location class LocationUpdateView(UpdateView): model = Location form_class = LocationForm Search class LocationListView(ListAPIView): model = Location queryset = Location.objects.all() serializer_class = Location filter_backends = (FullWordSearchFilter, DistanceToPointFilter, ) word_fields = ('name', 'zip_code', 'city', 'state', 'point') template = 'appname/search_submit.html' response_message = 'This is the response' def post(self, request): template = loader.get_template(self.template) query = request.POST.get('search', … -
How to add multiple objects from a given table (including possible duplicates) to another object?
Keep in mind this is all using Django-autocomplete-light to select objects and add them to another object. I have a list of repairs in a table called Repair. I wanted to use this list to assign multiple repairs to bikes in the table Bike. However, there can be duplicates of the same repair on a single bike, i.e. Flat Repair (if it needs front and rear flat repair). What is the standard way to do this in Django? I would really rather prefer using a table that I then reference and somehow keep a count of duplicate repairs. As of now, I can only have one Flat Repair per bike. In essence, the user should be able to type in a field and have repair choices show up and autocomplete. As they hit enter, the repairs, even duplicates, are added to the bike. -
Why is stylesheet only working for the index page, but not for any extensions of the index page? (templates using Jinja)
As I said in the title; I am making a basic blog using Django, and while I have a basic line of code that ties the CSS stylesheet to the index of the blog; this works just fine, but whenever I link to any template of said index sheet the stylesheet does not seem to roll over onto the template. In other words, the template does not have any CSS applied to it, unlike the index sheet. I am using Jinja2 template sequencing. This is the current HTML line linking the stylesheet: `<link rel="stylesheet" type="text/css" href="static/style.css" />` This is the template in question: {% extends 'tempblog/index.html' %} {% block content %} <br /><br /><br />Hi! {% for post in latest_posts %} <ul> <br /><br /> <li> {{ post.title }} </li><br /><br /> {{ post.body }} </ul> {% endfor %} {% endblock %} Also please note that the template is displaying all database calling just fine, this is a matter of the stylesheet only working on the index, and not on any extension of the index page. Thank you. -
Python-django url with two slugs
Hello I have a problem while I am trying two slugs in one url. I have: html file: <div class="panel-heading"> <h4><a class="link" href="{% url 'data:inspection_detail' plant_slug=plant.slug inspection_slug=inspection.slug%}">{{inspection.name}}</a></h4> </div> views.py file def inspection_detail(request, inspection_slug, plant_slug): if not request.user.is_authenticated(): return render(request, 'data/login.html') else: user = request.user plant = get_object_or_404(Plant, slug=plant_slug) inspection = get_object_or_404(Inspection, slug=inspection_slug) template = 'data/inspection_detail.html' context = {'inspection': inspection, 'user': user, 'plant':plant} return render(request, template, context) and my url patterns: url(r'^plants/(?P<plant_slug>[-\w])/(?P<inspection_slug>[-\w]+)/$', views.inspection_detail, name='inspection_detail'), But I get: Page not found (404) And I cant see where is the mistake! -
Let's Encrypt with uWSGI
I'm attempting to follow these instructions here to install an SSL cert for my domain. However, these instructions seem to assume that nginx is the only server. I'm using nginx with uwsgi. I'm new to both. I don't believe uwsgi has a 'webroot'(?). My django app is served from /home/me/myapp. I've created the .well-known directory there, like so: /home/me/myapp/.well-known. Using this command: sudo certbot certonly --webroot --webroot-path=/home/me/myapp -d myappdomain.com -d www.myappdomain.com I get this error: Domain: www.myappdomain.com Type: unauthorized Detail: Invalid response from http://www.myappdomain.com/.well-known/acme-challenge/HOjaeQfDlYQzAYfwGLltammjg6kMnwChV-Bc9BL2bSA: How can I properly server the .well-known directory if I have uWSGI behind NGINX? -
DRF Serializer fields DictField() AttributeError: 'str' object has no attribute 'items'
In django rest framework If i use DictField() in serializer its given me AttributeError at /api/v1/analytics/reports-configuration/2/ ‘str’ object has no attribute ‘items’ error.please take a look. serializers.py import json from rest_framework import serializers from models import ReportConfiguration class ReportConfigurationSerializer(serializers.ModelSerializer): report_type = serializers.ChoiceField(choices=['query', 'activity', 'summary']) read_only = serializers.BooleanField(required=True) query_data = serializers.DictField(required=True) class Meta: model = ReportConfiguration fields = ('id', 'title', 'query_data', 'created_by', 'last_activity_by', 'deleted', 'deleted_by', 'added_at', 'last_activity_at', 'report_type', 'read_only') def validate(self, data): if data['report_type'] is not 'summary' and data['read_only'] is True: raise serializers.ValidationError("If read only true then report type should be summary") if data['report_type'] is 'summary' and data['read_only'] is not True: raise serializers.ValidationError("If read only not true then report type should not be summary") return data def create(self, validated_data): validated_data['created_by'] = self.context['request'].user validated_data['last_activity_by'] = self.context['request'].user return ReportConfiguration.objects.create(**validated_data) views.py class ReportConfigurationViewSet(viewsets.ModelViewSet): serializer_class = ReportConfigurationSerializer queryset = ReportConfiguration.objects.all() permission_classes = (permissions.IsAuthenticated,) filter_backends = (DjangoFilterBackend,) filter_class = ReportFilter def list(self, request): response = super(ReportConfigurationViewSet, self).list(request) for data in response.data['results']: data['query_data'] = json.loads(data['query_data']) return response def retrieve(self, request, pk=None): response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk) response.data['query_data'] = json.loads(response.data['query_data']) return response models.py class ReportConfiguration(models.Model): class ReportTypeChoice(Choice): QueryReport = 'query' ActivityReport = 'activity' SummaryList = 'summary' title = models.CharField(max_length=300, unique=True, blank=False, null=False) query_data = JSONField(default={}) created_by = models.ForeignKey(User, … -
Django admin foreign key field cause performance issue
I have a Question model and a Solution model. class Solution(models.Model): user = models.ForeignKey('exam.Users', on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) solution = RichTextField() In Django admin, I display a Question_text in Solution section. @admin.register(Solution) class SolutionAdmin(admin.ModelAdmin): def get_ori_q(self, obj): se = obj.question return se.question For this Question_text field, see the picture below. But I don't want to edit it, or make it selectable, for the it cost a lot of time to display massive item if I click it. How can I make it read-only and display only one item, instead of displaying all items in Question table? -
( Django ) upload file always failed
I'm trying to upload a file to server with Django, but the form.is_valid is always return Flase. Then I have output the form value as follow presented. print form in views.py <tr><th><label for="id_country">country:</label></th><td><input type="text" name="country" value="DE" required id="id_country" maxlength="200" /></td></tr> <tr><th><label for="id_email">email:</label></th><td><input type="email" name="email" value="123456789@example.com" required id="id_email" /></td></tr> <tr><th><label for="id_filetoupload">fileToUpload:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="filetoupload" required id="id_filetoupload" /></td> </tr> form.py from django import forms class UserInfo(forms.Form): country = forms.CharField(label='country', max_length=200) email = forms.EmailField(label='email') filetoupload = forms.FileField(label='fileToUpload') urls.py from django.conf.urls import url from loadfileweb.views import receiveinfo urlpatterns = [ url(r'^home/', receiveinfo), url(r'^home/submit', receiveinfo) ] views.py def receiveinfo(request): if request.method == 'POST': form = UserInfo(request.POST, request.FILES) print "form info" print form print form.is_valid() if form.is_valid(): # process the data in form.cleaned_data as required country = form.cleaned_data['country'] email = form.cleaned_data['email'] print email print "------------ get email -----------" # redirect to a new URL: return HttpResponse('/thanks/') else: print "----- form isn't valid -------" return render(request, 'home.html', {'form': form}) else: print "--------- request.method != 'POST'------------" form = UserInfo() return render(request, 'home.html', {'form': form}) home.html <form class='UserInfo' action="submit" method="post" enctype="multipart/form-data">{% csrf_token %} E-mail: <input type="email" name="email" autofocus><br> {{ form.email.errors}}<br> Country: <input list="countrycode" name="country"> {{ form.country.errors}}<br> <datalist id="countrycode"> <option value="DE"> <option value="ES"> <option value="FR"> <option value="IT"> … -
CORS error while consuming calling REST API with React
I created a restful api with django-rest-framework accessible with this URL http://192.168.33.10:8002/scenarios/ and I'm creating a React app to make calls to the api an d consume its data. I'm using fetch to make calls to the api componentWillMount: function(){ this.setState({Problemstyle: this.props.Problemstyle}) fetch('http://192.168.33.10:8002/scenarios/') .then(result=>result.json()) .then(result=> { this.steState({items:result}) }) }, when i run my app i get an error in my browser Fetch API cannot load http://192.168.33.10:8002/scenarios/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.33.10:8001' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I'm not sure on how to solve this problem as i'm just starting to use React -
Why don't we pass any argument a function defined in 'views.py' - Django
In a Django project, when we define a function in viwes.py, it's expecting a one argument (something called request argument). views.py from django.http import HttpResponse def my_homepage_view(request): return HttpResponse("<h1>This is the homepage") But in url.py, when we pass my_homepage_view in to url()function, we don't pass any argument to my_homepage_view() function. In this case, I didn't pass any argument to my_homepage_view(). But it worked fine. url.py from lern_django.views import my_homepage_view urlpatterns = [ url(r'^$', my_homepage_view) ] Please can you explain me how was that possible? -
django form "exclude" works, "fields" doesn't
This question almost seems like too much of a hassle to ask, so if I don't provide enough details, sue me. I'm using a bunch of different things in this project so to provide details on all of it would take me half the day. If there's something specific that'll help you target the solution, please ask. I have a formset view, with an incredibly complicated pipeline. In my form view, I use ModelFormsetView from django extra views. I imagine the error must be in that code somewhere, but if I look in their code it has both "exclude" and "fields" at every step and never does it leave one out. fields = ('name', 'toggle_on', ) instead of exclude = ('created', 'modified', ) It will always include "created" and "modified." If I do exclude, it always works. The django docs say to use "fields" instead of "exclude" but the docs would appear to be wrong in this case. I know there are a bunch of other variables in a pipeline like this, but since changing it from fields to exclude solves it, it's got to be something wrong with the form. -
Django application to upload videos on S3 using boto3
I am new in Django and wants to develop an application to upload video on AWS S3 using Boto3. Please anyone of you can guide me step-by-step on how to implement this? As I am new so it's little bit hard for me to understand. Earlier I tried and created one Form with form.FileField() and It returns me File Object but that fileobject I am not able to upload using boto3 as upload_fileObj method must require read implemented as a rb. Thanks in advance and waiting for guidance. -
My local django project and every action is 40 sec long. Windows issue?
So i run this on Pycharm thru toolbar. As default command is "C:\Program Files (x86)\JetBrains\PyCharm 2017.1\bin\runnerw.exe" C:\Python34\python.exe C:/Users/TwardyDziad/PycharmProjects/foresee2/manage.py runserver 8000" We use: Django==1.11 django-allauth==0.32.0 oauthlib==2.0.2 psycopg2==2.7.1 I ran it on Python 3.4.4 and 3.6.4 also on virtual envs and nothing helped So i do pstat on PyCharm (name|call count|time|owntime) <built-in method WaitForSingleObject> 1 65706 65706 <built-in method OpenKey> 6928 125 125 <built-in method stat> 2547 89 89 <built-in method loads> 458 40 40 <built-in method __build_class__> 1397 280 26 get_data 458 37 24 <built-in method CreateProcess> 1 22 22 <built-in method QueryValueEx> 1090 16 16 read_windows_registry 1 157 16 <built-in method EnumKey> 5908 14 14 <method 'read' of '_io.FileIO' objects> 458 12 12 __next 11248 13 12 _parse 528 35 11 <built-in method hasattr> 37294 30 9 Seems like win-api is the most. This same project works on other teammates right. One have win10 also Pycharm other set up it in Ubuntu. So is my system broken or smth? I need it only for development, production will be another story. Thanks -
Getting multiple Django application site to resolve by port numbers
I have a Django website where I run multiple sites. Each application has a seperate apache instance and port assigned to it. the host.py file looks like the following host_patterns = patterns('', host(r'.*domain1.*', 'domain1.urls', name='domain1'), host(r'.*domain2.*', 'domain2.urls', name='domain2'), host(r'.*domain3.*', 'domain3.urls', name='domain3'), host(r'.*domain4.*', 'domain4.urls', name='domain4'), host(r'.*domain5.*', 'domain5.urls', name='domain5'), ) for example www.domain1.com runs under an apache instance and port 8010. Id like to create some internal monitors so I can check each site on a specific server. The only way to do this is with using port numbers of the apache instance so as http://10.10.10.10:8010 but when i try to modify my site to do this I get application errors. either by adding a line for domain host(r'.*8010.*', 'domain1.urls', name='domain1'), or modifying existing line host(r'.*domain1.*|.*8010.*', 'domain1.urls', name='domain1'), not sure what I am doing wrong -
Django Admin- Limiting ForeignKey Field's choices
I've been working on my Django Project. I use custom Forms (a class called Form), and I've got a class called Restricted_Form. The point of this class is that an Admin user ("staff status" user") has the option restrict which users or groups can have access to the Forms/submit filled Forms: #....models.py: from django.contrib.auth.models import User, Group class Restricted_Form(models.Model): Form = models.ForeignKey('forms.Form', help_text='Aqui escolher um Survey, para permitir apenas a certos Utilizadores/Grupos que tenham acesso a este. Os Utilizadores individuais escolhidos poderão ver e responder, assim como todos os Utilizadores pertencentes aos Grupos que escolher.') Authorized_Users = models.ManyToManyField(User, blank=True) Authorized_Groups = models.ManyToManyField(Group, blank=True) user = models.ForeignKey(User, blank=True, null=True, related_name="restriction_owner") It is worthy to note that a "Form" itself has: user = models.ForeignKey(User, blank=True, null=True) #this is always the user who created it This idea is OK. My issue is limiting what the non-superuser admins can do. They should only be able to create Restricted_Form objects including a Form they have created themselves. In practice, when they create a Restricted_Form, only "Forms" that they have created themselves should appear as options to select, in the drop-down menu. I've searched for this here on SO and mostly found old posts about this … -
Make the chart display current year in HighChart
Chart appears like so: I want it to display current year in x-axis where the months are. Had a look at different solutions but none of them help. Please, see where i went wrong since i'm still new to this. Appreciate your help a lot! Django version: 1.10 Python version: 3.6 chartViewHigh.html {% block main %} <h1 align="center">Analysis</h1> {% block content %} <div id="container3" style="width:50%; height:400px;"></div> {% endblock %} {% block extrajs %} <script> var endpoint = '/api/chart/data/'; var labels01 = []; var defaultData01 = []; var labels02 = []; var defaultData02 = []; var labels03 = []; var defaultData03 = []; ... $.ajax({ method: "GET", url: endpoint, success: function (data) { labels01 = data.labels01; defaultData01 = data.default01; labels02 = data.labels02; defaultData02 = data.default02; labels03 = data.labels03; defaultData03 = data.default03; labels04 = data.labels04; ... setChart() }, error: function (error_data) { console.log("error"); console.log(error_data) } }); $(function () { $('#container3').highcharts({ chart: { type: 'column' }, title: { text: 'Members Registration Current Year ' }, credits: { enabled: false }, xAxis: { type:"datetime", dateTimeLabelFormats:{ year: '%Y' }, tickInterval: 1, categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] }, yAxis: { tickInterval: 1, minRange: 1, title: { … -
Hide Model Property from Django admin and set Its Value Manually
I want to hide a column from django admin and set its value from session. In simple words i want to set a property of a model from session and don't want a field in admin for that column. Can someone help me? -
Django Model ValueError: too many values to unpack
I've been trying to solve a Django circular import problem in my project, using the idea presented in a bunch of answers here on SO, like this one Instead of something like: from forms_builder.forms.models import Form #... Form = models.ForeignKey(Form) This is what I'm doing: Form = models.ForeignKey('forms_builder.forms.Form') The problem is that I'm getting this error: ValueError: too many values to unpack I'm guessing the problem stems from the 2-value forms_builder.forms. In the examples I've seen people would only have a 'simple' App name with only one value. (forms_builder is this app I'm using) How can I solve this error? -
Django social auth error logging in with two email accounts
My application must be accessed through an account like user@mydomain.com (Google managed email account) First time I launch my application I can log in normally using that account. The problem starts when I log out (django log out) and try to login with my Gmail account (This is not allowed because of my email verification pipeline) The first account is my user@mydomain.com and the second is my user@gmail.com account I have a pipeline to verify if the user email belongs to my domain Clicking on the @gmail.com account return an error from my pipeline @partial def require_mydomain_email(strategy, details, user=None, is_new=False, *args, **kwargs): if user and user.email: if '@mydomain' in user.email: return elif is_new and not details.get('email'): email = strategy.request_data().get('email') if email: details['email'] = email else: current_partial = kwargs.get('current_partial') return strategy.redirect( '/email?partial_token={0}'.format(current_partial.token) ) else: email = details.get('email') if email: if '@mydomain' in email: return else: current_partial = kwargs.get('current_partial') messages.add_message(strategy.request, messages.WARNING, 'Your email must be an @mydomain email') return strategy.redirect('/'.format(current_partial.token)) The Main problem: After trying to log in with gmail.com account doesn't matter what account I'm trying to login after, my backend always receives the @gmail data from google. Here are my pipeline settings: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', …