Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.9 Attach file from database to email
I have a user submit a form containing an attachment file. That file goes into my database just fine. Once the user hits submit I am trying to send an email to my company with that attachment in the email. The attachment type can be any type. Unfortunately I keep getting an error: MultiValueDictKeyError at /mysite/register/. When I send the email without the attachment, all the info from the previous page is loaded perfectly. My issue is only attaching their file to the email. I know my code is off, but here it is: views.py: def thanks_for_registering(request): profile_id = request.session.get('register_profile_id') profile = UserProfile.objects.get(id=profile_id) subject = "{0} has just registed".format(profile.company_name) from_email = 'myemail@mycompany.com' to_email = 'myotheremail@mycompany.com' the_attachment = request.FILES[profile.the_attachment].name profile_data = { 'first_name': profile.first_name, . . . 'the_attachment_name': profile.the_attachment_name } plaintext = get_template('email/email_text.txt') htmly = get_template('email/email_template.html') email_content = Context(profile_data) text_content = plaintext.render(email_content) html_content = htmly.render(email_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, "text/html") try: msg.attach(the_attachment.name, the_attachment.read(), the_attachment.content_type) except: return "Attachment error" msg.send() return render(request, 'mysite/register.html', {}) the full error message: Environment: Request Method: GET Request URL: http://localhost:8000/mysite/register/ Django Version: 1.9 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', … -
Django Form Failure
I have the following form: # coding=utf-8 class SelectTwoTeams(BootstrapForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) self.currentSelectedTeam1 = kwargs.pop('currentSelectedTeam1', None) self.currentSelectedTeam2 = kwargs.pop('currentSelectedTeam2', None) self.currentfixturematchday = kwargs.pop('currentfixturematchday', None) self.currentCampaignNo = kwargs.pop('currentCampaignNo', None) super(SelectTwoTeams, self).__init__(*args, **kwargs) cantSelectTeams = UserSelection.objects.select_related().filter(~Q(fixtureid__fixturematchday=self.currentfixturematchday),campaignno=self.currentCampaignNo) if not cantSelectTeams: queryset = StraightredTeam.objects.filter(currentteam = 1) else: queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) self.fields['team1'].queryset = queryset self.fields['team2'].queryset = queryset self.fields['team1'].initial = self.currentSelectedTeam1 self.fields['team2'].initial = self.currentSelectedTeam2 team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None, widget=forms.Select(attrs={"class":"select-format",'onchange': 'this.form.submit();'})) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None, widget=forms.Select(attrs={"class":"select-format",'onchange': 'this.form.submit();'})) def clean(self): cleaned_data = self.cleaned_data # individual field's clean methods have already been called team1 = cleaned_data.get("team1") team2 = cleaned_data.get("team2") if team1 == team2: raise forms.ValidationError("You picked the same team!") return cleaned_data If I use the following in my HTML file and choose the same two teams it correctly says "You Picked the same team!": <form action="" method="post"> {% csrf_token %} {{ form }} </form> However, if I use the following: <form action="" method="post"> {% csrf_token %} {{ form.team1 }}{{ form.team2 }} </form> I get no feedback. Nothing occurs when I choose the same two teams. Any idea as to why separating the fields stops it from working? Many thanks, Alan. -
Cannot convert {'price_total__sum': Decimal('258.00')} to Decimal
I get this error when I do a Sum of an entire column: Cannot convert {'price_total__sum': Decimal('258.00')} to Decimal here the entire project: https://github.com/pierangelo1982/djangocommerce/tree/berge def add_to_order(request): if request.method == "POST": form = AddOrderForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.published_date = timezone.now() post.tot_price = CartItem.objects.filter(user_id=request.user.id).aggregate(Sum('price_total')) post.save() cart_list = CartItem.objects.filter(user_id=request.user.id) for cart in cart_list: formOrder = AddOrderItemForm(request.POST) post_cart = formOrder.save(commit=False) post_cart.order = post post_cart.product = cart.product post_cart.composition = cart.composition post_cart.price = cart.price post_cart.quantity = cart.quantity post_cart.total = cart.price_total post_cart.price_discount = cart.price_discount post_cart.price_reserved = cart.price_reserved post_cart.save() #cart_list.delete() #cancello carrello dopo ordine return redirect('/order', pk=post.pk) else: form = AddOrderForm() return render(request, 'order-form.html', {'form': form}) My Models Order, that receive the sum value, and the form: class Order(models.Model): user = models.ForeignKey(User, null=True, blank=True, verbose_name="Utente") code = models.CharField('Codice', max_length=250, null=True, blank=True) tot_price = models.DecimalField('Prezzo', max_digits=10, decimal_places=2, blank=True, null=True) tot_discount = models.DecimalField('Totale Scontato', max_digits=10, decimal_places=2, blank=True, null=True) tot_price_reserved = models.DecimalField('Prezzo Scontato Riservato', max_digits=10, decimal_places=2, blank=True, null=True) pub_date = models.DateTimeField('date published', editable=False) inlavorazione = models.BooleanField('in lavorazione', default=False) pagato = models.BooleanField('pagato', default=False) spedito = models.BooleanField('spedito', default=False) chiuso = models.BooleanField('chiuso', default=False) def save(self, *args, **kwargs): self.pub_date = datetime.now() super(Order, self).save(*args, **kwargs) # Call the "real" save() method. def __unicode__(self): return self.pub_date.strftime('%Y-%m-%d') class Meta: verbose_name_plural = "Ordine" ordering … -
AttributeError: 'module' object has no attribute 'urls'
Python 2.7 & Django 1.10 Что я делаю не так? выдает ошибку: AttributeError: 'module' object has no attribute 'urls' main/urls.py from django.conf.urls import url, include from django.contrib import admin import article urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include(article.urls)) ] article/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.basic_one, name='basic_one') ] -
enumerating only the top level keys
This is a representation of my dictionary: { "ParentObj": { "Elements": { "one": "1", "two": "2", "three": "3" } } } From Django templates, how do I get only the "ParentObj" key, which is the top level key in this dictionary. I'm ok with getting other top level keys too but I don't want to get the sub-keys. -
Post Rendering Middleware
In my Django project, after a page is rendered, I need to do some extra processing before it is sent to out. I would think the middleware process_template_response would do it, this seems to happen right after the view has executed and before rendering. What is the best way for me to get what I need? -
getting import error following scrapy tutorial
Following a scrapy tutorial I am getting an import error. my structure is stalk |-bin |-include |-lib |-properties |-properties | |-spiders\ | |-__init__.py | |-items.py | |-pipelines.py | |-settings.py | |scrapy.cfg my items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field class PropertiesItem(Item): # Primary fields title = Field() price = Field() description = Field() address = Field() image_urls = Field() # Calculated fields images = Field() location = Field() # Housekeeping fields url = Field() project = Field() spider = Field() server = Field() date = Field() pass my basic.py # -*- coding: utf-8 -*- import scrapy from properties.items import PropertiesItem class BasicSpider(scrapy.Spider): name = "basic" allowed_domains = ["web"] start_urls = ( 'http://www.hispanicheights.com/', ) def parse(self, response): result = response.xpath('//*[@id="cap"]/a/h5/text()').extract() # self.log("title :{}".format(result)) item = PropertiesItem() item['title'] = result pass when I try to import this from properties.items import PropertiesItem the word items is highlited and PropertiesItem has red squiggly error lines under it. What am I doing wrong? Edit Im using django 1.10 and python 3.5 -
How to write views for rendering title from models
I need to show this title or description of Event on html page, but i am not getting. i am not more familiar with views, So Please help. models.py class Event(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() event_type = models.ForeignKey(EventType) tags = TagField() max_volunteer_count = models.PositiveSmallIntegerField(default=1) location_lat = models.FloatField() location_long = models.FloatField() venue_address = models.TextField() def __unicode__(self): return self.title views.py def get_event_list(request): model = Event return render_to_response('events.html', locals()) urls.py url(r'^events/get_event_list/$','events.views.get_event_list', name ='get_event_list'), events.html <h4>{{ model.title }}</h4> <h2>{{ model.description }}</h2> -
Packet loss on Docker-Celery configuration running on Azure
I have the following configuration running on Microsoft Azure (all VMs are Ubuntu servers): Server A running a docker container with django web application Server B running a RabbitMQ server Server C running a docker container with celery worker (same image as server A) Server A publishes tasks to broker B, server C is picking them up and processes them. While part of the times this configuration works as designed, tat many cases the tasks are not published successfully and are "lost in the way". This behaviour is very inconsistent, there are times when many tasks in a row are processed as planned, while in other times many of them get lost. I couldn't find any pattern in this behaviour. My investigation so far: The lost messages never reaches server B (I took network captures from both machines A and B). rabbitmqctrl list_queues verifies that there are no messages stuck in the queue tcpping on port 5672 shows stable connection A->B, without any packet-loss (done this from both host A and the docker container running on A). Following a post I've read I've tried to cancel tcp_timestamp on both A and B - problem still reproduce. I have a similar … -
WEIRD Django AuthenticationForm Behaviour
I have, all day, tried to figure this out but I can't really see where the problem is coming from. I have a Django AuthenticationForm that seems to be submitting data somehow but not getting validated. forms.py: class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'name': 'username'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'name': 'password'})) views.py: def index(request): template = 'myapp/login.html' if request.method == "POST": print request.POST #prints QueryDict with its data reg = LoginForm(request.POST or None) if reg.is_valid(): return HttpResponse('Success: Form is valid!') else: return HttpResponse('Error: Form not valid') loginform = LoginForm() context = {'loginform':LoginForm} return render(request, template, context) HTML: <form method="post" action="."> {% csrf_token %} <h2>Sign in</h2> <p class="text-danger">{{loginform.errors}}</p> {{ loginform.as_p }} <button name = "signin" type="submit" value="0">Sign in</button> </form> The print request.POST in my views.py prints QueryDict: {u'username': [u'yax'], u'csrfmiddlewaretoken': [u'r8y1PaVNjxNWypdzP MaFe1ZL7IkE1O7Hw0yRPQTSipW36z1g7X3vPS5qMMX56byj'], u'password': [u'sdfdsfsddfs'] , u'signin': [u'0']} but the reg.is_valid() keeps returning false. -
Django sessions throwing KeyError
I have a very simple code in views, something like this: def mostrarServiciosFecha(request): request.session['clientes_servicio_fecha'] = clientes_servicio_fecha And then: def generarFacturas(request): clientes_servicio_fecha = request.session['clientes_servicio_fecha'] And I keep getting this error KeyError: 'clientes_servicio_fecha' Keep in mind "clientes_servicio_fecha" is a dictionary and is well settled, I can print it with no problems in the first function, sometimes the session works (changing the name several times) but I end up getting an empty array. -
Django send_mail vs. EmailMultiAlternatives
Qualitatively speaking, which is better to use? I've run my app in localhost trying them both out. They both seem to work as quick as the other. Would there be any reason to avoid one or the other? My purpose it to send an email back to my company when someone registers. Only one email will be sent. Also, I'm not understanding adding the text_content. Is this in case the html doesnt work? I can send an email with this file being blank with no issues. -
SECRET_KEY errors with enviroment variables
I am working through the TaskBuster Django tutorial whose goal is to help in the process of setting up a good development setup for a project. When I run the command echo $SECRET_KEY In either my "Dev" environment or my "Test" environment I get the same output so I believe that my $ENVIROMENTS/bin/postactivate and predeativate variables are set up correctly. my base.py folder contains # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # Get SECRET_KEY from the virtual environment from django.core.exceptions import ImproperlyConfigured def get_env_variable(var_name): try: return os.environ[var_name] except KeyError: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg) SECRET_KEY = get_env_variable('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'bapsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bapsite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Django - problems with URLS mapping and dispatcher
Greting, I'm a beginner and have a problem. Probably that will be a tiny problem, but i can't deal with thay with myself. I'm learning a Django and I would like to build an application with the calendar and tasks, where every task has a separate link via get_absolute_url. I've created a list of activities and url link to each of them, but when I pick a one of them there is no reaction. Seriously, I even didin't receveid error message. Please, find code below. I will be greatfull for any anwers. from django.db import models from django.utils import timezone from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().order_by('hour') class Activity(models.Model): STATUS_CHOICES = ( ('30 min', '30 min'), ('1:00 h', '1:00 h'), ('1:30 h', '1:30 h'), ('2:00 h', '2:00 h'), ('2:30 h', '2:30 h'), ('3:00 h', '3:00 h'), ('3:30 h', '3:30 h'), ('4:00 h', '4:00 h'), ('4:30 h', '4:30 h'), ('5:00 h', '5:00 h'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='hour') body = models.TextField() hour = models.DateTimeField(default=timezone.now()) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = models.Manager() duration = models.CharField(max_length=10, choices=STATUS_CHOICES, default='30 min') published = PublishedManager() class Meta: ordering = ('-hour',) def __str__(self): return self.title def get_absolute_url(self): return reverse('core_tm:activity_detail', … -
request.session.session_key not set despite SESSION_SAVE_EVERY_REQUEST (Django 1.10.1)
From what I understood here session_key is the primary key of the session object. When I inspect request.session, I do find a session object, but it's primary key is not set. It seems to be unsaved. So for now I am fixing this problem by checking in every view whether request.session.session_key exists and if not, calling save(). Does anyone have an explanation to why I only seem to get my hands on unsaved session objects? -
Trying to minimize the number of trips to a database voting table
I use django 1.10.1, postgres 9.5 and redis. I have a table that store users votes and looks like: ========================== object | user | created_on ========================== where object and user are foreign keys to the id column of their own tables respectively. The problem is that in many situations, I have to list many objects in one page. If the user is logged in or authenticated, I have to check for every object whether it was voted or not (and act depending on the result, something like show vote or unvote button). So in my template I have to call such function for every object in the page. def is_obj_voted(obj_id, usr_id): return ObjVotes.objects.filter(object_id=obj_id, user_id=usr_id).exists() Since I may have tens of objects in one page, I found, using django-debug-toolbar, that the database access alone could take more than one second because I access just one row for each query and that happens in a serial way for all objects in the page. To make it worse, I use similar queries from that tables in other pages (i.e. filter using user only or object only). What I try to achieve and what I think it is the right thing to do is … -
how to create a for loop for this case in python?
maybe the title seems strange, but i'm bloqued for certain times searching how to create a for loop of this case: I have a list of lists having this format : data=[['nature', author1, author2, ...author n] ['sport', author1, author2, ....author n] .... ] I have tried this code : authors=[author1, author2, ...author n] for i in range(len(authors)): data = [['nature', function(names[i], 'nature')], ['sport', function(names[i], 'sport') ..] but unfortunately I guess it returns a result in this format : data=[['nature', author1] ['sport', author1] .... ] -
In Django, wow do I elegantgly pass the object to which an inline is connected to an inline form?
In theory, this should be pretty easy, but I think I'm making it very difficult. Maybe someone can help. I have an admin class for sites SiteAdmin, an inline SitePanelInline, and a form SitePanelInlineForm. One of the fields within the form is dependent on the site to which the inline is attached, so somehow I need to know which site I'm on from within the form. What is the simplest way to make the form aware of the site instance so it can generate the proper options? -
django email username and password
I'm implementing a contact form for one of my sites. One thing I'm not sure I understand completely is why you need EMAIL_HOST_USER and EMAIL_HOST_PASSWORD. The user would only need to provide his/her email address, so what is the EMAIL_HOST_USER referring to then and why would I need to specify an email and password? EDIT: I'm using webfaction as my mail server -
Django: Template isn't loading app_tags file. Unable to use custom filter: "Invalid Filter"
I have the following folder structure: myProject | myapp | templatetags | __init__.py | app_tags.py The app_tags.py file: from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter(is_safe=False) @stringfilter def upper2(value): """Converts a string into all uppercase.""" return value.upper() The test.html template: {% load app_tags % } <div>Test Word: {{ test_word }}</div> <div>Test Word: {{ test_word|upper2 }}</div> If I use the {{ test_word|upper2 }} I get an Invalid filter: 'upper2' error. If I don't try to use the upper2 filter, the {% load app_tags % } doesn't appear to be loading. -
Is it possible to show a link in Django to admins only?
is it possible to test in Django if the logged in user is an admin? And just in this case to show a link normal users can't see? Thanks Croghs -
adding a list of menu items in a django session
I have the user menu in an object list, and I want to put it into the django sesion. I've trying but django tells me 'list' object has no attribute '_meta' actually this is the object that represents a item in the menu class MenuItem(object): def __init__(self, id, name, link, items=None): self.id = id self.name = name self.link = link self.items = items and in a function I append MenuItems in a list. menu = [] menu.append(MenuItem(1, "hi", "some_link")) finally in the view I try to put the menu in session. request.session['menu'] = menu And in this part is when django throws a 'list' object has no attribute '_meta' error. -
Target WSGI script '../wsgi.py' cannot be loaded as Python module
I'm deploying a django project and getting that 500 error (see Server log error). Where am I doing wrong? some notes: centOS mod_wsgi installed same python and django version in both develop and deploy environement using virtualenv in deploy environement Server log error [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] SyntaxError: invalid syntax [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] mod_wsgi (pid=6570): Target WSGI script '/new_esmart/esmart2/esmart2/wsgi.py' cannot be loaded as Python module., referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] mod_wsgi (pid=6570): Exception occurred processing WSGI script '/new_esmart/esmart2/esmart2/wsgi.py'., referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] Traceback (most recent call last):, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] File "/new_esmart/esmart2/esmart2/wsgi.py", line 13, in <module>, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] import django.core.handlers.wsgi, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] File "/new_esmart/esmart_env/lib/python2.7/site-packages/django/__init__.py", line 1, in <module>, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] from django.utils.version import get_version, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] File "/new_esmart/esmart_env/lib/python2.7/site-packages/django/utils/version.py", line 7, in <module>, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 17:07:54 2016] [error] [client 192.168.30.93] from django.utils.lru_cache import lru_cache, referer: http://192.168.30.17/logistics/alarms/ [Wed Sep 21 … -
missing text in xml generation django
When I print my xml here with in this method is fine. I get what I expected. But when I use return the root, I don't see the texts. I just see the tags? Is this something I am doing in creating the text or is there something else I am overlooking? def xml_generation(pretty_print=False): root = etree.Element('read') node = etree.SubElement(root, 'test') value = etree.SubElement(node, 'value') for dict in Address.objects.values('address'): value.text = dict['address'] root.append(node) root_range = etree.Element('ranges') ip_range = etree.SubElement(root_range, 'range') for range_dict in Address.objects.values('range'): ip_range.text = range_dict['range'] root.append(root_range) print 'whole xml', etree.tostring( root, encoding=unicode, pretty_print=pretty_print) return root -
sys.path.append, how to resolve name collisions when you cannot modify modules
I'm trying to append to my PYTHONPATH the location of two Django modules (version 1.4) to use their ORM models. Here is the code: sys.path.append('/path/project1') sys.path.append('/path/project2') When I try to set up the Django Enviroment as follows: import settings setup_environ(settings) Only settings of project1 are loaded. I think the problem is that both models contains a file called settings.py respectively, therefore, names collide. I cannot modify modules. How can I add both modules settings to the Django Enviroment?