Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
chcp not recognized internal external in Atom command terminal for Django
I'm currently trying to learn Django with the Atom IDE. In Atom, I've installed the platformio-ide-terminal package. I then created a django environment by typing in the Atom command terminal the following: conda create --name MyDjangoEnv5 I consistently get this message after trying to my initial attempt to use Django: C:\Users\Michael> activate MyDjangoEnv5 "chcp" is not recognized as an internal or external command, operable program or batch file. "cmd" is not recognized as an internal or external command, operable program or batch file. I installed Django in the Atom command terminal conda install django and the installation went perfectly fine. I have looked up another stackoverflow link regarding this "chcp" not recognized issue, and didn't find it helpful or clear. I tried checking my path by right clicking on my PC (I'm using Windows 8, 64-bit), and clicked on properties. Right-click "This PC" > Properties > Advanced system settings > Environment Variables... In System variables I added variable name asPATH and variable value as C:\Windows\system32\cmd.exe and for User variables for Michael I added C:\Windows\system32; as PATH. I then tried in a new Atom command terminal activate MyDjangoEnv5 and still got the same "chpc" is not recognized... error again. Can anyone … -
How do I make integers optional in DRF
I have a serializer with an integer field foo = serializers.IntegerField() and I'd like that field to be optional. It seems obvious to me that foo = serializers.IntegerField(required=False) should work, but it doesn't, I get the error message: {"error":{"foo":["A valid integer is required."] I though I said that it wasn't required. I also tried adding a default, serializers.IntegerField(required=False, default=42) Am I missing something? Is this even possible? -
The button will send an email
HTML <div class="wrapper"> <div id="overlay"></div> <a href="#" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-another-button" data-url="{% url "messaging:send" request_id=object.pk %}"> <i class="material-icons">assignment_late</i> <div class='alert alert-success' id="show-message" style="display: none;"> <p> The message was sent to the client. Please wait 5 minutes <br> before sending the message again. </p> </div> </a> </div> JavaScript $(function(){ var timeout; $('.select-another-button').each(function(){ $(this).bind('click', function(e) { $(this).attr('disabled','true'); //disables the button $('#overlay').show(); //after disabling show the overlay for hover timeout = setTimeout(function(){ $(this).attr('disabled','false'); //enables after 5mins $('#overlay').hide(); //hide the overlay }, 300000); e.preventDefault(); fileBrowser(this); return false; }); }); }); $("#overlay").hover(function(){ var timeleft = Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000); $('#show-message').html("Please wait" + timeleft).show(); },function(){ $('#show-message').hide(); }); Django @staff_member_required @csrf_exempt def send(request, request_id=None): req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) if context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return HttpResponse('') I've created a button which will send an email under certain conditions. So far I know I'm struggling with setTimeout from the JS section, but it is not the point of that question. Once I click on the button and the message is send, I'd like to deactivate the button for 5 minutes and then … -
Serving sites on multiple ports with nginx
Looking for this solution for a while now and think I'm pretty close, however... So I have 5 different VMs running webpages on different ports. For brevity sake lets say 8080 to 8484. I want to have them all listen on 127.0.0.1 and their respective port. I also want nginx to serve as an https and password protected front to a landing page that will redirect the users to these internal sites. server { listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/home.crt; ssl_certificate_key /etc/nginx/ssl/home.key; ssl_dhparam /etc/nginx/ssl/dhparam.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0 ssl_session_cache shared:SSL:10m; ssl_session_tickets off; # Requires nginx >= 1.5.9 add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 101M; auth_basic "Login required"; auth_basic_user_file /etc/nginx/htpasswd; location /server1 { proxy_pass http://127.0.0.1:8080; proxy_set_header Host \$host; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; } location /server2 { proxy_pass http://127.0.0.1:8181; proxy_set_header Host \$host; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; } .... So this will prompt me for the user, pass and redirect to the appropriate page being hosted on that port, but I get an error saying disallowed host at /server1 for an invalid HTTP_HOST header as \127.0.0.1 is not valid. Is this even … -
Django Sign up form with bootstrap template
Hey guys i am learning django framework and developing a project. I read have read the docs but still i am not understanding that how to make a form with bootstrap and validate it and show the errors on the client side. I am not understand where should i place my validation code inside forms.py or views.py I have seen that some websites had done validation in the views.py and some done it in forms.py.. Completey confused how to show the form validation errors at the client side. models.py from django.db import models # Create your models here. class maintable(models.Model): user_name=models.CharField(max_length=30) user_email=models.CharField(max_length=30) user_password=models.CharField(max_length=30) class Meta: db_table="maintable" Here is my views.py def signedup(request): if request.method=="POST": mySignupForm=signup_form(request.POST) if mySignupForm.is_valid(): username=mySignupForm.cleaned_data['name'] useremail=mySignupForm.cleaned_data['email'] userpassword=mySignupForm.cleaned_data['password'] userconfirmpassword=mySignupForm.cleaned_data['confirmpassword'] main_table=maintable( user_name=username, user_email=useremail, user_password=userpassword ) main_table.save() return render(request,'home/thanks.html',{"username":username}) Here is my forms.py class signup_form(forms.Form): name=forms.CharField(max_length=30) email=forms.CharField(max_length=30) password=forms.CharField(max_length=30) confirmpassword=forms.CharField(max_length=30) Here is my signup form with bootstrap <form method="POST" action="{% url 'forms.views.signedup' %}">{% csrf_token %} <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">@</span> <input class="form-control" type="text" name="name" placeholder="Name"/> </div> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">@</span> <input class="form-control" type="email" name="email" placeholder="Email Id"/> </div> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">@</span> <input class="form-control" type="password" name="password" placeholder="Password"/> </div> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">@</span> <input class="form-control" type="password" … -
How do you add a unique field (non empty) field to an existing model in Django?
I have a model that looks like so: class FoodPreferences(models.Model): foods = models.ManyToManyField(to='Food', db_index=True, through='FoodToPreferenceMap') is_vegan = models.BooleanField(default=True) some_new_unique_field = models.CharField(max_length=64, unique=True) and now I want to add the some_new_unique_field to the model, but because it has no default value migrations would ask me for a new value. The field is supposed to be computed based on each row's foods values. How should I do approach this? is it possible to set a default value to be computed dynamically? -
Django Celery ubuntu 14.04
I'm attempting to deploy a django app on an ubuntu 14.04 server on digital ocean. I understand that celery is for asynchronous tasks. The user does something and instead of waiting for an expensive task to execute they can go to another section of the site. Celery does this by using redis or another message broker. It makes a queue and workers execute the tasks on the queue. I'm trying to use this to make api calls less invasive to user experience. As I deploy this to production I am very confused about where all of the stuff for celery 'lives'. I've seen posts saying I can do everything I want with celery through the admin page, and other posts have a supervisor file made that starts celery. When I try to make the supervisor file I get an error command at '/home/django/django_project/venv/bin/celery' is not executable. Regarding the management of celery through the admin page I'm not sure how celery workers and queues are created and managed. I would like to schedule tasks through there but am in general very confused. I would appreciate anyone clearing this up. Thank you -
Parts of javascript cannot load in Django admain page
I was using Django 1.9 to build my comment-check application, but I suddenly found parts of CSS/javascript didn't display on the Django admin page while I was on the adjustment about urls and views. enter image description here enter image description here As you can see, all admin pages except the detail content pages works well. And in the content pages, Chrome developer tool console show these messages RelatedObjectLookups.js:160 Uncaught TypeError: $ is not a function at RelatedObjectLookups.js:160 at RelatedObjectLookups.js:189 (anonymous) @RelatedObjectLookups.js:160 (anonymous) @RelatedObjectLookups.js:189 For sure, I don't want to paste the code from RelatedObjectLookups.js becasue I never edited any statements in this js file(maybe). This file's location is here by default: myapp\static\admin\js\admin I didn't get any 404 status code or other error response from the server. Most importantly, when I tried to check whether it was the specific case in this app so I opened my other django projects admin pages, this problem still persisted. Even though I reinstall the Django in virtualenv cannot solve it. It is the first time I ask question in here, also I'm not a native English speaker and just a python beginner. This task confused me for few hours and still found a … -
Django - Finding the closest objects from a set of dates
Apologies if this has been answered, I've tried to find and solve this puzzle myself but I've been unable to so far. Given I am running Django with a PostgreSQL database with the following entries (date format using datetime): [ {id: 0, date: '2017-07-10T13:00:00Z'}, {id: 1, date: '2017-07-10T18:00:00Z'}, {id: 2, date: '2017-07-11T13:00:00Z'}, {id: 3, date: '2017-07-11T18:00:00Z'}, {id: 4, date: '2017-07-12T13:00:00Z'}, {id: 5, date: '2017-07-12T18:00:00Z'} ] And I want to return the closest objects for each of my given dates: ['2011-01-01T12:00:00Z', '2017-07-20T14:00:00Z', '2017-07-12T16:00:00Z'] So my outcome would eventually end up as: { '2011-01-01T12:00:00Z': {id: 0, date: '2017-07-10T13:00:00Z'}, '2017-07-20T14:00:00Z': {id: 5, date: '2017-07-12T18:00:00Z'}, '2017-07-12T16:00:00Z': {id: 5, date: '2017-07-12T18:00:00Z'} } Is this possible in an elegant way without having to return all the objects from the DB and then using abs to find the closest date for each in regular Python? I can only solve it by querying everything from the DB, but I don't think that's the right way to go here and I want to avoid fetching everything or doing multiple calls. -
Django: What's best way to handle friends? [on hold]
I am somewhat new to Django and i'm trying to get some practice by making an app that allows users to find other friends using the app and make private group chats. The issue that i have run into is, how should I handle the way that the user adds "friends". At first I thought that I should give each user a table of friends but i read at how-to-create-one-model-table-for-each-user-on-django that this would be an inefficient method. So without giving each user his/her own table, and not using a separate package such as simple friends or Django-friendship, what would be the most efficient method to handle user "friends"? -
django modal keeps loading same data on iteration
Okay so I am trying to have a table displaying results from a query. I want the data in the table to be truncated and the user to be able to see the full data in a modal. I have tried implementing this as seen below. However, the modal is displaying the same result in every column for the first row. It seems as though once the modal takes data it won't change dynamically on iteration to load new data. Is this right? If so what is a way around this either in javascript or in my html. Please see the code below and thanks! Template code: {% if data %} {% for key, value in data %} {% if value.4 %} <td class='test'>{{ value.4 }}<a href='#' id="trigger_{{ forloop.counter }}"><img src='{% static "img/expand-icon2.png" %}' id="expand"></a> {% if methods %} {% for key2, value in methods %}{% ifequal key2 key %} <div id="classModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="classInfo" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="classModalLabel"> Triples: </h4> </div> <div class="modal-body"> <table id="classTable" class="table table-bordered"> <thead> <tr> <th style="width: 4%">#</th> <th>Subject</th> <th>Predicate</th> <th>Object</th> <tr> </thead> <tbody> {% for item in … -
django-allauth DefaultAccountAdapter clean_password() got an unexpected keyword argument 'user'
I have written my own custom account adapter using django-allauth and django 1.10, so that I can specify a regex patterns for passwords to be validated. This is a snippet of my code: class MyAccountAdapter(DefaultAccountAdapter): def clean_password(self, password): if re.match(settings.ACCOUNT_PASSWORD_REGEX, password): return password else: raise ValidationError("Password must be at least 8 characters long, contain one digit and one captalised alphabet") I have specified to use this class in my settings.py: ACCOUNT_ADAPTER = 'app.adapters.MyAccountAdapter' When I attempt to sign up (i.e. submit a filled in form), I get the following error: TypeError at /accounts/signup/ clean_password() got an unexpected keyword argument 'user' Traceback: File "/path/to/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/path/to/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/path/to/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/path/to/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/path/to/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/path/to/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/path/to/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/path/to/site-packages/allauth/account/views.py" in dispatch 205. return super(SignupView, self).dispatch(request, *args, **kwargs) File "/path/to/site-packages/allauth/account/views.py" in dispatch 74. **kwargs) File "/path/to/site-packages/allauth/account/views.py" in dispatch 183. **kwargs) File "/path/to/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/path/to/site-packages/allauth/account/views.py" in post 96. if … -
How to list all foreign keys associated with an item in Django
I am trying to build a simple listing application with Django. I am using a Language datatype and a Technology datatype which has a language foreign key. I want to display all technologies associated w/a language beneath that language. Here is my current setup: models.py from __future__ import unicode_literals from django.db import models class Language(models.Model): name = models.CharField(max_length = 32) def __str__(self): return self.name class Technology(models.Model): class Meta: verbose_name_plural = 'technologies' name = models.CharField(max_length = 32) description = models.TextField() language = models.ForeignKey(Language) def __str__(self): return self.name views.py: def skills(request): return render(request, 'personal/skills.html') urls.py: from django.conf.urls import url, include from . import views from django.views.generic import ListView from personal.models import Language, Technology urlpatterns = [ url(r'^$', views.index, name='index'), # Defining url patterns. As things stand, we have a start and an end url(r'^contact/', views.contact, name='contact'), url(r'^skills/$', ListView.as_view(queryset=Technology.objects.all(), template_name='personal/skills.html')) ] skills.html: {%extends 'personal/header.html'%} {%block content%} {%for technology in object_list%} <h3>{{technology.name}}</h3> <h5>{{technology.language}}</h5> {%endfor%} {%endblock%} I think I need to pass the skills into the template as a second queryset in the URLS file, but I am not really sure. How should I go about the handling of these related datasets to have them return and display in the way I want? -
Django access superclass method of superclass in multiple inheritance
I have the following class design for my viewsets and mixins. My problem is that when I call super().create() from SomeModelViewSet, it calls that viewset's overridden update() instead of the update() of MixinA. Is calling MixinA.create(self) the way to go? Please do alert me if this is bad design. Disclaimer: Me calling update() from create() is due to some uncommon spec mixins.py class MixinA(mixins.CreateModelMixin, mixins.UpdateModelMixin): def create(self, request, *args, left=None, right=None **kwargs): # ... self.update(request, left=left, right=right) def update(self, request, *args, left=None, right=None, **kwargs): # ... class MixinB(mixins.DestroyModelMixin): def destroy(self, request, *args, **kwargs): # ... class MixinC(mixins.ListModelMixin): def list(self, request, *args, **kwargs) # ... viewsets.py class BaseViewSet(MixinC): # ... class MyViewSet(MixinA, MixinB, BaseViewSet): pass views.py class SomeModelViewSet(MyViewSet): def create(self, request, pk=None, **kwargs): a = someObj(pk=pk) b = someObj(pk=None) return super().create(request, left = a, left = b, **kwargs) def update(self, request, first_pk=None, second_pk=None, **kwargs): a = someObj(pk=first_pk) b = someObj(pk=second_pk) return super().update(request, left=a, right=b) def destroy(self, request, first_pk=None, second_pk=None, **kwargs): lookup = {'first__pk': first_pk, 'second_pk': second_pk} return super().destroy(request, **lookup) -
Nginx hosted uwsgi django app: only accessible via curl, not by browser
I'm hosting a Django app using uwsgi and nginx. If I call curl -v my_ip:port it connects. If I direct a browser towards my_ip:port it returns a ERR_CONNECTION_REFUSED and the connection doesn't show up in the log. uWSGI: file : data_collection_project.ini [uwsgi] project = data_collection_project base = /data_nfs/data_collection_project chdir = %(base) # /%(project) home = /home/rootadmin/.virtualenvs/data_collection #plugins = python #module = data_collection_project.wsgi:application module = data_collection_project.wsgi:application master = true processes = 2 socket = %(base)/%(project).sock chmod-socket = 666 nginx: file: /etc/nginx/sites-available # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///data_nfs/data_collection_project/data_collection_project.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8433; # the domain name it will serve for server_name my_ip; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /data_nfs/data_collection_project/media; # your Django project's media files - amend as requir$ } location /static { alias /data_nfs/data_collection_project/static; # your Django project's static files - amend as requi$ } # Finally, send … -
can we create directory in view? django
I want to create / remove directories in static folder using django's view. Is it possible? Something like, when I run django's view I want to create some extra folders in static folder...then do some processing inside the folder, and remove them later -
Show telegram channel posts in website - php
i have a bot and a channel in telegram. I want to create a link of my channel photos(for show user in website) Note : i read some document about get file . I can find file path but i don't know to where should i use it(for example it is : file_0.jpg) -
Django Extensions: ForeignKeyAutocompleteTabularInline doesn't work with model inheritance?
Having defined my models as follows (example code): class Category(models.Model): description = models.CharField(...) class Product(models.Model): code = models.CharField(...) description = models.CharField(...) class Drink(Product): # drink attributes class Food(Product): # food attributes class Relation(models.Model): category = models.ForeignKey(Category) product = models.ForeignKey(Product) Using ForeignKeyAutocompleteTabularInline as an inline in a CategoryAdmin class to retrieve all kind of products (Drinks and Food) raises a NoReverseMatch exception because app_product_changelist isn't defined. Is that the expected behavior? Any workaround this? -
Sending SMS and email to 100000 members in django-mysql envrionment
I am having a real headache on how to handle this one. Basically, the application got members that are projected to reach one million at the end of the year. It relies heavily on USSD but also have email. Actually for now, I would prefer to send the SMS first. The issue is this: the members have groups based on their activities and a single member can have multiple groups. Currently, the highest number of members in a group is 17,000.00. The group can basically send SMS to those 17,000 members. The group leaders specify paramters ("All Members","Females","Age 24-28" etc) and send the SMS, which must save a copy in the database. Currently, there are 5 active groups but they will certainly increase in the future and they can all request to broadcast SMS to members at once. The phone numbers of members is kept in: class Profile(model.Models): user=models.ForeignKey(User) phone=models.CharField(max_length=13) Similarly, the app should basically scan the member profiles to send them period notifications. For now, I am following the following: Select the phone numbers of all members that satisfy the criteria Create an id for the broadcast and wait for previously stacked SMS requests to finish. Then add the … -
How to create dictionary key-values in django
I am developing server web with Django, and my model ST_Folio contains idST and idFolio, I need create a dictionary idST: idFolio1, idFolio2, ... But my problem is that I can create similar dictionary but no like I want. First: <QuerySet [<St_folio: 1st_folio>, <St_folio: 2st_folio>, <St_folio: 3st_folio>]> Second: {<ST: st1>: [<St_folio: 1st_folio>, <St_folio: 2st_folio>], <ST: st2>: [<St_folio: 3st_folio>]} I am using this method for this.. st_database = St_folio.objects.exclude(idST__isnull=True) dictionary = {k: list(g) for k, g in groupby(st_database, key=lambda q: q.idST)} I need thing like this: {<ST: st1>: [<idFolio: folio1>, <idFolio: folio20>], <ST: st2>: [<idFolio: folio1>]} Thanks!! -
Editing default fields' help_text for form in Django (1.11)
For the past couple days I have been trying to solve a strange problem with the default help_text on a form I created to handle user signups. I first noticed the issue when I saw that the html django is inserting as the default help_text is getting escaped. Screenshot of Issue Instead of displaying the <ul>, which I remind you is the default help_text that django includes for password fields, it is displaying plain text. So this is where I first noticed that must be doing something wrong. If the default form help_text is getting escaped and looking awful like that, I'm clearly making a mistake. Next I will explain what I did to try to fix this, and then will give a overview of the model, form, view, and template so you guys have something to work from. The first solution I found online was to use the Meta class, so I did in my forms.py under the class SignUpForm: that I am modifying. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): company = forms.CharField() city = forms.CharField() state = forms.CharField() zip = forms.IntegerField() address = forms.CharField() phone = forms.IntegerField() class Meta: model … -
Django Local Environment Settings
i started a new project in Django but local environment settings come from the previous project. So how can i reset local environment settings? Thank you.. -
Django Wagtail CMS File Too Large for Upload
I am using Django Wagtail CMS 1.10.1 and and am getting a file too large when trying to upload images or documents. What I don't understand is that the files are less than 1.5mB. How do I adjust the limits on permitted upload file sizes to get around this. Thank you. -
celery Flower not showing some workers?
Flower 1.0 is not showing some worker but flower 0.7 is showing the same worker as active.Strange? I can see that celery is also showing the worker as active from control stats. -
OneToOne relation and NestedSerializer issue about User model
I'm trying to do a login app including registration, authentication etc... I'm getting this error: AttributeError: Got AttributeError when attempting to get a value for field 'user' on serializer 'PictureUserSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'User' instance. Original exception text was: 'User' object has no attribute 'user'. But, when I check my admin page. The user has been registered with the right informations. I'm not feeling like this error come from nowhere and I must do something wrong. Here is my code: logginapp/models.py from django.db import models from django.contrib.auth.models import User class PictureUser(models.Model): user = models.OneToOneField(User) #OneToOne link to the Django's User Model avatar = models.ImageField(null=True, blank=True, upload_to="avatars/") def username(self, user): return user.username def password(self, user): return user.password def email(self, user): return user.email loginapp/serializer.py from django.core.validators import validate_email from django import forms from rest_framework import serializers from loginapp.models import PictureUser class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email') write_only_fields = ('password',) class PictureUserSerializer(serializers.ModelSerializer): """ Serializer to put the PictureUser model into JSON """ user = UserSerializer() class Meta: model = PictureUser fields = ('user', 'avatar') read_only_fields = ('created',) def create(self, validated_data): print (validated_data) return User.objects.create_user(validated_data['user']['username'], …