Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ElasticbeanStalk Deployment
I'm deploying a django application on elasticbeanstalk and when I run eb open I'm receiving a Internal Servor Error 500. How do I fix this error. Here are my eb logs results ============= i-0b11de8b8521ea5c0 ============== ------------------------------------- /var/log/httpd/error_log ------------------------------------- [Fri Oct 21 04:04:32.248804 2016] [:error] [pid 27152] [remote 172.31.5.67:52953] 'File "/opt/python/current/app/pronet/src/pronet/wsgi.py", line 12, in <module> [Fri Oct 21 04:04:32.248810 2016] [:error] [pid 27152] [remote 172.31.5.67:52953] from django.core.wsgi import get_wsgi_application [Fri Oct 21 04:04:32.248831 2016] [:error] [pid 27152] [remote 172.31.5.67:52953] ImportError: No module named 'django' [Fri Oct 21 04:04:32.801821 2016] [:error] [pid 27152] [remote 172.31.5.67:53209] mod_wsgi (pid=27152): Target WSGI script '/opt/python/current/app/pronet/src/pronet/wsgi.py' cannot be loaded as Python module. [Fri Oct 21 04:04:32.801865 2016] [:error] [pid 27152] [remote 172.31.5.67:53209] mod_wsgi (pid=27152): Exception occurred processing WSGI script '/opt/python/current/app/pronet/src/pronet/wsgi.py'. [Fri Oct 21 04:04:32.801908 2016] [:error] [pid 27152] [remote 172.31.5.67:53209] Traceback (most recent call last): [Fri Oct 21 04:04:32.801966 2016] [:error] [pid 27152] [remote 172.31.5.67:53209] File "/opt/python/current/app/pronet/src/pronet/wsgi.py", line 12, in <module> [Fri Oct 21 04:04:32.801971 2016] [:error] [pid 27152] [remote 172.31.5.67:53209] from django.core.wsgi import get_wsgi_application [Fri Oct 21 04:04:32.802002 2016] [:error] [pid 27152] [remote 172.31.5.67:53209] ImportError: No module named 'django' [Fri Oct 21 04:04:33.784345 2016] [:error] [pid 27152] [remote 172.31.5.67:52953] mod_wsgi (pid=27152): Target WSGI script '/opt/python/current/app/pronet/src/pronet/wsgi.py' cannot … -
Django template for loop AJAX does not work
I am trying to implement a forum. When a user submits a post, there is an AJAX like this: $.post("my-url", paramObj, function(data, status) { $('#board').html(data); }); "#board" is the div holding all the posts. Data is rendered in my view: html = render_to_string('board template', context) And the template looks like: {% for post in post_list %} //<p>s for post //using exactly the same AJAX request above //token is the csrf token from last request <form id = "{{ forloop.counter }}" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="{{token}}"> //the form {% endfor %} However, it only works for the first post, then after rendered partially, any new posts will refresh the page and not calling my function in view. I am thinkg this is because csrf token, but I have tried https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax and @csrf_exemtp both do not work. -
Why is assertRedirects test failing in the Django test?
Testing in the browser works and the headers are correct (302 -> 200). Runserver shows the correct behavior (302 -> 200). But the test fails saying that the response was 302. def test_redirects(self, *args): response = self.user.get(reverse('admin')) self.assertRedirects(response, reverse('profile')) In runserver: $ "GET /admin HTTP/1.1" 302 0 $ "GET /profile HTTP/1.1" 200 90054 -
what is the best way to use less Django template syntax as possible with Django Form?
I am just beginner of Django. At first, It seemed very convenient to use Django Form. I can get all which i already I defined in Model with ModelForm class. I can just put { form } in template. There are already pre-defined Field type and I can use it conveniently. But it is tricky if you need to work with one who doesn't know Django or Python and are charge of making front-end part. For example, I make template like this. example.html <form action="." method="post"> {% csrf_token %} {{ form }} <input type="submit" value="ok"> views.py class TestView(FormView): template_name = 'example.html' form_class = TestForm success_url = '/success/' def form_valid(self, form): print('data is validated! you can do work with cleaned data!') return super(TestView, self).form_valid(form) Q1 : A front-developer can't work with {{ form }}. right? So I can change just example.html because it works properly if you set name attribute and type attribute correctly. example.html <form action="." method="post"> {% csrf_token %} <input type="text" name="name"> <input type="text" name="calorie"> <input type="submit" value="Ok"> </form> models.py class Cereal(models.Model): name = models.CharField(max_length=50) calorie = models.CharField(max_length=50) Q2 : I think it would be fine for a front developer to work with it if I change example.html above? … -
why the page not found?(django)
Page not found (404) Request Method: GET Request URL: http://localhost:8080/music/1/ Using the URLconf defined in emeer.urls, Django tried these URL patterns, in this order: ^admin/ ^music ^$ [name='index'] ^music ^(?P[0-9]+)/$ [name='detail'] The current URL, music/1/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index, name='index'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), ] views.py from django.http import HttpResponse def index(request): return HttpResponse("<h1>This will be a list of all albums</h1>") def detail(request,album_id): return HttpResponse("<h2>Details for Album id:"+ str(album_id) +"</h2>") -
POST response in Django Tastypie for custom field definition doesn't seem right
Ok I'm totally puzzled by this... I have a custom field defined like this example on a standard looking model and api endpoint using Tastypie. When I retrieve the data from the db, I append some extra string to the value. On a POST response the string is not appended, but I would've expected the data to be committed and retrieved (POST/GET). I'd prefer not to override dehydrate with an extra query just because of this create response - what's a good solution here? THANKS! # models.py class NameCaller (models.Model): mean_sentence = MeanSentenceField(... # fields.py class MeanSentenceField(models.CharField): def from_db_value(self, value, expression, connection, context): if value is None: return value return self.make_mean_sentence(value) def make_mean_sentence(value): return '{0}, you big jerk'.format(value) # api.py class NameCallerResource(ModelResource): class Meta: ... # repl test = NameCaller(mean_sentence='Hello') test.save() print test.mean_sentence >> 'Hello, you big jerk' curl POST -d '{"mean_sentence": "Hello"}' localhost/api/name_caller/ >> {"id": 1, "mean_sentence": "Hello"} curl GET localhost/api/name_caller/1/ >> {"id": 1, "mean_sentence": "Hello, you big jerk"} -
JQuery not working with Angular2 components
I am working on a web application that is Django on the backend, and Angular2 on the front end. Django serves up a base template, and Angular2 components are injected into that base template. I've gotten to the point where all the components are rendering on the page as they should with angular2, but certain parts of the components that require custom JQuery are not functioning. For example I have two identical html partials, one an Angular2 component, and one using Django templates. The partial is a jquery flexslider I am using for testimonials. in the Django templates chunk, the flexslider is working, but the same angular component right next to it does not render the flexslider. I instantiate the flexslider in a jquery document.ready function. Are angular2 components not actually a part of the DOM, and if so does that mean that JQuery in document.ready functions wont affect Angular2 components ? base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Halloween Project</title> <script src="/static/node_modules/jquery/dist/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.css"> <link rel="stylesheet" href="/static/node_modules/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="/static/node_modules/flexslider/flexslider.css"> <link rel="stylesheet" href="/static/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet"> <script src="/static/node_modules/bootstrap/dist/js/bootstrap.min.js"></script> <script src="/static/node_modules/flexslider/jquery.flexslider-min.js"></script> <script src="/static/node_modules/chart.js/dist/chart.min.js"></script> <!-- GMAPS SECTION SCRIPTS --> <script src="https://maps.google.com/maps/api/js?key=AIzaSyAsCKTyJeFPq0LpqPaBnUCgRp5my8W3GbA"></script> <script type='text/javascript' src='/static/js/gmaps.js'></script> <!-- … -
run time in django views cost time is different in python shell
I am using django and I found a very confusing question. In my views.py like this if request.method == "GET": raw_get = request.GET.dict() raw_data = '' draw = raw_get.get('draw', 0) if raw_url == "index": recordsTotal = Host.objects.count() raw_data = Host.objects.select_related('belongs_to_ostype').prefetch_related( 'assignedip_set').select_related( 'belongs_to_PlatForm').prefetch_related( 'applications__with_vip').prefetch_related( 'applications__belongs_to_apptype').prefetch_related('applications').all() start = time() data = {"data": [i.show_index() for i in raw_data], 'draw': draw, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsTotal} end = time() print 'cost time', end - start return JsonResponse(data) from the terminal, it shows the cost time, like this cost time 10.1911799908 [21/Oct/2016 09:39:54] "GET /assets/data_index/?_=1477013984767 HTTP/1.1" 200 471123 Howerver, when I use python manager.py shell, I have the follewing def test2(): recordsTotal = Host.objects.count() start = time() data = {"data": [i.show_index() for i in raw_data], 'draw': 0, 'recordsTotal': recordsTotal,'recordsFiltered': recordsTotal} end = time() print 'cost time', end - start This function do the same thing as in views.py,but the cost time is much different. When I run this function, cost time like this >>> test2() cost time 4.91849398613 Why? -
Monitoring User Activity in Django
I am creating a book app where users can sign up and start reading. This is the model.py for the book: from django.db import models from django.urls import reverse from django.conf import settings class Chapter(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) date_completed = models.DateTimeField(blank=True, null=True) completed = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("course:subchapter_list", kwargs={"pk": self.pk}) class SubChapter(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) completed = models.BooleanField(default=False) def __str__(self): return self.title class SubSection(models.Model): sub_chapter = models.ForeignKey(SubChapter, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) text = models.TextField(null=True, blank=False) completed = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("course:detail", kwargs={"slug": self.sub_chapter.slug, "slug2": self.slug, "pk": self.sub_chapter.chapter.pk, } ) How can I monitor each user's progress such that when a subsection/subchapter/chapter is viewed/read, that model instance's completed attribute is set to True just for that user? My current implementation sets completed to True for everyone -
How to access to extend user information from the template in Django?
I am extended user.model to ClientUser I want to have access to ClientUser information using current user from the template side. I want to display the name of the company in my template, something like this {{user.company}} class ClientUser(models.Model): client = models.OneToOneField(User) company = models.ForeignKey(Company) def __str__(self): return str(self.company) + ' - ' + str(self.client) class Company(models.Model): company_name = models.CharField(max_length=250, null=True) company_url = models.CharField(max_length=500, null=True) active = models.BooleanField(default=True) def __str__(self): return self.company_name -
How to connect to Django from Spring
I'm trying to find a way of sending data to my web server on Spring framework from Django which controls actions of tensorflow. If Spring server send a request, is it possible to send a output from Django? If you have experiences like this, please give me some tips. -
Where does the `build` phase happen in setuptools?
This a question about setuptools and creating a python distribution for a web application. Context It is a django project and we distribute it via a private pypi, to ourselves, not external users (yet). Currently we run python setup.py sdist to create the distribution and we upload that to our pypi. I suspect it is just a copy of the source code as a tar.gz. We checkout the source to do development. We don't install for dev via pip (perhaps we should?). Recently the project has started using nodejs. Which now means that now we need to do a "build" to create new files which are not part of the source code, but do need to be deployed. The build process requires a bunch of node packages which are not a necessary, or desired, part of the final deployment to a webserver. Reading through the packaging documentation it describes sdist, bdist_wheel, and also develop targets for setup.py, but I'm not clear on how to apply these to our situation. Question 1 When we pull from our pypi, what should we be pulling? the pre-built deployable version of code for the webserver, without source code?, or code on which we run … -
django testing: client.get returns MultipleObjectsReturned error
When I run the following test, I want client.get() to return a list of examples. It does so correctly, but it throws this error: MultipleObjectsReturned: get() returned more than one Example -- it returned 8! How do I deactivate this error? def test_read_all_examples(self): # get all examples url = reverse('example') admin = User.objects.get(username='admin') client = APIClient() client.force_authenticate(user=admin) response = client.get(url, format='json') print("GET - ExampleTests Response:", response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) -
Syntax error in a correct python script when redirected to stdin
Using the bash shell on Ubuntu Linux and Python 2.7.6, if I run the python script below with the command, python test.py I get this output: outer inner 2 If I, instead, use redirection of stdin like this, python -i < test.py The output is, >>> outer >>> >>> ... ... ... File "<stdin>", line 4 print i ^ SyntaxError: invalid syntax >>> So, clearly, I shouldn't use the -i option with shell redirection, ie with the '<' character in the command. This combination apparently leads to some manipulation of white space which, by the time python parses the input, is a python syntax error. Unfortunately, I run into the same problem when running python scripts in the Django python shell and the command to run the Django python shell has no way to disable interactive python mode and no way to pass the name of a python script file. Furthermore, I believe this worked on a different Linux box or earlier on the same Linux box so I wonder if there is some environment setting that would fix it. Is there a way to change the behavior of python's interactive mode or is there a way to disable interactive … -
Django how do I get a command to execute when all tests pass?
I'm trying to find out if there is a way to have a function fire when all the tests pass. trying to do something along the lines of: call(["say", "all tests have passed Dave"]) -
Django not searching correct table name for custom user model
I'm trying to use a custom user model in my Django project. After running migrations, the database table is named accounts_listuser while Django appears to be looking for them in accounts_user. How can I change this so Django looks at the correct table for the user model? In my settings.py: # Auth user models AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( 'accounts.authentication.PersonaAuthenticationBackend' ) The accounts/models.py file: class User(models.Model): email = models.EmailField(primary_key=True) last_login = models.DateTimeField(default=timezone.now) REQUIRED_FIELDS = () USERNAME_FIELD = 'email' is_authenticated = True is_anonymous = False And the file (accounts/authentication.py) where the query fails: from django.contrib.auth import get_user_model User = get_user_model() def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None The full source code can be found here if it helps. -
Using Django with an existing, complex database
Is it possible to use Django with an existing database, Microsoft SQL in my case, that is really huge and complex and in addition must not be changed in any way by Django? I already read this, but it does not seem to solve my problem; it says manage.py migrate will add some tables to the database, which must not happen. My user stories are: I want to view the customer data from the existing database in my browser (SQL select) I want to write a visit report (SQL insert) Beyond that, the database must not be changed. Is that possible with Django? Is Django even the right tool for the job? Is it possible to have a Django-specific database and a different database from which it will select/insert? -
" django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 5: 'get_verbose_name', expected 'empty' or 'endfor'. "
I have been searching for ways to display data from Django models in a view/template. I am still just a beginner but have read a lot of stackoverflow to gain knowledge. The implementation of what I am trying to do I picked up from this thread: Display table of objects django After inputting the template.html and the views.py (slightly modifying my views.py - changing MyModel to the Environment Model) I am getting the error : "Invalid block tag on line 5: 'get_verbose_name', expected 'empty' or 'endfor'. Did you forget to register or load this tag?" This error is referring to the <th>{% get_verbose_name field %}</th> in template.html I have tried to add a verbose name to every field in the model but this is not the apparent issue. Attached in a pastebin is my views.py, models.py and template.html. My views.py and template.html are almost exactly the same as the solution checked in the linked stackoverflow thread. My issue is basically understanding why this error exists, and how I can resolve it Thank you for your help tables.html <table> <thead> <tr> {% for field in cached_fields %} <th>{% get_verbose_name field %}</th> {% endfor %} </tr> </thead> <tbody> {% for d in … -
Django: Identify the urls that provide duplicate content and set a canonical link
models.py class People(models.Model): name = models.CharField(max_length=16) meters_away = models.IntegerField() Lets populate the db: >>> from people.models import People >>> a = People() >>> a.name = 'George' >>> a.meters_away = 15 >>> a.save() >>> b = People() >>> b.name = 'Jim' >>> b.meters_away = 10 >>> b.save() Supposing that we have a url that returns all people in a range of x meters: http://example.com/range/<meters> This url scheme accepts 3 hits as follows: http://example.com/range/20 http://example.com/range/30 http://example.com/range/40 Those hits will create the following queries: >>> hit1 = People.objects.filter(meters_away__lt=20) >>> hit2 = People.objects.filter(meters_away__lt=30) >>> hit3 = People.objects.filter(meters_away__lt=40) Where: >>> list(hit1) == list(hit2) == list(hit3) >>> True This means that example.com, will serve 3 different urls with the same content. From a SEO point of view, how could all the possible urls (meters: 21, 22, 23, 24, 30, 40 etc) be filtered in a way that a canonical url is appended to them? -
DRF - extend obtain auth token
I have Django Rest Framework with token auth. I have a following url url(r'^api/auth/', views.obtain_auth_token), which returns me token. What I need to do is perform some db logic, when user performs authorization which is getting the token. I need to query db and do some stuff there. It seems to me that I have somehow to override default behaviour and add some custom logic to obtain_auth_token. How can I do that ? -
How do I use RelatedField from Django Rest Framework when there is a reverse ForeignKey?
Here are my models: class Property(models.Model): id = [...] address = [...] class Property_Value(models.Model): id = models.ForeignKey(Property) amount = [...] last_updated = [...] def __unicode__(self): return '%s: %s' % (self.last_updated, self.amount) My serializer are: class Property_ValueSerializer(serializers.ModelSerializer): class Meta: model = Property_Value fields = ('last_updated', 'amount') class PropertySerializer(serializers.ModelSerializer): 1) property_values = Property_ValueSerializer(source='property_value_set', many=True) 2) property_values = serializers.RelatedField(many=True, read_only=True) class Meta: model = Property fields = ('id', 'address', 'property_values') I would like to display a json like this: [ { "id": "2", "address": "123 Apple Lane", "property_values": [ { "10/13/2016": "1709195.00" } ] } ] If I use option 1, I get: [ { "id": "2", "address": "123 Apple Lane", "property_values": [ { "last_updated": "10/13/2016", "amount": "1709195.00" } ] } ] If I user option 2 (which is what was suggested by the Rest tutorial, I get an Attribution Error: AttributeError at /api/property/ 'Property' object has no attribute 'property_values' I'm not quite sure what I am doing wrong. Can someone point out what I am doing wrong? Thanks. -
Paginating many to many field in django
Right now I paginate things like so: paginated_query = Paginator(model.objects.filter(stuff=True).all(), 20) paginated_query.page(3) but say that instead of paging this query, I have a field that I want to paginate class model(models): many_stuff = models.ManyToManyField(model2) ... and say I have 1 object with a LOT of model2 entries tied to it, it'll take a really long time to pull out everything, so would it be possible to pull them out chunk by chunk? -
using Aldryn Apphooks Config
Hi everyone one I am using Aldryn Apphooks Config to add configuration to my apphook. My model is like this class Entry(models.Model): TYPES_CHOICES = ( ('none', 'not specified'), ('v', 'By Visit'), ('p', 'By Patient'), ) app_config = AppHookConfigField(FaqConfig) url = models.CharField(blank=True, default='', max_length=250) count = models.CharField(blank=True, default='', max_length=250) start = models.CharField(blank=True, default='', max_length=250) status = models.CharField(choices=TYPES_CHOICES, max_length=10) and my view.py is like this class IndexView(AppConfigMixin, generic.ListView): model = Entry template_name = 'faq/index.html' def get_queryset(self): qs = super(IndexView, self).get_queryset() return qs.namespace(self.namespace) I don't want to pass the entire model to my html file, in my view file I want to create a value with value = url+count+start and pass this to my html. Any idea how to do this Thanks in advance -
Passing a Django form to a template tag
I'm trying to render a Django form on every page of my Wagtail site in a jQuery slideout box. I've created a template tag that is currently rendering the box, but the form is not showing up. I'm thinking that I'm incorrectly passing the form variable. My template tag file looks like this: from django import template from django.shortcuts import render, redirect from django.template.loader import get_template from django.core.mail import EmailMessage from django.template import Context from .forms import DemoForm register = template.Library() @register.inclusion_tag('demo_form.html') def book_a_demo(request): form = DemoForm if request.method == 'POST': demo_form = form(data=request.POST) if demo_form.is_valid(): contact_name = request.POST.get('name', '') company_name = request.POST.get('company', '') contact_email = request.POST.get('email', '') contact_phone = request.POST.get('phone', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = Context({ 'contact_name': contact_name, 'company_name': company_name, 'contact_email': contact_email, 'contact_phone': contact_phone, }) content = template.render(context) email = EmailMessage( "Request to Book a Demo", content, "domain" +'', ['example@email.com'], headers = {'Reply-To': contact_email } ) email.send() return render(request, 'demo_form_landing.html') return render(request, 'demo_form.html', {'form': form}) demo_form.html looks like this: {% load static %} <div id="feedback"> <div id="feedback-tab">Book a Demo</div> <div id="feedback-form" style='display:block;' class="col-xs-4 col-md-4 panel panel-default"> <form role="form" action="" method="post" class="form panel-body"> {% csrf_token %} {{ form.as_p }} <button … -
Django 1.3.7 TemplateDoesNotExist error admin/index.html
There are numerous questions asked on this site similar to this one, but I couldn't find one that could explain this particular behavior. I am relatively new to django and ubuntu, so maybe the explanation is simple. This is an old (v1.3.7) django project I'm attempting to migrate to a new server. Here is the full error I am getting in my apache log: TemplateDoesNotExist at /admin/ admin/login.html Request Method: GET Request URL: http://131.212.123.7:26080/glrimon/admin/ Django Version: 1.3.7 Exception Type: TemplateDoesNotExist Exception Value: admin/login.html Exception Location: /.../leave_beave/lib/python2.7/site-packages/django/template/loader.py in find_template, line 138 Python Executable: /.../leave_beave/bin/python leave_beave is the name of my virtualenv. I received this same error for an earlier problem, and I solved it by creating a symlink from the templates directory in question (.../python2.7/site-packages/lib.../package/templates) to my /project_dir/templates directory, which is the one configured as my template directory in settings.py: TEMPLATE_DIRS = ( os.path.join(PATH, 'templates'), ) I did this at the time, since I thought it was a one-off hack solution sort of thing, but now I'm getting the same error for attempting to access the admin page of my site (http://.../admin/). This tells me I'm going about this wrong. I suppose I could add a symlink to every template directory …