Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add one more property in poll based on django tutorial
I come from ASP.NET MVC background. When I follow the django tutorial(https://docs.djangoproject.com/en/1.10/intro/tutorial02/), I found it is hard to change the model or add new template. For this tutorial, if I want to choose what color the Choice will appear as to the users who vote on them when I create a Choice for a Question. What are the steps to do that? I just found django tutorial is not organized like Microsoft's tutorial, so it is hard to work on the python project. -
ValueError | DoesNotExist: Room matching query does not exist
I am tring to create chat room in Django. I use Redis Server and Django Channels. Also I have models Project and Room. Every Project has own chat room. When I try to open chat room page by this url below I have error. It seems to me that my get_or_create method in views.py file not correct. How to fix this error. Need HELP! URL: url(r'^(?P<project_code>[0-9a-f-]+)/chat_room/$', chat_room, name='chat_room'), Error: Internal Server Error: /ru/account/dashboard/projects/1744d0bc-e439-4562-9c29-4e7b2451f39c/chat_room/ Traceback (most recent call last): File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 176, in chat_room room = Room.objects.get(project=project_code) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 385, in get self.model._meta.object_name project.models.DoesNotExist: Room matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\handler.py", line 237, in process_exception_by_middleware return super(AsgiHandler, self).process_exception_by_middleware(exception, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 178, in chat_room room = Room(project=project_code) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\base.py", line 537, in __init__ setattr(self, field.name, rel_obj) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 211, in __set__ self.field.remote_field.model._meta.object_name, … -
Custom query filter in django admin
I want filter all Quote based on characters length, and this is my query in django admin. class QuoteCountFilter(admin.SimpleListFilter): """Filter based on quote_text characters count.""" title = _('Quote Text Char Count') parameter_name = 'quotelength' def lookups(self, request, model_admin): return ( ('lessthan50', _('Less than 50')), ('morethan50', _('More than 50')), ) def queryset(self, request, queryset): if self.value() == 'lessthan50': return queryset.extra(select={"val": "SELECT id FROM web_quote WHERE character_length(quote_text) < 50"}) However, it returns Programming error more than one row returned by a subquery used as an expression Any ideas how to fix? -
django: Add an extra serializer field in a many=True serializer?
So I serialize comments with the many=True argument. I want to add a comment_count after I serialize it. Of course, this wouldn't work: serializer.data.update({'comment_count':comment_count}) since you can't use update on a ReturnList object. What's the best way to accomplish this? -
Allauth Django Login URL
allauth django I would like to redirect a user to a "dynamic" login page. I am currently being redirected to accounts/login but I would like it to be accounts/login/?name=Bob for user Bob accounts/login/?name=Carl for user Carl accounts/login/?name=Alice for user Alice etc ... Note that I could change the LOGIN_URL in settings.py to be e.g. accounts/login/?name=Bob but that would remain fixed and I would not get accounts/login/?name=Carl or accounts/login/?name=Alice. Once the user has successfully login, I would need to retrieve the name from the request e.g. If user Bob has successfully login, get the name=Bob, etc. Usually, I would do request.GET.get('name','') but I would need to change allauth views Is there a way to achieve the above without changing the source code of allauth. -
Django app structure if same model to many apps
I am working on a Django web app for a statistics company. A few of the tables in their PostgreSQL database pretty much drive all the data are involved in most JOINS. In other words, it essential for the entire application to function properly. There are at least 12 different unique processes, or stages, to this company's cycle involving this data. Each on would make sense to make its own Django app in the project. It would not make sense to me to add the models to anyone of these apps. It kind of makes sense to make a unique app that just has models from which other apps can import. For example, if you are working with items numbers, item numbers are obviously driving the data. A web application might have a Reporting, Inventory, Order Entry, etc. all of which would make sense to have as separate apps, but wouldn't make sense to have your Items model under any one app... at least to me. Just curious what practices others are using in the situation. -
Keep objects in order using a float
I am attempting to build a model that will keep items in order when a user changes its position (this happens on a JS frontend). I feel a 'float' is best, as this value will constantly be changing. I will be passing the value by a javascript application. class Item(models.Model): title = models.CharField("Title", max_length=10000, blank=True) position = models.FloatField("Item position", blank=True, null=True) So the data could be: title | position Charlie | 1 Mark | 2 Bruce | 3 When Mark's position changes, it would automatically change Charlies' to position value to 2: title | position Charlie | 2 Mark | 1 Bruce | 3 How would I post this information (API) so that django realises one title belongs above another? -
Does Django work diffrently in a different OS
I was running a Django Server on my Desktop which runs Linux Mint and it worked perfectly but when I run my server on the same Desktop but using a Diffrent OS (Apricity OS) i get an error. I made a github repo with my code in it (https://github.com/pythongiant/Memes). Error- AttributeError at /photos/memes 'FieldFile' object has no attribute 'replace' Request Method: GET Request URL: http://127.0.0.1:8000/photos/memes Django Version: 2.0 Exception Type: AttributeError Exception Value: 'FieldFile' object has no attribute 'replace' Exception Location: /usr/lib/python3.5/site-packages/Django-2.0.dev20170317160306-py3.5.egg/django/utils/encoding.py in filepath_to_uri, line 252 Python Executable: /usr/bin/python Python Version: 3.5.2 Python Path: ['/mnt/14B0B442B0B42C5C/My Programs/memes/memes', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-linux', '/usr/lib/python3.5/lib-dynload', '/usr/lib/python3.5/site-packages', '/usr/lib/python3.5/site-packages/Django-2.0.dev20170317160306-py3.5.egg', '/usr/lib/python3.5/site-packages/pytz-2016.10-py3.5.egg'] Server time: Wed, 22 Mar 2017 09:01:06 +0530 I dont even use the function replace in my whole Project. Thanks (in advance) -
What combination/libraries to use if I want to develop a simplified ERP using Django + React
Im new to web development and I want to create a simplified ERP. Now, I started with using Django and currently looking at react as my Frond end. Im just confused with React as it does require many components/libraries to pair with. I read about flux, redux, ang mobx and now Im confused on what to choose from this three that will be suitable for ERP. This is the stack that I want to use. MySql as my database, django as server side and react as client side. Thank you very much. -
How do I display the results of data_frame.plot.bar() on the webpage using Django?
I want to display the results of pandas df.plot.bar() on the webpage.How do I do it? This is what I am trying. def graph(request): fig = Figure() ax = fig.add_subplot(111) data_df = pd.read_csv("C:/Users/yadynesh/Final_Project/original.csv") data_df = pd.DataFrame(data_df) data_df.plot.bar(ax=ax) canvas = FigureCanvas(fig) response = HttpResponse( content_type = 'image/png') canvas.print_png(response) return response -
Django Celery Workers in multiple machine
we are trying to deploy a django project on three nginx web servers with aws ELB. We expect the traffic around 1 million request in 1 minute. I dont have an idea how to architect the system with celery tasks/ any others to handle high traffic. Should I run celeryd worker on each web server? do I need to configure multiple workers on each machine.? Is this the way to handle heavy traffic websites ? running the workers inside same machine within web server require CPU from machine will it affect the request time I have separate server for redis broker and for caching. How can I use periodic tasks if the code is the same in all web servers ? Is there any other way to run periodic tasks outside Django ? IS there any best way to do the tasks other than celery ? Like within GET/POST request django view function call some remote worker execute on different machine ? Will it be better than running celery inside a machine. Help me with architecture my design. Thanks. -
Connect Django to Jboss virtual database
Is it possible to use a RedHat JBOSS virtual database as the database backend for Django? If so what would the DATABASES section in settings.py look like? -
django getattr for ManyToManyField
how to use getattr to get ManyToManyField value? in model's save method : getattr(Project.objects.filter(name=self.name)[0], 'type') getattr(self, 'type') getattr(Project.objects.filter(name=self.name)[0], 'user') getattr(self, 'user') I got this: 10kmop 10kmop auth.User.None auth.User.None user is a ManyToManyField, I got None here. how can I got those user value? -
Simplest AngularJS App to with Session Authentication to DRF
I have been banging my head against the wall for far too long trying to get session authentication to work in AngularJS with the basic Django REST Framework setup. I've read through blogs dozens of stack overflow questions and answers, and I'm just not getting it. I have a large application that I'm working on, but in order to facilitate an answer to this issue, I've produced a minimalist AngularJS App on top of a fork of the bare-bones Django REST Framework Tutorial code here. (All the front-end dependencies are included in the fork.) Just do pip install -r requires.txt, python manage.py makemigrations snippets, python manage.py migrate, and then python manage.py runserver. The main code of interest is here: "use strict"; var geoint = angular.module('snippets', [ 'ngRoute', 'ngCookies', 'ngAnimate', 'ngResource', 'snippets.controllers', ]) .config(function ($routeProvider, $httpProvider) { $httpProvider.defaults.withCredentials = true; $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $routeProvider .when('/', { title:'Snippets - Home', templateUrl: STATIC_URL + 'snippets/partials/snippets.html', controller: 'SnippetsCtrl' }) .otherwise({ redirectTo: '/' }); }) .run(function($rootScope, $location, $http) { // Get a CSRF Token $http.get('api/auth/login/?next=/api/').then( function successCallback(response){ console.log(response); // Post should come back with Set-Cookie sessionid, but it doesn't! $http.post('api/auth/login/', {username:'username', password:'password'}).then( function successCallback(response){ console.log(response); // Get this user's information $http.get('api/currentuser/').then( function … -
Allow signup only to invitation accepted user
I am developing an app where a user should first request for invitation and if his invitation is accepted by admin(from admin), a message should be sent that you can signup. Flow 1) User submits the form with his/her email address 2) Mail will be sent saying Thank you for joining us 3) Now if admin accepts the request, invite_accepted is True again a mail should be sent saying You can now signup 4) At last when user submits the signup form, it should check that email address request is accepted or not. If accepted, signup process should be successful otherwise should display message of sorry you are not accepted yet. From the flow I could do till 3 but no idea how can i check the email exists or not so that i can allow for signup process to continue or not. I am using django allauth for registration. Here is my code models.py class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_("e-mail Address")) request_approved = models.BooleanField(default=False, verbose_name=_('request accepted')) @receiver(post_save, sender=Invitation) def send_email_when_invite_is_accepted_by_admin(sender, instance, *args, **kwargs): request_approved = instance.request_approved if request_approved: subject = "Request Approved" message = "Hello {0}! Your request has been approved. You can now signup".format(instance.email) from_email = None to_email … -
Python Social Auth Djang Github OAuth
I'm trying to integrate my Django website with Github Authentication using Python-Social-Auth library Configuration so far: settings.py INSTALLED_APPS += ( ... "social_django", "social_core", ) AUTHENTICATION_BACKENDS = [ "account.auth_backends.UsernameAuthenticationBackend", "social_core.backends.github.GithubOAuth2", ] TEMPLATES = [ { ... 'context_processors': [ ... "social_django.context_processors.backends", "social_django.context_processors.login_redirect", ], }, }, ] login.html <a href="{% url "social:begin" "GithubOAuth2" %}">Github</a> But when I click the link, it shows a 404 Not Found Page. And where do I put the secret key and other github configuration? -
why slow when implement direct searching using python and django to display the file?
def SearchBox(request): fullpath = "" input_Lot = request.GET.get('input_lot') input_Operation = request.GET.get('input_operation') summary1A = "1A" summary_combine = "combined" Lot_Operation_combine = str(input_Lot).upper() + "_" + str(input_Operation) + "_" + str(summary_combine) Lot_Operation_combine1 = str(input_Lot).upper() + "_" + str(input_Operation) + "_" + str(summary_combine) Lot_Operation_1A = str(input_Lot).upper() + "_" + str(input_Operation) + "_" + str(summary1A) if input_Lot is None: return render(request, 'Output.html') else: path1 = "//kmf" shp_list = [] for dirpath, dirnames, y in os.walk(path1): for k in y: k.startswith(Lot_Operation_combine) and k.endswith(".html") fullpath = os.path.join(dirpath, k) shp_list.append(fullpath) if os.path.isfile(fullpath): path = "//kmf" shp_list = [] for dirpath, dirnames, x in os.walk(path): for f in x: if f.startswith(Lot_Operation_combine1) and f.endswith(".html"): fullpath = os.path.join(dirpath, f) shp_list.append(fullpath) if os.path.isfile(fullpath): with open(fullpath, 'r')as f: f_contens = f.read() print(f_contens) kau = f_contens context = { "Final": kau } return render(request, 'Output.html', context) else: path = "//kmf" shp_list = [] for dirpath, dirnames, x in os.walk(path): for f in x: if f.startswith(Lot_Operation_1A) and f.endswith(".html"): fullpath = os.path.join(dirpath, f) shp_list.append(fullpath) if os.path.isfile(fullpath): with open(fullpath, 'r')as f: f_contens = f.read() print(f_contens) kau = f_contens context = { "Final": kau } return render(request, 'Output.html', context I have more than a thousand of html file inside my virtual share folder in network. When I try … -
converting html result from dango view to pdf
i read and tried most of the answers in stackoverflow and many other platforms for the solution but no luck please do help me with this. the result is made by loops method from views and filtered by input. i have results in html made by django views i configured it in A4 format in css somehow and tried to print preview in chrome the alignment are perfect except its making a blank page after every result as it contains thousands of page it will be hard for printing. thanks in advance. -
How does a django app start it's virtualenv?
I'm trying to understand how virtual environment gets invoked. The website I have been tasked to manage has a .venv directory. When I ssh into the site to work on it I understand I need to invoke it with source .venv/bin/activate. My question is: how does the web application invoke the virtual environment? How do I know it is using the .venv, not the global python? More detail: It's a Drupal website with Django kind of glommed onto it. Apache it the main server. I believe the Django is served by gunicorn. The designer left town _ -
Django chained filtration returns Related Field Invalid Lookup in Django 1.10
I have several models in a Django 1.10, Python 2.7 application running on an Ubuntu 16.04 VM, and when I try to get two of them through chained relation/filtration, it seems to fail one way. The two models are: class Crisis(models.Model): name = models.CharField( max_length=200, default='' ) # Time fields start_date = models.DateTimeField( null=True, blank=True ) end_date = models.DateTimeField( null=True, blank=True ) # Blast zone fields radius = models.DecimalField( max_digits=14, decimal_places=6 ) origin = models.PointField( srid=4326, null=True, blank=True ) zone = models.PolygonField( srid=4326, null=True, blank=True ) # Location fields country = models.ForeignKey( "boundaries.Country", verbose_name="country", related_name="crises", null=True, blank=True, default=1 ) class Meta: verbose_name = 'crisis' verbose_name_plural = 'crises' # Returns the string representation of the model. def __unicode__(self): # __unicode__ on Python 2 return unicode(self.name) class Game(models.Model): name = models.CharField( default='', max_length=200, null=True, blank=True ) number_of_turns = models.IntegerField( default=10, null=True, blank=True ) crisis = models.ForeignKey( 'games.Crisis', related_name='games', related_query_name = 'game', null = True ) donor = models.ForeignKey( 'games.Donor', related_name='donor', blank=True, null=True ) description = models.CharField( default='', max_length=2000, null=True, blank=True ) def __unicode__(self): # __unicode__ on Python 2 return u'{0}'.format(self.name) There are other models in the application which are used and for which I can get to game via crisis, as observed … -
How to do complex filter in django with rest framework?
I have 2 subcategorires of Tipo_Unidad, so I send via get the ID of tipo_unidad it depends of the checkbox selected but I have a problem, When I select the two categorires at the same time I send the ID in this format [1,2] and I don't know how to the for loop in my django view to obtain the query for each ID received. This is part of my view: q = request.GET.get('tipo_venta') i = request.GET.getlist('id_tipo_unidad[]') maxi = request.GET.get('Max') mini = request.GET.get('Min') if q is not None or i is not None or maxi is not None or mini is not None: for var in i: unidad = Unidad.objects.filter(id_tipo_unidad=var) serializer = UnidadSerializer(unidad, many=True) return Response(serializer.data) else: return Response({}) If I send only one ID the code works but if I send two it don't work, and the django console show this: invalid literal for int() with base 10: '1,2' -
Retrieve related models for Django Admin multiselect using intermediate table/model
Sorry for the wall of text. Here's an abbreviated version. I am converting a legacy application/database table over to Django and I'm having trouble setting up the Django admin site to include an inline form that would select multiple related models. The models are named Event, EventProduct, EventProductColor and Color. EventProductColor relates multiple colors to an EventProduct. I am trying to set it up so the admin page for an Event allows you to edit any related EventProducts. Each EventProduct has a default color and a number of available colors. So far I have the inline form for editing EventProducts, but can’t figure out how to configure the admin to allow the user to pick multiple colors. The following is the code I have so far. It’s been simplified a bit for this post. models.py class Color(models.Model): name = models.CharField(max_length=255, blank=True, null=True) url_name = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'colors' class Event(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'events' class EventProduct(models.Model): event = models.ForeignKey(Event, models.DO_NOTHING, blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True) default_color_id = models.ForeignKey(Color, models.DO_NOTHING, null=True, blank=True, db_column='default_color_id') colors = models.ManyToMany(Color) # this should … -
custom user color scheme django
I want my user to be able to use there own colors that the pick on a form or color picker(future) store these and then pick from a list of color schemes they created. so far i am using the info from the form to pass through the template like so for each attribute i want them to be able to change. {%if user.is_authenticated%}{%for colorscheme in colorscheme%} {{colorscheme.color1}}{% endfor%}{%endif%} ^^That is alot of code for the 20+ elemants to change inline my question is there a better way of doing this by passing the variable through the css somehow or is there a way to store this info in a context processer and pass to template. I have tried the context processor but when i go to filter the query-set i have problems with the Anonymous User with out a profile. def colorscheme(request): colorscheme = pickacolorscheme.objects.filter(profile=request.user.profile) return { 'colorscheme': colorscheme, } Any help would be grateful! -
display variables from objects django
What I am trying to do is take to variables that I have as people select from the two options in the form it will display the email selected and the course selected next to each other underneath it. I can't use sessions for it. And Im told there is a way to just pull it from data base and show it. My code is linked below. Views.py from django.shortcuts import render, redirect, HttpResponse from .models import courseuser from .models import User # Create your views here. def index(request): context ={ "courses": courseuser.objects.all(), } return render(request, "courseapp/index.html" ,context) def create(request): if request.method == 'POST': courseuser.objects.create(course_name = request.POST['course_name'], description = request.POST['description'] ) return redirect ( "courses:index" ) def catalog(request): context ={ "courses": courseuser.objects.all(), "people" : User.objects.all() } return render(request, "courseapp/catalog.html" ,context) def addstudent(request): student = user.objects.get(id = request.Post['user']) course = courseuser.objects.get(id =request.POST['course']) return redirect("courses:catalog") urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name= 'index'), url(r'^user$', views.create, name='success'), url(r'^catalog$', views.catalog, name='catalog'), url(r'^addstudent$', views.catalog, name='addstudent') ] catalog.html <!DOCTYPE html> <html> <head> <title>Catalog</title> </head> <body> <div id = container 1 > <ol> <form action="{% url 'courses:addstudent' %}" method='post'> <h4>Select User</h4> {% csrf_token %} <select class="" name="user"> {% for … -
Getting data from python with JS and plotting it, with Django backend and Google maps api
I've got a project with a django backend that I'm using for logins, and using the mysql DB through my local host. I currently have my gettweets.py script returning an array of coordinates and have a JS script that is supposed to get these results and plot it to google maps api. My JS script fails at $.get. However, if i go to 127.0.0.1/gettweets?tag=%23Pizza, i get something like this: ["-87.634643, 24.396308", "-80.321683, 25.70904", "-79.639319, 43.403221", "-95.774704, 35.995476", "-84.820309, 38.403186", "-120.482386, 34.875868", "-121.385009, 38.716061", "-111.530974, 40.619883"] I've been trying to get JS to make the call on the button click because I don't think I can get the results to it through Django. Why is it getting stuck? Here is the JS inside of index.html var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: new google.maps.LatLng(49.13,-100.32), mapTypeId: 'roadmap' }); } // Loop through the results array and place a marker for each // set of coordinates. $('#searchButton').click(function(){ $.get('../../gettweets?tag=%23Trump', function(data, status) { alert(status); var data = JSON.parse(this.response); alert('data'); data.forEach(function(point) { var coordString = point['coord']; var x = coordString.substring(0,coordString.indexOf(',')); var y = coordString.substring(coordString.indexOf(',')+1,coordString.length); console.log(x); console.log(y); var coords = results.features[i].geometry.coordinates; var latLng = new google.maps.LatLng(x,y); var marker = new google.maps.Marker({ …