Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Logging all debug info for one particular app?
I setup logging and it's working great. What I want to do now is log all debug info for one particular app called 'my app' in addition to the other logs and am not sure how to achieve this. Working set up as it is now: LOGGING = { 'version': 1, 'disable_existing_loggers': False, # 'formatters': { 'default': { 'format': '\n%(levelname)s - %(asctime)s\n%(message)s\n' }, }, # 'handlers': { # 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, }, # 'debug_log': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/django/debug.log', 'maxBytes': 1024*1024*5, 'backupCount': 5, 'formatter': 'default', }, # 'error_log': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/django/error.log', 'maxBytes': 1024*1024*5, 'backupCount': 5, 'formatter': 'default', }, }, # 'loggers': { '': { 'handlers': ['mail_admins', 'error_log',], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['debug_log',], 'level': 'DEBUG', 'propagate': True, }, } } I'd like to set up DEBUG logging that captures everything for the one particular app. I add the following handler to LOGGING: 'app_log': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/django/app.log', 'maxBytes': 1024*1024*5, 'backupCount': 5, 'formatter': 'default', }, And the following logger: 'my_app': { 'handlers': ['app_log',], 'level': 'DEBUG', 'propagate': True, }, Add the following to my_app.views: import logging logger = logging.getLogger(__name__) And here's where I'm not sure … -
Django Multiple Forms on Class Based View
I am trying to show multiple forms at a single template using class based views. My goal is not only to show the forms, but to validate them and save to the database using a single "Submit" button. I have followed the answer of the following topic: Django: Can class-based views accept two forms at a time? For that I used the code from this link: https://gist.github.com/jamesbrobb/748c47f46b9bd224b07f Showing the two different forms at a single template following the first link answer was no problem at all, but, this only took me half of the way, since I am not able to validate and save the forms data with a single submit button. I am shure that the code provided on Link 2 is able to do what I am wanting, but I could not figure it out how. Could anybody give it a help or an example usage of the multi-form-processing on the code provided? -
In Django 1.10 include built-in password change form in template and control redirect
my question is a bit similar to what was asked here: How to implement password change form in Django 1.9 I try to create a profiles page for my users in Django where in addition to changing the password the user can also unsubscribe from the mailings list etc. In addition, after changing the password I want to redirect to the same page and not the changed_password_done template. I am new to Django and want to do things Django conform. My solution works but I want to be as conform as possible. What I did now is creating a class based view like this: from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm class EditProfile(LoginRequiredMixin, View): template_name = "profile.html" title = "Edit profile" def get(self, request, *args, **kwargs): form = PasswordChangeForm(user=request.user) return render(request, self.template_name, {'title': self.title, 'form': form}) def post(self, request, *args, **kwargs): form = PasswordChangeForm(user=request.user, data=request.POST) context = { 'title': self.title, 'form': form } if form.is_valid(): form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(request, form.user) context.update({'updated': True}) return render(request, self.template_name, context) I did not add the other … -
Can't get all comments to reload without page refresh after comment submitted thourgh ajax
I have been trying to come up with a scheme where the comments sections refreshes in a template when a user posts comments with the comment that was just posted being included. The page must not be refreshed. Sorry for indentation. template - {% extends "home/header.html" %} {% block content %} {% if request.user.is_authenticated %} <form> {% csrf_token %} <p>Comment: </p><input type="text" name="fname" id="posted_comment"> <input type="hidden" class='meme_char_id' meme_char_id={{meme.meme_char_id}}> <input type="submit" id ="btnSubmit" name="submit" value="Post"> </form> <!-- displaying comments here --> <div class="box" id="comments_div"> <h3 class="h4">{{comment_count}} comments </h4> <ul class="list-group"> {% for comment in all_comments %} <h5>{{ comment.commentby.username }} : </h5> <li class="list-group-item list-group-item-success">{{ comment.comment_text }}</li> {% endfor %} </ul> </div> {% endif %} {% endblock %} Now, my JS file is - $(document).ready(function() { $('#btnSubmit').click(function(e) { e.preventDefault(); var data = new FormData(); var comment = $('#posted_comment').val() var meme_char_id = $(".meme_char_id").attr('meme_char_id') data.append('comment', comment); data.append('meme_char_id', meme_char_id); $.ajax({ type: 'POST', url: '<mydomain>/comment/', data: data, processData: false, contentType: false, success: function(reply) { $(".comments_div").html(reply) } }) }); }); And finally my view is - def comment(request): if request.is_ajax(): comment = request.POST['comment'] meme_char_id = request.POST['meme_char_id'] this_meme = Memes.objects.get(meme_char_id=meme_char_id) print "comment - ", comment, " meme_char_id - ", meme_char_id new_comment = Comments(comment_text=comment, meme_id=this_meme.meme_id, commentby_id=request.user.id) new_comment.save() all_comments = … -
How to create a staff-dynamic in a Django project
I have a Django project related to a company, and it'll have a section called "News and Events", which will have "News", "Photo Gallery", "Event Calendar" and "Newsletter" as sub-sections.. My idea is to: -Make "News" a blog -Make "Events Calendar" something like Google Calendar(showing month, then can 'zoom' into a day -"Newsletter" page where you put your email and starts receiving the newsletter of the company So far, so good, but here's the real problem: How to make this a staff-friendly environment? The company's marketing team will be the ones to post in this page, and I don't find anywhere something on how to do this in a django project(in Wordpress I found some topics, but couldn't apply in Django).. . So I need to create a page for the staff to edit? Know a good tutorial of a complete blog in Django? I followed a few that I found but it's just for the basic idea of a blog.. Anyway, I know that this is not the ideal post here, but I did some research and came out empty... If this is again't a rule of StackOverflow, please tell that I'll delete the post. Thanks. -
Django - unsupported operand type(s) for |: 'NoneType' and 'unicode'
I am trying to run the following code in django, which gets the initial, years, rate value from a get request, I want to send back "Please input all three fields" but i don't understand what the error is? def submit(request): P = request.GET.get('initial') Y = request.GET.get('years') R = request.GET.get('rate') if P is None | Y is None | R is None: return render(request, 'home/home.html', { 'error_message': "Please input all three fields" }) else: return render(request, 'home/home.html') the error im getting is: unsupported operand type(s) for |: 'NoneType' and 'unicode' -
Custom API function
I'm using Django Rest Framework and Angular to build an app. I have created Serializers and ModelViewSet classes for my models that I want to be accessed in the front-end by Angular. It all works fine at the moment but I would like to have functionality beyond basic operations. Right now, I can only perform CRUD queries from my front-end service. But, I would like to create a functions that would 'get most recent' or something that is more specific. Preferably, I would like to have the back-end model communicate with its corresponding Angular resource. Thanks in advance! -
django update comments section in template after user posts a comment, without reloading entire page?
I am sort of new to Django. I have been picking things up quick and was making good progress until I stumbled on this : My issue - I have been trying to come up with a scheme where the comments sections refreshes in a template when a user posts comments with the commented that was just posted being included. The page must not be refreshed. Template looks like this - part 1 - <some article/photo> part 2 - <form for comment> part 3 - <all comments on the article/photo> I am really sorry I can't post any code due to copyright issues. But I am pretty sure a tonne of people have done this here/ are doing this on daily basis. Please be generous and explain to a newbie how advanced users seem to accomplish this without a trouble. Thanks! -
Creating an API using Django-Rest-Framework with join tables
I have the following MySQL tables: -Make -Model -Styles Make/Model has the following fields: id, name These two tables (and all the other tables) are connected by a styles table which has the following fields: id, make_id (foreign key), model_id (foreign key) In other words, Styles is the parent table that contains an ID for Make and Model which connects the two. How do I go about making a relationship with DRF to give me the expected output: "makes": [{ "id": 1, "name": "Acura", "models": [{ "id": "Acura_ILX", "name": "ILX", "styles": [{ "id": "1" "name": "Sport" }] }, { "id": "Acura_ILX_Hybrid", "name": "ILX Hybrid", "styles": [{ "id": "1" "name": "Sport" }] }, { "id": "Acura_MDX", "name": "MDX", "styles": [{ "id": "1" "name": "Sport" }] }] -
How to use Django's DetailView (or some built-in view class) for a home page?
I'm building an app in Django and I would like to set up a home page for authenticated users. I thought it was best to use de built-in generic.DetailView for this, given that the details I want to show in the page are those of the identified user. The thing is, this class needs to receive the id of the target entity through the URL as a decimal pk argument. However, the information about the entity, is in request.user, and I would like to avoid repeating that information so as not to show my user ids in the urls. I would imagine that getting the request within the get_object method would do the trick, but it does not take arguments. Is this possible? Is this a good idea? Are there any alternatives that I may be missing? -
Error in django poll tutorial
I just started with Django, and I'm following https://docs.djangoproject.com/en/1.10/intro/tutorial02/. I am recieving error at the shell when I run Question.objects.all () in the shell. I ran dir (Question) as well and it said it did not exist, but I know it does. Remigrated the tables/database since I edited models.py several times and it did not pick up any changes. I also added the unicode method but that did not solve it.Thanks in advance for your help. Here is my models.py from __future__ import unicode_literals from django.db import models # Create your models here class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.Question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=8) def __unicode__(self): return self.Choice -
PyCharm issue with runserver command
I have a script, part of a Django app, that makes thumbnails from pdfs. It runs fine if I do ./manage.py runserver from the command line, but if I run from PyCharm, it breaks. When I step through the code, the problem is that the code used to open the blob always returns an empty wand.image object. It's the right class (wand.image) but it's an empty one. The object I pass it is a pdf, but the blob conversion, which produces no error at all, is empty. The error occurs in the next line (single_image = all_pages.sequence[0]) because all_pages is empty, so the index is out of range. Again, if I launch the server from the command line, it works, but if I launch from PyCharm, it breaks. Here's the code I'm running: from wand.image import Image as WandImage from wand.color import Color def convert_to_thumb(pdf_path, slug): with open(pdf_path) as f: image_binary = f.read() all_pages = WandImage(blob=image_binary) #<-- Here image_binary is a pdf single_image = all_pages.sequence[0] #<-- BOOM! all_pages is a wand.image, but it's empty. Gives an Index error with WandImage(single_image) as i: i.format = 'png' i.background_color = Color('white') i.alpha_channel = 'remove' i.transform(resize='x100') save_name = slug + '_pdf_preview.png' i.save(filename='/foo/bar/' + save_name) … -
Django - is not a registered namespace
I am trying to process a form in django/python using the following code. home.html: <form action="{% url 'home:submit' %}"method='post'> views.py: def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) urls.py: url(r'^submit/$', views.submit, name='submit'), when i try to run it in a browser i get the error: NoReverseMatch at /home/ u'home' is not a registered namespace and also i get that there is an error in the form? -
Need to change a username field from CharField to ForeignKey
I'm having trouble transitioning from a Charfield() to a ForeignKey() field. My code below shows how my current CharField() is being used to assist in an ajax call. It currently works by clicking on a username, which gets the HTML of that username clicked and then can .get() any profile by searching the CharField() like this profile = Profile.objects.get(username=username_clicked). By the way, the HTML from that username clicked is from another Charfield(), author, which is a field in my comment model for when someone makes a comment. So the ajax call opens up a small profile box with a few details of the user clicked. Here's my code: profile model class Profile(models.Model): username = models.CharField(max_length=32, default='AnonymousUser') age = models.IntegerField(default=0) points = models.IntegerField(default=0) def __str__(self): return self.username js $('a.username').on('click', function() { var username = $(this).html(); var url = "/raise_profile/"; $.ajax({ type: 'GET', url: url, data: { username_clicked: username, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() }, success: function (data) { $('.profile_username').html(data.username); $('.profile_age').html(data.age); $('.profile_points').html(data.points); } }) }); view def raise_profile(request): username_clicked = request.GET.get('username_clicked') if request.is_ajax(): profile = Profile.objects.get(username=username_clicked) profileAge = profile.age profileUsername = profile.username profilePoints = profile.points return JsonResponse({'age': profileAge, 'username': profileUsername, 'points': profilePoints}) comment model class Comment(models.Model): comment_text = models.TextField(max_length=350, blank=True, null=True) author = models.CharField(max_length=120, blank=True) … -
Cannot overwrite default django database settings
I've got a problem with Django DATABASES setting in settings.py. I'm using Python 3.4.3, Django 1.10.5 and psycopg 2.6.1 if my code looks like DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ' dbname', 'USER': 'postgres', 'PASSWORD': 'dbpass', 'HOST': 'localhost', 'PORT': '5432', } } and i run manage.py diffsettings in DATABASE section there are some default settings: DATABASES = {'default': {'USER': '', 'HOST': '', 'AUTOCOMMIT': True, 'NAME': '', 'ATOMIC_REQUESTS': False, 'OPTIONS': {}, 'TEST': {'MIRROR': None, 'CHARSET': None, 'NAME': None, 'COLLATION': None}, 'ENGINE': 'django.db.backends.dummy', 'PASSWORD': '', 'CONN_MAX_AGE': 0, 'TIME_ZONE': None, 'PORT': ''}} but when I change 'default' to 'db' (or any other name) DATABASES = { 'db':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ' dbname', 'USER': 'postgres', 'PASSWORD': 'dbpass', 'HOST': 'localhost', 'PORT': '5432', } } the manage.py diffsettings 'knows' the database db: DATABASES = {'db': {'NAME': 'dbname', 'HOST': 'localhost', 'PORT': '5432', 'PASSWORD': 'dbpass', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres'}, 'default': {'OPTIONS': {}, 'ATOMIC_REQUESTS': False, 'HOST': '', 'AUTOCOMMIT': True, 'PASSWORD': '', 'USER': '', 'TIME_ZONE': None, 'NAME': '', 'PORT': '', 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.dummy', 'TEST': {'NAME': None, 'MIRROR': None, 'COLLATION': None, 'CHARSET': None}}} What should I to to use my database as a default and don't have to use DATABASE_ROUTERS ? -
How to set django model field as method?
This is my model for user order class Order(models.Model): """Order Models""" first_name = models.CharField( max_length=256, blank=False, verbose_name=_('Name')) total_order_cost = models.DecimalField( max_digits=10, decimal_places=2, default=21, verbose_name=_('Total Order Cost')) And my model for ordered items class OrderItem(models.Model): """ Ordered Item Model """ order = models.ForeignKey(Order, verbose_name=_('Order')) price = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('Price')) quantity = models.PositiveIntegerField( verbose_name=_('Quantity')) total_price = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('Total Price')) def get_cost(self): return self.price * self.quantity def save(self, *args, **kwargs): self.total_price = self.get_cost() super(OrderItem, self).save(*args, **kwargs) Field total_price gets value from get_cost. How can I make field total_order_cost work the same way? I want it to get value from def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) I can't overwrite method save for total_order_cost, because when I save order object - ordered items don't exist yet. My view: def make_order(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() # here I save order object for item in cart: # and here I save ordered items OrderItem.objects.create( order=order, product=item.product, price=item.product.price, quantity=item.quantity) cart.clear() return HttpResponseRedirect('%s?status_message=%s' % (reverse('get_cart'), _('Thank you for your order!'))) else: form = OrderCreateForm() return render(request, 'products/make_order.html', { 'form': form}) -
Can't make an instance of the class in Django
I'm making a filter in Django, which takes URL of tweet as argument and returns a HTML code to display in browser. Unfortunately, this doesn't work, as Django complains that OEmbedConsumer is not callable. I believe it's either a random bug or a misunderstanding of how to use specific parts of framework on my side. from django import template from oembed import OEmbedConsumer, OEmbedEndpoint register = template.Library() @register.filter def get_twitter_html(url): consumer = OEmbedConsumer() endpoint = OEmbedEndpoint('https://publish.twitter.com/oembed', ['http://*.twitter.com/*', 'https://*.twitter.com/*']) consumer.addEndpoint(endpoint=endpoint) response = consumer(url) return response.html.replace('\\', '') I have also tried to skip () but then addEndpoint complained about lack of self. Which is somewhat expected. Thanks in advance. -
Django uploading a file deletes the "default" image
I have an Ourteam App that allows you to upload an image, name, title, and social media information for employees. Whenever I create an object the "default.jpg" file is deleted from the media_root. This is my model: from django.db import models from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from smartfields import fields from smartfields.dependencies import FileDependency from smartfields.processors import ImageProcessor from django.template.defaultfilters import slugify class Employee(CMSPlugin): # Set Name name = models.CharField(_('name'), max_length=48) # Define Slug slug = models.SlugField(max_length=40, null = False, blank = True) # Set Title title = models.CharField(_('title'), max_length=48) # Set Image upload path and image properties image_upload_path = 'ourteam/%Y/%m/%d' image = fields.ImageField(upload_to=image_upload_path, blank=True, default='ourteam/default.jpg', dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 150, 'max_height': 150})) ]) created = models.DateTimeField(_('created'), auto_now_add=True) email = models.EmailField(_('email'), max_length=254) # Social Media twitter = models.CharField(_('twitter'), max_length=24, blank=True, default='https://www.twitter.com') linkedin = models.CharField(_('linkedin'), max_length=24,blank=True, default='https://www.linkedin.com') facebook = models.CharField(_('facebook'), max_length=24,blank=True, default='https://www.facebook.com') class Meta: verbose_name = _('employee') verbose_name_plural = _('employee') db_table = 'employee' ordering = ('-created',) get_latest_by = 'created' def __unicode__(self): return u'%s' % self.title def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Employee, self).save(*args, **kwargs) def get_all_employees(): all_entries = Employee.objects.all().order_by('created') return all_entries def slug(sluggy): sluggy = sluggy.replace(' ', '-').lower() return slugify(sluggy) -
Django-I creating temp object and appending to list, overwrites whole list
I am trying to create temporary objects to a model and then append it to a list but the list keeps getting overwritten with the last value, is there a way to overcome this in django? for line in handle: k=Class_Output.make_object(line) miranda_entry.append(deepcopy(k)) print (miranda_entry[0].query) print(miranda_entry[len(miranda_entry) - 1].query) -
django skip entry when looping over queryset (in template)
I have a ListView model, which generates me the required queryset. Then, I my template, I do something like: {% for i in queryset %} {{i.var1}} {% endfor %} .. and this works perfectly. But, what I want to do is: {% for i in queryset %} {% if i.var1 == "mystring" %} <skip this entry and do i++> {% else %} {{i.var2}} {% endfor %} .. but how do I <skip this entry and do i++>? -
install django error Quit the server with CONTROL-C. Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS.?
Im trying to install django with ./manage.py runserver but appears this error please help me -
Show response from get request
if I have a get request for example : /?title1=xxx&message1=xxx&file1=xxx&...&titleN=xxx&messageN=xxx&fileN=xxx The example above display the data. How could I traverse the list of get request and display each 'requestN' on it's own div. Of course this using jinja template and django . I actually find a solution for showing only two parameters . {% for key, value in GET.items %} {% if forloop.counter0|divisibleby:2 %} {% include "title_snippet.html" with title=value %} {% else %} {% include "message_snippet.html" with message=value %} {% endif %} {% endfor %} This solution display work only for two parameters by div I want it to work for N parameters ?titre1=titre1&?message1=message1&?titre2=titre2&?message2=message2 -
admin django. Add the total prince in admin.
hello I have to add a line or for example total_prince = 123312 in admin models.py class Exit(models.Model): description= models.CharField(max_length=50) data_uscita = models.DateField('data uscita') costo = models.DecimalField(decimal_places=2, null=True,blank=True) admin.py class ExitAdmin(admin.ModelAdmin): list_display =['description','prince','total_exit'] def total_exit(self, request): total = Exit.objects.all().aggregate(tot=Sum('prince'))['tot'] return total but is not ok because j have a columns with the total_exit that are repeated. I want total write only just once I'm using Python 2.7.11 -
REST to Salesforce: Intermittent Cryptography_rand_bytes and Bad Handshakes
I've built an application that allows users to OAuth with Salesforce and then makes REST calls on the user's behalf. I'm using a package called simple_salesforce to handle the authentication/rest calls. Running locally I'm not having any issues. However, when I push my Django application to AWS using Elastic Beanstalk I'm finding that I'm getting errors inconsistently. # /var/log/httpd/error_log # extern "Python": function Cryptography_rand_bytes() called, but @ffi.def_extern() was not called in the current subinterpreter. Returning 0. # [Thu Jan 26 18:36:45.482125 2017] [:error] [pid 5531] test_query error: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",) This is happening when I try to test the connection for a user, code below # Here is the first call, I'm trying to check the connection between my application and Salesforce def ajax_check_connection(request): customer_id = request.POST.get('id') customer = Customer.objects.filter(id=customer_id).first() employee = Employee.objects.filter(customer__id=customer.id).filter(user__is_active=True).first() try: # Here I do a test query to ensure check the connection, if it fails I'll return 400 svc = test_query(employee) to_json = {'result': 'success', 'message': 'Confirmed'} response_status = 200 except Exception, e: to_json = {'result': str(e)} response_status = 400 return HttpResponse(json.dumps(to_json), status=response_status, content_type='application/json') def test_query(employee): query = "SELECT Id, Name, IsSandbox FROM Organization LIMIT 1" try: # the first step here is to … -
Django trying to import phantom module
I've been trying to play with Django, but when I try to make the simplest project using the CLI, I keep receiving the error: "ImportError: No module named californication.settings". As far as I can tell, there is no module named "californication" for Python, and I can't figure out why Django is looking for this module. I have Python 2.7 installed on my laptop (Macbook Air, running macOS Sierra 10.12). Note: there is no code to show you here, because I haven't even made it that far. I'm just trying to use the Django toolkit to autogenerate a Django project, as outlined here: https://docs.djangoproject.com/en/1.10/intro/tutorial01/ Here's what I see when I install Django using pip: $ pip install django Downloading/unpacking django Downloading Django-1.10.5.tar.gz (7.7MB): 7.7MB downloaded Running setup.py egg_info for package django no previously-included directories found matching 'django/contrib/admin/bin' warning: no previously-included files matching '__pycache__' found anywhere in distribution Installing collected packages: django Running setup.py install for django no previously-included directories found matching 'django/contrib/admin/bin' warning: no previously-included files matching '__pycache__' found anywhere in distribution changing mode of build/scripts-2.7/django-admin.py from 644 to 755 changing mode of /usr/local/bin/django-admin.py to 755 Installing django-admin script to /usr/local/bin Successfully installed django Cleaning up... Now, when I use django-admin …