Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named PIL and No module named Image
I'm using nginx+uwsgi+django for my site on virtual server. Also use sorl-thumbnail. In this string: th = get_thumbnail(p.photo, '445x300', crop='center', quality=99) I get this errors: Traceback (most recent call last): File "/home/nafuser/nafVenv/lib/python3.5/site- packages/sorl/thumbnail/engines/pil_engine.py", line 8, in <module> from PIL import Image, ImageFile, ImageDraw, ImageFilter ImportError: No module named 'PIL' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/nafuser/nafVenv/lib/python3.5/site-packages/sorl/thumbnail/helpers.py", line 66, in get_module_class mod = import_module(mod_name) File "/home/nafuser/nafVenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/nafuser/nafVenv/lib/python3.5/site-packages/sorl/thumbnail/engines/pil_engine.py", line 10, in <module> import Image ImportError: No module named 'Image' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/nafuser/nafVenv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/nafuser/nafVenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/nafuser/nafVenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/nafuser/nafVenv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./portfolio/views.py", line 49, in portfolio th = get_thumbnail(p.photo, '445x300', … -
Django how to change bounds value of IntegerRangeField
I have model with IntegerRangeField in it, which returns data as, for example, NumericRange(1992, 1997, '[)') after adding objects to db. I need second option of range to be also included in it, so the bounds sdhould be like '[]'. I was looking for the solution in the psycopg2 documentation, but didnt find answer unfortunatelly. Please help! Thanks in advance. My current models.py from django.contrib.postgres.fields import IntegerRangeField from django.contrib.postgres.validators import RangeMinValueValidator, RangeMaxValueValidator from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from datetime import datetime class Bancnote(models.Model): validators_errors = {'par_length': 'Змініть номінал на коректний'} Dollar= 'Dollar' Euro= 'Euro' TYPE_CHOICES = ( (Dollar, 'Dollar'), (Euro, 'Euro') ) type = models.CharField(max_length=11, choices=TYPE_CHOICES, default=HRYVNA) par = models.PositiveIntegerField() year = IntegerRangeField() size = models.CharField(max_length=7) sign = models.TextField(max_length=250) desc = models.TextField(max_length=500) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) + ' ' + self.type + ' ' + str(self.year.lower) + '-' + str(self.year.upper) -
ProtocolError and ConnectionResetError when Downloading Django with Pip
I am trying to download Django using pip in Powershell. Every time I type pip install django I get this from Powershell: Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connectio n aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, N one))': /simple/django/ Operation cancelled by user This is also the case for other things I try to download using pip i.e virtualenv Anyone know how to fix this and successfully download django? I am using windows 8. -
use django model to get db information from json request
I'm using Django 1.9.6. I have a simplified User model which corresponds to the data in the database: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(_('active'), default=False,) and I would like to the user information (is_active) from the email. My simplified User view is as follows: def settings(self, request, **kwargs): self.method_check(request, ['post']) data = self.deserialize( request, request.body, format=request.META.get( 'CONTENT_TYPE', 'application/json; charset=UTF-8' ) ) as_user = request.as_user if as_user: return self.create_response(request, { 'success': True, 'is_active': as_user.is_active, }) return self.create_response(request, { 'success': False, }) And the request body is a json that looks like: { "asUser": "user_email@company.com" } I'm not sure exactly what to do where I currently have the line: as_user = request.as_user to get the other information about the user in the model class. -
Django & Mongo ORM mapping
I have a Django project with a MongoDB, connecting through pymongo. I've looked into several ORM(-like) layers, but none of them seem well maintained or supporting the Django 1.8 (mongo-engine only supports Django 1.5, mongokit is no longer maintained, and the other libraries seem to have no real community behind them). So I think I'll be just using pymongo, which means that there is quite some things I'll need to implement myself, for example validation (checking that every document inserted in a collection has the required fields and field types). How would I go about this? Are there any example projects that I can take a look at? I found this project which connects from Django directly to Mongo, but there is not much structure in it. -
Django 1.11 TypeError context must be a dict rather than Context
Just received the Sentry error TypeError context must be a dict rather than Context. on one of my forms. I know it has something to do with Django 1.11, but I am not sure what to change to fix it. Offending line message = get_template('email_forms/direct_donation_form_email.html').render(Context(ctx)) Entire View def donation_application(request): if request.method == 'POST': form = DirectDonationForm(data=request.POST) if form.is_valid(): stripe.api_key = settings.STRIPE_SECRET_KEY name = request.POST.get('name', '') address = request.POST.get('address', '') city = request.POST.get('city', '') state = request.POST.get('state', '') zip = request.POST.get('zip', '') phone_number = request.POST.get('phone_number', '') support = request.POST.get('support', '') agree = request.POST.get('agree', '') email_address = request.POST.get('email_address', '') number = request.POST.get('number', '') cvc = request.POST.get('cvc', '') exp = request.POST.get('exp', '') # token = form.cleaned_data['stripe_token'], # exp_m = int(request.POST.get('exp_month', '')) # exp_y = int(request.POST.get('exp_year', '')) exp_month = exp[0:2] exp_year = exp[5:9] subject = 'New Donation' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = ['deniselarkins@/////\\\\\.com', 'charles@/////\\\\\.net', 'marcmunic@/////\\\\\.com', ] token = stripe.Token.create( card={ 'number': number, 'exp_month': exp_month, 'exp_year': exp_year, 'cvc': cvc }, ) customer = stripe.Customer.create( email=email_address, source=token, ) total_support = decimal.Decimal(support) / 100 total_charge = decimal.Decimal(int(support)) / 100 # Charge the user's card: charge = stripe.Charge.create( amount=total_charge, currency='usd', description='Donation', customer=customer.id ) ctx = { 'name': name, 'address': address, 'city': city, 'state': state, 'zip': zip, 'phone_number': phone_number, … -
Pil to Django ImageField
I try to create an image from an url and save it in my django model. If the first part works fine, I do not know how to associate the generated file to my object. This is my function to generate the image file: def get_remote_image(image_url, merchant_product_path): im = None name = '' r = requests.get(image_url, stream=True) if r.status_code == 200: name = urlparse(image_url).path.split('/')[-1] full_path = os.path.join(settings.MEDIA_ROOT, merchant_product_path) if not os.path.exists(full_path): os.makedirs(full_path) im = Image.open(r.raw) if im.mode != "RGB": im = im.convert("RGB") im.thumbnail((500, 500), Image.ANTIALIAS) im.save(full_path + name, 'JPEG') return {'im': im, 'name': name} And now, the part to associate this file to my object: i = get_remote_image(row['pict'], m.get_products_media_path()) obj, created = ProductLine.objects.update_or_create( ... ... ... ) if i['im'] is not None: try: obj.main_picture.save( i['name'], ContentFile(i['im']), save=True) except TypeError: continue This code works but unfortunately, mu pictures are created in the correct folder, objects are created/update but each one has no picture file :( Can someone tell me what's wrong ? -
Django Hierarchical Many-to-Many model filtration and representation (self-referencing)
I'm facing a really weird problem here so here it goes. First of all the stack I'm using - Django and Django Rest Framework What I'm trying to achieve - allow the user to generate Label objects which contain some information and can have multiple children and multiple parents. The nesting depth should be N-level. So one can have the following structure: Fruit Cherry Kiwi Red Cherry Bag As you can see Cherry can be both labeled as Red and Fruit I realize this can be implemented using a Many to Many structure. I've implemented the following: class Label(models.Model): name = models.CharField(max_length=255, null=False) label_relation = models.ManyToManyField('self', related_name='sublabels', blank=True, db_index=True) visible = models.BooleanField(default=True) index = models.PositiveIntegerField(default=0) label_type = models.ForeignKey('LabelType', default=1) class Meta: verbose_name_plural = 'labels' def __unicode__(self): return self.name class LabelParent(models.Model): parent = models.ForeignKey(Label, related_name='child') child = models.ForeignKey(Label, related_name='parent') So far so good - but now I wish to actually grab and return the data in a structure so that one can navigate the Label tree. And this is where things get messy pretty quick! So what I have as data in Label table: 1 Fruit 2 Red 3 Cherry 4 Kiwi 5 Bag And in my LabelParent table we'd have … -
Send POST data in email body - Django
I would like to send my post data in the body of an email. I would like to do something like this, but the body dict is obviously not the right format (this returns the error 'dict' object has no attribute 'splitlines'). What is the best practice for accomplishing this? from django.core.mail import EmailMessage def send_mail(request): body = [ 'name': request.POST['name'], 'phone': request.POST['phone'], 'email': request.POST['email'], 'appointment prefs': request.POST['appt'], 'message': request.POST['message'], ] email = EmailMessage( 'Website Inquiry', body, to=['myemail@gmail.com'] ) email.send() -
Reset form Django with instance
I create page to update user auth username. But in front end, if exist username django show erros (ok) but change request.user instance. So my username on menu change and input too. I need refresh page to back to normal. form_profile = UserProfileForm(request.POST or None, instance = UserProfile.objects.get(user = request.user)) form_user = UserForm(request.POST or None, instance = request.user ) if form_profile.is_valid() and form_user.is_valid(): form_profile.save() form_user.save() template = loader.get_template('users/user_edit.html') return HttpResponse(template.render({"form_profile":form_profile, "form_user": form_user}, request)) I can't reset form with form_profile = UserProfileForm() because is user edit page. I need "reset" form with actual informations. Screenshot -
Django-Celery Database Access
django-celery-beat running so far ... tasks get queued and worker is executing simple tasks :) now I would like to have my celery task to do a query towards the django database (to get a list of IP addresses for which I want to check reachability). can i use the django 'helper code' to do the query or do I need to make a 'raw' connection from celery to sqlite/mysql? thanks for any help on this /pat celery.py # http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals import os from celery import Celery #from celery import shared_task from django.conf import settings #settings.configure() #from portal import models #logger = logging.getLogger(__name__) #from portal.models import location # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sc_custportal.settings') app = Celery('sc_custportal') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') #app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) queryset = location.objects.all() # response = os.system("ping -c 1 8.8.8.8") # if response == 0: # print("up!") error: [2017-05-04 14:55:09,962: … -
Send an email in clicking on a button
This line here <a href="{{ object.request.send_contract_through_fax_services }}" class="btn pull-right {{ object.state|request_state_color }} darken-2 " data-turbolinks="false">{%trans "Fax contract" %}</a> gives me the following button. class CustomerRequestUpdateView(RequestUpdateView): template_name = 'loanwolf/customers/request.html' url_namespace = 'customers' subject = 'The contract of %s' % self.customer.email_user contact_message = 'This is just a test for later on during this project' from_email = settings.EMAIL_HOST_USER to_email = [from_email, ] send_mail_mtd = send_mail( subject, contact_message, from_email, to_email, fail_silently=False, ) return render(request, 'loanwolf/customers/request.html', {'send_mail': send_mail_mtd}) #render_to_pdf()? Here is one of the Django classes from the file loanwolf/24h/customers/views.py. I would like in clicking on the button to execute the method send_fax. I am a very new user of Django. I would like your help for doing such thing. Could anyone have time to show me what a good practice for that? P.S. Please let me know if the question is unclear. -
Masking password in Django
I am new to python and Django framework and I created a login form which works well but only thing is that I am not able to mask the password while it's being entered. Views.py class LoginFormView(FormView): template_name = 'Login/login-page.html' form_class = AuthenticationForm def form_valid(self, form): login(self.request, form.get_user()) return redirect('personal:index') Login/login-page.html {% block content %} <form class="form-horizontal" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{field.html_name}}</label> <div class="col-sm-5"> <input class="form-control" id="{{ field.id_for_label }}" name="{{ field.html_name }}" /> </div> </div> {{ field.errors }} {% endfor %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success "> <span class="glyphicon glyphicon-log-in" aria-hidden="true"></span> Sign in </button> </div> </div> </form> {% endblock %} Whenever I try to add the following code in views.py password = forms.CharField(widget=PasswordInput) I has no effect and if I try the same with form_class instead of forms it doesnt work as type object 'AuthenticationForm' has no attribute 'CharField' Also in the login-page.html I have used the input tag whose type by default is set to text is there a way to change it to password ? As I have looped on fields in the form. Kindly let me know where I … -
social_django, redirect_uri is incorrect, vk backend
After migration from python-social-auth to split social according to this file I get 401 error (DEBUG=True) when somebody want to sign in using VK backend. 401 Client Error: Unauthorized for url: https://oauth.vk.com/access_token Exception Location: /usr/local/lib/python3.5/dist-packages/requests/models.py in raise_for_status, line 844 For Debug=FALSE I get: redirect_uri is incorrect, check application redirect uri in the settings page What I have tried to far: I have tried to reset VK app keys and change them in settings. Also I have checked the redirect URI's in VK app and they are the same as in the request. I think the problem is not with VK app setup but most probably in missing settings inside of split social Django app. Any ideas are welcome! -
Django 1.11 - It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
I know there was such a question, but it did not work for me well. I get a message from the console when I do "migrate". How to deal with this error? I would like someone to tell me tpo step by step. I would be very grateful. I am using for virtualenv python 3.4 and powershell. -
Get access to model without related_name
I have model Calendar: class Calendar(models.Model): name = models.CharField(_('Name'), max_length=50) active = models.BooleanField(default=True) Here is model with related_name: class Base(models.Model): calendar = models.ForeignKey(Calendar, related_name='base') code = models.CharField(_('Code'), max_length=2, default='DE') default = models.BooleanField(default=False) Here is no problem because I can get access to calendar via: base_ids = self.calendar.base.values_list('id', flat=True) But I have another model without related_name: class Post(models.Model): calendar = models.ForeignKey(Calendar) pub_date = models.DateTimeField(blank=True, null=True) I tried with: post_id = self.calendar_set.themes.values_list('id', flat=True) but it's no working. -
Django template how to remove repeated values?
Is there a way to say to Django to hide/remove (show a blank space) for fields that got same values as previous row? i.e.: if now is equal for differents Articles can it be show only for the first of the group? from django.views.generic.list import ListView from django.utils import timezone from articles.models import Article class ArticleListView(ListView): model = Article def get_context_data(self, **kwargs): context = super(ArticleListView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context <h1>Articles</h1> <ul> {% for article in object_list %} <li>{{ article.pub_date|date }} - {{ article.headline }}</li> {% empty %} <li>No articles yet.</li> {% endfor %} </ul> Article - now a - 2017-01-01 b - c - 2017-01-02 d - Is this possible from view or directly in template? -
Building Payment System(Digital Wallet) for cryptocurrencies
So I want to make a digital wallet application for multiple cryptocurrencies(such as bitcoins, litecoins), that can handle payments between clients. I just read about how bit-coins works, but because it's a P2P network and I'm not getting the idea about: how I'll make payments between clients how I'll broadcast confirmation to bit-coin blockchain how I'll generate a unique address for the user, etc... I'm working with python and Django framework. So is there any library/API that can help me to access bitcoin protocol. -
in django change data at template via jquery
i'm beginner in django and python. i can't solve this problem. def post_list(request): if request.is_ajax(): posts = Post.objects.filter(user_id=1) else: posts = Post.objects.filter(user_id=3) post_list = posts[:20] return render(request, '...html', {'post_list': post_list}) here is script; script's alert works but post_list doesn't change $(document).ready(function () { $('#some).change(function () { var some= $('#some').val(); $.ajax({ url: '', type: 'GET', data: { 'user_id': some, }, datatype: 'json', success: function (data) { alert('work'); }, error: function (jqXHR, textStatus, errorThrown) { alert('don't work'); } }); }); }); url(r'^$', post_list, name='post_list'), thanks.. -
Is there a security hole in using {{ request.META.HTTP_HOST }} in templates?
In a related question on using the hostname in a django template, the comments discuss the possible security risks of relying on information supplied for that purpose. They advice against using request.META.HTTP_HOST. What is the security risk? For instance, can {% if request.META.HTTP_HOST != 'localhost:8000' %} safely be used to exclude analytics modules from tracking the development server (if ran on port 8000 of course)? What is the risk of relying on request.META data? -
Render 'send_fax' to a template
I am very new user of Django. I would like to send an email (for fax) in clicking on a button. So I have created the method send_fax in the view CustomerRequestUpdateView. I am a bit confusing here. Does this method have to use a POST request? How could I render 'send_fax' to my template? I would like that method could be implemented in the class directly. class CustomerRequestUpdateView(RequestUpdateView): template_name = 'loanwolf/customers/request.html' url_namespace = 'customers' def send_fax(self): subject = 'The contract of %s' % self.customer.email_user contact_message = 'This is just a test for later on during this project' from_email = settings.EMAIL_HOST_USER to_email = [from_email, ] send_mail( subject, contact_message, from_email, to_email, fail_silently=False, ) return #render(request, template_name, context) render_to_pdf() I thought I could use render_to_response() or just render(), but my method use self, not request. Could anyone be able to help me here? Thanks in advance! -
How to execute django signal async
I have registered a post_save receiver with user model, How to execute that receiver async from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender='User') def handle_save(sender, **kwargs): if kwargs['created']: print "here i want to do some time consuming task like, send otp and welcome mail message, how to execute it async?" Right now when i save user model receiver gets executed in sync with request. -
Django 1.10 & Socket.IO with Python 3
I'm trying to find some "django-socketio" repo to use in my project. I using django 1.10 and python3. I really searched but I do not found working examples with python3. My poor workaround I started node project and put socket.io inside route In my django view I send returning data to node route with my django session I manage session coming from django inside my node and emit inside route to client. This work but I can't believe this is a good solution.. Anyone have other ideas? Or working examples with python3 and socketio? Thanks! -
How do I use 'through' in a Django ManytoMany relationship?
I've read the docs, but there is one thing that isn't clear in using 'through' in a ManyToMany relationship. Suppose I have a 'Convention' model and a 'Persona' model. 'Conventions' are collections of 'Persona'. 'Persona' is a representation of a type of person. A varying number of 'Persona' may join a 'Convention' -- and that's what I need to capture. How do I say Convention A is made up of X number of Persona M, and Y number of Persona N? While a Persona represents a type of Person, it does not give me a count of the number of 'Persona M' attending a Convention? That's the extra data that I need to capture in the intermediate model. That is, when setting up my models, should 'Convention' have a ManytoMany relationship to a table called 'ConventionPersonas' that has a count, a FK to Convention, and a FK to Groups? -or- Should I have a 'Convention' model that has a ManyToMany relationship with 'Persona' through 'ConventionPersona' -- and will that still allow a 'Persona' to be in many different 'Conventions'? -
Compare data from django models and store value in a variable which will be processed further
So I have a django model class example(models.Model): name = models.Charfield(max_length=100) address = models.Charfiled(max_length=100) so now I have to do is compare the name and if the name are similar than the address must be stored in a variable which will be processed further. say name is ron so whenever there will be name ron address must be stored to a single variable for that instance and processed further. So now I want to know how to do the comparison of the model instances.