FAQ Database Discussion Community


git fork from certain tag version - requirements.txt

django,git,github
I want to fork one github project code, but not from master branch, but from older release. Reason: I want to edit one place in the code in my fork version and put the url of this tag version into my requirements.txt so that pip install -e git+https://git_url_to_my_form_in_this_tag_version works. I...

DjangoCMS 3 Filter Available Plugins

django,django-cms
In the DjangoCMS3 documentation it says you can configure DjangoCMS behavior using CMS_PLACEHOLDER_CONF in your settings. For instance: CMS_PLACEHOLDER_CONF = { 'right-column': { 'plugins': ['TextPlugin', 'PicturePlugin'], ... This would make TextPlugin and PicturePlugin to be the only two plugins available inside any placeholder called "right-column". It works, but what if...

Callable in model field not called upon adding new object through Django admin

django,django-models,django-admin
In https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.default we read that the callable of a default field value is called, every time a new object is created. In my model I have: when_first_upload = models.DateTimeField(default=datetime.datetime.now()) When in the admin page I create a new object I always get the same datetime, as if the callable is...

Get the first image src from a post in django

django,django-templates,django-views
I have a model to write blogs. In that I'm using a wysiwyg editor for the Blog's descritpion, through which I can insert an image within the description. class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField(default=timezone.now) publish = models.BooleanField(default=False) In the admin it looks like this:...

Where I should put my python files in a django framework? [duplicate]

python,django
This question already has an answer here: Project design / FS layout for large django projects [closed] 6 answers forgive the trivial question but I have just started learning how to use the django framework. When I create my new web site app (e.g mysite) I get the following...

Create angular page in Django to consume data from JSON

angularjs,django,django-templates
In an angular controller I have a list of items: app.controller('MainController', ['$scope', function($scope) { $scope.items = [ {"foo":"bar 1"}, {"foo":"bar 2"}, {"foo":"bar n"} ] }]); The following html page, based on angular, displays a list of item: <!DOCTYPE html> <html> <head> <title>list</title> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

Switch Case in Django Template

python,django,django-1.3
I'm trying to put different template for different category based on category ID. I'm using Django 1.3. Switch case is not working with Django 1.3, I get this error: Invalid block tag: 'switch', expected 'endblock' or 'endblock content' but switch case had been correctly closed. Here is my code: {%...

django rest post return 405 error code

django,django-rest-framework
I am using django with rest framework and I try to test POST on existing object but I keep getting 405. my ViewSet looks like this: class Agents(viewsets.ModelViewSet): serializer_class = serializer.AgentSerializer model = serializer_class.Meta.model .... and in the urls: router = routers.SimpleRouter() router.register(r'rest/agents', api_views.Agents, "Agent") ... urlpatterns += router.urls I...

Strange Django ''BEGIN' - PARAMS = ()" query

python,django,sqlite
I'm optimising my code which was making far too many queries on start. I'm getting to almost the bare minimum now, and have started coming across the following: QUERY = 'BEGIN' - PARAMS = () This seems to be used almost every single time and practically doubles the number of...

Django ClearableFileInput - how to detect whether to delete the file

django,django-forms,django-crispy-forms
I'm using Django Crispy Forms for my form with an option to upload an image (ImageField in my Model) The forms renders as I'd expect, with the checkbox to clear an existing file. However when processing the form submission the 'image-clear' checkbox always gives me a 'None' value. image_clear =...

Upload to absolute path in Django

django
I am trying to get upload_to of FileField to be an absolute path rather than relative to MEDIA_ROOT. If I make the path absolute I get a 400 error on post of file. If no leading / it stores under MEDIA_ROOT. The uploaded document needs to be held securely and...

Why is Django widgets for TimeInput not showing

django,django-forms,django-templates,django-views
I'm trying to create a TimeInput field in a form and noticed that the widget isn't showing correctly. But when I check the localhost:8000/admin, I see the widget showing up correctly. My code is as follows. For models.py, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

Django Form output/Error Checking issue

django
I have a model that contains an integer field class myModel(models.Model): number = models.IntegerField() Whenever I display or input data to this model I want to do so in octal. When I populate my edit form I do this: number = oct(numberObject.number).replace('Oo','') When I go to the edit form it...

django error TemplateDoesNotExist

python,django,django-templates
I am new to Django and just follow the Django official document, but here is a problem. I create a new Django project with Django 1.8.2 + PyCharm 4.5.1 + Python 3.4.3 + Windows 8.1 - mysite - main - migrations __init__.py __init__.py admin.py models.py tests.py views.py - mysite __init__.py...

django 1.8 CreateView Error

python,django
I'm using django 1.8 to create a login form. But the template containing registration form does not render properly. my views.py class SignUpView(CreateView): RegistrationForm = UserCreationForm fields = ['username','password1','password2'] model = User template_name = 'accounts/signup.html' my forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from crispy_forms.helper import FormHelper from...

sorl-thumbnail: Creating a thumbnail inside a for loop in a template

django,sorl-thumbnail
I am trying to create a thumbnail with the size of 100x100 px from an image. I am using a for loop, and the for loops works and the image is rendered but for some reason when I am trying to create a thumbnail it doesn't work. Here is my...

Stuck with nested serializer using Django Rest Framework and default user

django,api,rest,django-rest-framework,serializer
The models and serializers are described in the pastebin: http://pastebin.com/ZxzxWY7V In my database I have a user which also has a member profile and a set of credentials attached to it. Now... when I run this as is and try to pull a user using the AuthUserModelSerializer I get the...

Django migrations missing way to declare “needed_by”?

django,dependencies,database-migration,django-south
If you have two apps: core_app plugin_app The core does not need the optional plugin. Up to now we used south and could use needed_by if a migration of the plugin needs to run before a migration of the core app. I could not find something in the docs: https://docs.djangoproject.com/en/1.8/topics/migrations/...

upload_to dynamically generated url to callable

python,django,models
I've seen a lot of post about this problem without really understanding how to solve it. I have this model: class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField() I'd like to have my image saved to media root following this template: <name>/logo/<filename> At first glance, I would like...

Django include template tag alternative in python class

python,django,django-templates
I know there is a Django template tag that allows to include other templates like so: {% include 'template.html' %} I am wondering if I could do the same, but in a separate python class (not in the HTML template)? I know that for example the url tag has an...

Does Django implement user permissions in databases with models?

python,django,orm,django-admin
In a typical database, admin can assign users and can create tables which can be accessed by only a particular set of users or groups. One can also create queries that can be made by certain users in a database like MySQL. Does Django provide any such functionality or is...

Django: Add space after a comma in a string using javascript in a template

javascript,django
In an html template I get a variable's value from a select drop down list like one or more,two In need to add an extra space after the comma and I need my string to be one or more, two My current javascript is: $('#id_diag-diagnosis_option').change(function () { var value =...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing
I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views
I have this model in models.py: class Life_events(models.Model): patient = models.ForeignKey(Demographic) HSCT_date = models.DateField('HSCT date',null=True,blank=True) HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True) partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True) date_of_input= models.DateField(null=True,blank=True) def __str__(self): return str(self.patient) My forms.py contains: class LifeEventsForm(forms.Form): def __init__(self,...

Is there a way to install django with pip to point to a specific version of python in virtualenv

python,django,pip,virtualenv
I have a system with CentOS installed. It currently runs python2.6, but python2.7 is also installed. I want to run django 1.7, which is also currently installed. If I run django outside of a virtualenv, it is using python2.6 by default. I didn't install it myself. What I assume is...

Django view: Convert unicode retrieved from db to string

python,django
In django view I retrieve data from a table in MySQL db using diag_patient = Diagnosis.objects.get(patient=myid) diag_val = diag_patient.diagnosis_option print "diagnosis value=", diag_val When I print diag_val I get [u'One', u'Two'] I want to convert it to a string equal to One, Two. Can you help me please?...

Custom CMSPlugin migrations in Django 1.7

django,django-cms,django-migrations
I'm using Django CMS 3.1 with Django 1.7.8. I'm trying to upgrade an old project to these respective versions but I'm hitting a brick wall with a couple of my custom-written CMSPlugin-inhereting plugins. Django won't migrate any models. django.db.migrations.state.InvalidBasesError: Cannot resolve bases for [..My Models..] The models are defined as...

How can I fill the table? (Python, Django)

python,django
I faced with a problem: I have 4 lists with data. And I need to fill the table with this data. It is the example of table: So, as you already understood, at first column must be data from a first list, at second - second list, ... I tried...

how to compare only date from a model's datetimefield with current date?

python,linux,django,web,frameworks
I want to use Model.objects.filter(datetime_lte=datetime.datetime.now.date()) How exactly can I achieve this? I am using django 1.6.5. I want only records of current date. This will give all previous day's records also

How to get simple ForeignKey model working? (a list of class in another class)

django,django-models,django-queryset
I tried to figure this out on my own :( couldn't quite get there. Pls take pity. . . I'm trying to represent exercise data (a start time an end time and many--an undetermined number of-- heart rates) this is the model I have set up: class HeartRate(models.Model): timestamp =...

Django UnicodeDecodeError in model object

django,encoding
this is another UnicodeDecodeError I'm dealing with in django. I can't find the way to solve it. I'm trying to create an object: nivel_obj = Nivel.objects.filter(id=nivel_id) nueva_matricula = Matricula(nivel=nivel_obj, ano_lectivo=ano_lectivo, alumno=a) nueva_matricula.save() The "Matricula" object has a "nivel_obj" that is a Foreign Key. The "nivel_obj" has a name that is...

django cannot multiply non-int of type 'str'

python,django
I'm a beginner in python & django coding. I have this model : class QuoteRow(models.Model): (...) quantity = models.IntegerField(blank=True, null=True) unit_price = models.DecimalField(max_digits=12, decimal_places=6, blank=True, null=True) And these lines in another model 'Quote' : def _total_amount(self): return QuoteRow.objects.filter(quote=self.pk).aggregate(Sum('unit_price' * 'quantity')) total_amount = property(_total_amount) In the shell : q=Quote.objects.get(pk=2) // valid...

Permission denied Setuptools

python,django,curl,setuptools
I'm trying install setuptools in my Mac, but when I run command curl https://bootstrap.pypa.io/ez_setup.py -o - | python show a message telling: Processing setuptools-17.1.1-py3.4.egg Removing /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/setuptools-17.1.1-py3.4.egg Copying setuptools-17.1.1-py3.4.egg to /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Adding setuptools 17.1.1 to easy-install.pth file error: [Errno 13] Permission denied:...

Algoritm to sort object by attribute value without allowing gaps or duplicates

python,sql,django,sorting,django-orm
I have a agenda with multiple dates, each date can contain 0 > ... items. Items can be sorted by position, positions should be Integer values without gaps and duplicates. class Item(models.Model): date = models.DateField() position = models.IntegerField() def move_to(position): qs = self.__class__.objects.filter(date=self.date) # if the position is taken, move...

How to get a Django Prepopulated Model Form for User to *not* populate password

django,django-forms,modelform
I have a ModelForm for the User model that I want to use to allow the user to update some of their settings (first name, last name, email, and, of course, password). It's a very basic form and I did the UserForm(instance=user) so the user would see their current values....

How can i hook into django migrations for django 1.8

python,django,migration
I am using django 1.8. Now i need to add some custom fields based permisions so i have created a YML file from python models like this description: permissions: ['ADMIN'] award: permissions: ['USER'] Its working fine but my issue if some chnages the field names or reomves some field then...

Django: html without CSS and the right text

python,html,css,django,url
First of all, this website that I'm trying to build is my first, so take it easy. Thanks. Anyway, I have my home page, home.html, that extends from base.html, and joke.html, that also extends base.html. The home page works just fine, but not the joke page. Here are some parts...

Django listview clone selected record

django
From an existing LISTVIEW is there a simple way to create a new record based on existing previos record? 1) select the record 2) call the CREATEVIEW 3) set as initail the data from point 1) would this be possible and which is best? A) Get data from 1) by...

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield
I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

django runserver from python script

python,django
Edit:[ I'm using Djagno 1.8 ] The normal way to start the Django server is to run the following command from a terminal or a bash script python manage.py runserver [Ip.addr]:[port] e.g. python manage.py runserver 0.0.0.0:8000 How can I start a Django server from a python script ? One option...

Django template not found in main project directory error

python,django,templates
I am getting a 'template not found' error, although I've set up a correct template hierarchy (or so I thought) . ├── manage.py ├── twinja │   ├── admin.py │   ├── admin.pyc │   ├── __init__.py │   ├── __init__.pyc │   ├── migrations │   │   ├── __init__.py │   │   └── __init__.pyc │   ├──...

DRF Update Existing Objects

django,django-rest-framework
I'm new to DRF and python so go easy on me... I can successfully get the RoadSegment objects, but I cannot figure out how to update an existing object I have the following model: class RoadSegment(models.Model): location = models.CharField(max_length=100) entryline = models.CharField(unique=True, max_length=100) trafficstate = models.CharField(max_length=100) With the following serializer:...

Django and GeoDjango database backend

mysql,django,spatial,geodjango
I am using a Django app with MySQL database backend and I want to implement GeoDjango I have to change backend to: django.contrib.gis.db.backends.mysql I don't know if that is simple as it?...

attempting to alter data via POST and ajax in django not working

jquery,ajax,django,post
I want to be able to click a button that will change data using ajax (jquery). Here is what I am doing now: html/js: <button onclick="alterData('some sort of data')">click me!</button> function alterData(someInput){ $.ajax({ type: 'POST', url: '/home/alter/', data: {someInput: someInput}, }); } urls.py: urlpatterns = [ ... url(r'^alter/',views.alter), ... ]...

'unicode' object has no attribute 'get' Django beginner

django,python-2.7,django-forms
I have a very simple code in Django and I've this error which comes everytime. The content of the form is well saved in the model but this error shows up when I want to use reverse: 'unicode' object has no attribute 'get' There is my code: views.py: class PastaView(View):...

Django add an attribute class form in __init__.py

python,django,forms,django-forms
My form class from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) My app file __init__.py from django import forms from my_app.forms import Form from captcha.fields import ReCaptchaField def register(form): form.captcha=CaptchaField() register(Form) Code in __init__.py add an attribute captcha but it is not on the page. I...

Difference between django.contrib.auth.login and django.contrib.auth.views.login

django,authentication
What's the difference to use django.contrib.auth.login or django.contrib.auth.views.login? First in __init__.py and second in views.py I saw that code and it differs from each other. Same is with some other views, for example 'logout'. As I understand, django.contrib.auth.views.login is used when I want to redefine some parametrs of that view?

How can I resolve my variable's unexpected output?

django,python-2.7
I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

Use django to expose python functions on the web

python,django
I have not worked with Django seriously and my only experience is the tutorials on their site. I am trying to write my own application now, and what I want is to have some sort of API. My idea is that I will later be able to use it with...

deploy django under apache mod_wsgi waiting for localhost

python,django,apache,mod-wsgi
I am deploying a Django project on Apache. and after configuration, I open the "localhost" in the browser, and nothing showed up and the status bar just keep saying "Waiting for localhost". Here is some info. Environment: OS: ubuntu Python: 2.7.3 Django: 1.8.2 Apache: 2.2.21 Django project: /var/www/ocr_service Apache virtualhost:...

No such table as django_site

django,django-admin,django-settings
I am following from the docs of django-disqus to use it in my project. I have installed it in my settings, with other needed settings (API key and short name). But when I try to run these commands: >>> from django.contrib.sites.models import Site >>> Site.objects.all() I am getting an error:...

pass variables to http404 django

python,django
I am trying to pass variables to the 404.html template. I am able to call 404.html but not able to pass any values. How can I do this? I'd like to have something like this. raise Http404({'error', 'acb_error') ...

Modify WSDL in soap webservice with spyne of python

python,django,soap,wsdl,spyne
I am develeping with django and python , and I need publish 1 service with SOAP with 2 operations. For this task I chose the spyne library: http://spyne.io/#auxproc=Sync&s=aux Because apparently is easy to understand and start to develop. I did the first example and was fine, even I developed my...

How to save a form which has been generated by overriding __init__?

django,forms,django-forms
I have a form - class PermissionForm(forms.Form): def __init__(self, *args, **kwargs): super(PermissionForm, self).__init__(*args, **kwargs) permissions = Permissions.objects.all() for permission in permissions: self.fields[permission.name] = forms.CharField() Now since I don't know the field names, so how do I write the save method for this form?...

Django MySQLClient pip compile failure on Linux

python,linux,django,gcc,pip
Django documentation as of v1.8 recommends using mysqlclient connector for the framework. I'm attempting to pip install the package on Ubuntu 14.04 with Python 3.4 and running into a GCC error that I'm unable to find reference to. I'm not an expert on compiling software, so was hoping somebody can...

Django: CSS not extended for some pages?

python,css,django,extend
I'm trying to learn Django using the online version of the "Test-Driven Development with Python" book. I have a base.html file and home.html and list.html file. Now, CSS works fine for home.html, but not at all for list.html! They both extend their CSS from the base.html file, so why is...

How to list objects in many to many Django

django,many-to-many,django-queryset
Considerer this model class Dealership(models.Model): dealership = models.CharField(max_length=50) class Ordered(models.Model): customer = models.ForeignKey("Customer") dealership = models.ManyToManyField("Dealership") status = models.CharField(max_length=2, choices=status_list, default='p') I try $ ./manage.py shell >>> from new_way.core.models import Ordered, Dealership >>> q = Ordered.objects.all()[:5] >>> [i.dealership for i in q.dealership.all] And generate error Traceback (most recent call last):...

Django: show newlines from admin site?

python,html,django,newline,textfield
This is probably very simple. My database objects have a TextField. Now, when I add the contents of the TextFields to an html paragraph, there are no new lines. How can I make Django show those newlines? Thank you!

Customize change_list.html in django admin

python,django,django-admin
change_list.html has Action part where a user selects an action and applies it on the selected items(queryset). What I am trying to do is the following: 1. Add an additional <select> box near Action select box 2. Add an additional action which will use the value of the added select...

Django, creating variables in a Template and assigning a value

python,django,templates
I am trying to create a template in Django. In that template i have: dato which contains a dictionary like this {"Name":"Someone","Age":"23"} and propiedad which contains a dictionary like this {"parameterName":"Name"}. I can make {{propiedad.parameterName}} and get the value Name. After that i would like to store that value in...

How to work with django-rest-framework in the templates

json,django,django-templates,django-rest-framework
Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it. model: class Day(models.Model): date = models.DateField(default=date.today) class ToDo(models.Model): date = models.ForeignKey(Day) name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) normal view: def home(request): days = Day.objects.all() return render(request, 'test.html', { 'days':days })...

Scrapy Memory Error (too many requests) Python 2.7

python,django,python-2.7,memory,scrapy
I've been running a crawler in Scrapy to crawl a large site I'd rather not mention. I use the tutorial spider as a template, then I created a series of starting requests and let it crawl from there, using something like this: def start_requests(self): f = open('zipcodes.csv', 'r') lines =...

Django Rest Framework - how to get Http header information in urls.py

python,django,django-views,django-rest-framework,django-urls
I am making a Django-based API and here is my urls.py. from django.conf.urls import include, url api_version = "v1" urlpatterns = [ url(r'^v1/', include( "api."+ api_version +".urls", namespace=api_version )), ] What I want to do is to retrieve API version from http accept header. I tried to use django.http.HttpRequest module,...

Show message when there's no excerpt - Django templates

python,django,django-templates,django-template-filters
I have this field on a Django template: <p class="border_dotted_bottom"> {{ expert.description|slice:":300" }} <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>.... </p> If this object (user) has no 'decription' (a text field) it shows the word 'None', I need to get rid of that, maybe if he doesn't...

Display django runserver output from Vagrant guest VM in host Mac notifications?

python,django,osx,notifications,vagrant
I can think of many ways to skin this cat, and Googling hasn't shown an elegant solution either. Does anyone have an easy / elegant way to forward the output from Django's runserver command in a terminal connected to a guest Vagrant VM to the host to display to Mac's...

django-admin startproject not working with python3 on OS X

python,django,osx,python-2.7,python-3.x
I have python3 installed with Django 1.8.2 on Mac OS. There is also python 2.7 installed by default with the OS. When trying to run startproject I get - $ django-admin startproject mysite Traceback (most recent call last): File "/usr/local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line ImportError: No...

Tell Travis to skip a test, but continue to include it in my main test suite?

django,travis-ci
I am using Django 1.8 and I have a management command that geocodes some items in my database, which requires an internet connection. I have written a test for this management command. However, the test runs the script, so it also requires an internet connection. After pushing the test to...

How to add capital to django-cities-light country model?

python,django,timezone,countries,django-countries
I'm using django-cities-light (lighter version of django-cities) with Django 1.8.x. It defines the abstract models of Country, Region/State and City, so that we can extend and add custom fields. For example, we can add timezone to city by writing a post_import signal handler as explained here. Likewise I need to...

How to use template within Django template?

python,html,django,templates,django-1.4
I have the django template like below: <a href="https://example.com/url{{ mylist.0.id }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... (the actual template is quite big) It should be used 10 times on the same page, but 'external' html elements are different: <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> *django...

No module named http_client error when trying to run django with django rest framework

python,django,rest
I am trying to create a simple API using django rest framework. In the view i have the following code. from django.shortcuts import render from moviestash.models import Movie from moviestash.serializer import MovieSerializer from rest_framework import generics #List all movies and add movies class MovieList(generics.ListCreateAPIView): queryset = Movie.objects.all() serializer_class = MovieSerializer...

Django REST tutorial DEBUG=FALSE error

python,django,django-rest-framework
I'm trying to learn to use the django REST framework via the tutorial. I've gotten to the section "Testing our first attempt at a Web API". When I start the server, I get: System check identified no issues (0 silenced). June 15, 2015 - 00:34:49 Django version 1.8, using settings...

Passing checkboxes values to view in django

django,checkbox,django-templates,django-views
I have a table with some database data <table id="id_list_table" class="table table-condensed"> <caption>Inputs list</caption> <thead> <tr> <th>#</th> <th id="input">Input</th> </tr> </thead> <tbody id="fbody"> {%for input in InputsAll%} <tr> <td>{{ input.input }}</td> <td> <a class="btn btn-primary btn-xs" href="{% url 'edit' %}?input_num={{input.id}}" id="edit">edit</a> <a class="btn btn-danger btn-xs" href="{% url 'delete'...

Django: How to add a new button in admin/index.html for specific model

django,django-admin
I am overriding the admin/index.html content block. I have this inside: {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}"> {% if model.admin_url %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} {% if model.add_url %} <td><a href="{{ model.add_url }}"...

django get the social token form allauth

python,django,facebook
Hello i tried to get the social token from the DB but i get this error. I can't find any answer to this and tried everything i can think of. Please if anyone knows how to fix this. NameError at / name 'user' is not defined Request Method: GET Request...

Button updates text of first element instead of selected element

javascript,jquery,html,django,django-templates
When I select the "Like" button, the button updates properly. However, the "like count" updates the count for the first image only, instead of the image I selected. Any ideas how to make only the selected image's like count update as the button does? Thank you in advance! html: {%...

Specify a filename suffix with easy-thumbnails in django

django,easy-thumbnails
I am using the easy-thumbnails lib in django to create thumbnails. However, I can't figure out how to override the thumbnail naming process. At the moment the lib is appending the thumbnail size to the file name, but I would like to specify a custom name e.g. _large. How can...

python-requests does not grab JSESSIONID and SessionData cookies

python,django,session,cookies,python-requests
I want to scrape a pdf file from http://www.jstor.org/stable/pdf/10.1086/512825.pdf but it wants me to accept Terms and Conditions. While downloading from browser I found out that JSTOR saves my acceptance in 2 cookies with names JSESSIONID and SessionData but python-requests does not grab these two cookie( It grab two other...

How can I customize a drop-down list form element in django?

python,django,forms
I am creating an application in django and I have the next problem: I create a form class in django, as I show here: class A(forms.ModelForm): class Meta: model = ModelA This way, the form will show a drop-down list with ALL the elements in the modelA, but what I...

Sending parameters to view when submitting a form in Django

python,django
I need to send some parameters when submitting a form in Django and I'm not sure how to do this. Right now I have a form inside a page(Page A) allows filtering-- so my url for that page looks like this example.com/view-students?grade=5&teacher=smith Inside that page I have a pop-up that...

Django ManyToManyField in admin value list

django
class Schedule(models.Model): landing = models.ManyToManyField(Place, related_name="landing_schedule", null=False) def __unicode__(self): return u'%s | %s' % (self.departure, self.landing) How can i display the values inside admin for the ManyToManyField ?...

Combining multiple django apps into one view, what am I doing wrong?

python,django,django-templates,django-views
I have a Django project with multiple apps that I need to combine and render as a single page. I have the following sections of code: One of the views I'm trying to aggregate with other views: class ResourceList(generic.View): model = Submissions template_name = 'url_list.html' def get(self, request, *args, **kwargs):...

No module named _mysql - Google App Engine & Django

python,mysql,django,google-app-engine
First of all I'm working on Mac (Yosemite). I've created a simple Django project with Google App Engine. I'm using Cloud SQL in production and MySQL in development environment as recommended in the docs. The project uses virtualenv on my dev machine of course. I can run the project with...

User registration endpoint in Django Rest Framework

django,django-rest-framework
I'm using Django rest framework. I've written the following view to register a new user to the system. @api_view(['POST']) @csrf_exempt @permission_classes((AllowAny, )) def create_user(request): email = request.DATA['email'] password = request.DATA['password'] try: user = User.objects.get(email=email) false = False return HttpResponse(json.dumps({ 'success': False, 'reason': 'User with this email already exists' }), content_type='application/json')...

Update queryset attribute value without losing order on that attribute

python,django,django-models
class Foo(models.Model): value = models.IntegerField() class Meta: ordering = ('value',) Consider this queryset: [<Foo pk=1 value: 0>, <Foo pk=3 value: 2>, <Foo pk=2 value: 5>] What would be a good way to update the queryset to look like this: [<Foo pk=1 value: 0>, <Foo pk=3 value: 1>, <Foo pk=2 value:...

Trying to write a unit test for file upload to a django Restless API

python,django,rest,file-upload,request
I'm writing a fairly small lightweight REST api so I chose restless as the quickest/easiest support for that. I didn't seem to need all the complexity and support of the django-REST module. My service will only received and send json but users need to upload files to one single endpoint....

django and python manage.py runserver execution error

python,django,manage.py
When I execute python manage.py runserver command for my django_test projects I get following error: System check identified no issues (0 silenced). June 14, 2015 - 20:43:03 Django version 1.8.2, using settings 'django_test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "manage.py",...

Django: Store multiple & dynamically ordered model sequence

python,django,django-models
Lets say, a user has video clips and images, both of them with their corresponding model, VideoClipModel and ImageModel. Now i'm adding a new functionality where a user can combine clips and images to create a "final" video. Now what i need is to create a model where i can...

How do I loop through a nested context dictionary in Django when I have no idea the structure I will recieve

django,django-templates,django-views
I have a dictionary I am passing to a template that looks something like this: {'leasee': {'respond': {'hour': True, 'day': True}, 'contact': {'phone': True, 'facebook': True, 'email': True, 'other': True, 'text': True}, 'licence': '987654321', 'help': {'beautySupplyProvider': True, 'photographer': True}, 'phoneNumber': '12345678910', 'name': 'Chris', 'certifications': {'yes': True, 'long': 'All of them'},...

Django TemplateDoesNotExist Error on Windows machine

python,django
I have been following the tutorial for Django Tango with Django I was trying to add a template as instructed on the link. I am working with Python 2.7, Django 1.8 on a windows 7 machine. Below is the error that I get: TemplateDoesNotExist at /rango/ rango/index.html Request Method: GET...

Add field to django ModelForm that are in the model but not in the form

python,django
I have a django model and a ModelForm. The model has about 10 fields, but I only want to show a few with the ModelForm for the user. So I have something like this: class Create_EventForm(ModelForm): class Meta: model = Event fields = ['event_name','event_datetime','event_venue','event_url','event_tags','event_zip','event_category','event_description'] However, I can't create an object...

Please help me decipher a traceback for “ValueError: invalid literal for int()” in my models

django,django-models,django-middleware
I am trying to create a list of ProductPart objects where ProductPart.part matches the value of an instance of Variety.variety_name. Here is a demonstration of my problem. > v = Variety.objects.get(id=2) > p = ProductPart.objects.get(id=1) > v.variety_name 'Non Pareil (Inshell)' > p.part <Variety: Non Pareil (Inshell)> > a = ProductPart.objects.values().filter(part=v.variety_name)...

Django Rest Framework Pagination Settings - Content-Range

django,pagination,django-rest-framework
I am using DRF as server side to a Dojo/Dgrid web application. Dojo needs a content-range or range response from the server. Currently it doesn't send any and so the pagination for dgrid.grid isn't working properly. In the DRF documentation it states" Pagination links that are included in response headers,...

Operational error while using stripe with profile app

django,python-2.7,django-templates,stripe-payments
I am trying to embed Stripe in custom profile app and using django-registration package for registering users. I need to get users registered and then generate a Stripe ID for new users but getting the error below: OperationalError at /accounts/login/ no such table: profiles_userstripe My complete code for Profile app...

Django block inclusion not working. What did I miss?

django,django-templates
In my base.html file I have this: {% block menu %}{% endblock menu %} and in base_menu.html I have this: {% extends "base.html" %} {% block menu %} <nav class="navbar navbar-inverse navbar-fixed-top"> ... stuff ... </div> {% endblock menu %} I would expect the menu html to show where the...

Detecting first 20 chars in string in mark_safe()

python,django
How can I add non breaking space(&nbsp) after first 20 chars of my_string? my_string = "12345678 912345678 15235213523 23512351235" test = mark_safe(re.sub( #after first 20 chars add &nbsp, r' \1&nbsp;', my_string, flags=re.UNICODE, )) ...

Django file upload took forever with Phusion Passenger

django,apache,file-upload,passenger
I have a Django app deployed using Passenger (I did not choose mod_wsgi because mod_passenger is already there and being used). When I uploaded an MP3 file (900 kB), Google Chrome displays upload % which reached 100% pretty fast but then it took forever for the resulting page. The database...

Why isn't Celery starting up?

django,celery
I have a Django app, which I've configured to use Celery. It works fine using the dev settings from the tutorial. Now I'm trying to get it working with a daemonized server. I have Celery installed in a virtualenv, and am starting it (from the project's root directory) as follows:...

Django runserver not serving some static files

django,python-3.x
My local testing server for Django v1.8.2 on Windows 8.1 is only serving certain static files. Others are giving a 404 error. #urls.py - excerpt urlpatterns = [ url(r'^$', views.index) ] + staticfiles_urlpatterns() #settings.py - excerpt INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users' ) STATIC_URL =...

Django: Handling several page parameters

python,django,list,parameters,httprequest
I have several possible parameter to process in a page. Assume x0, x1, x2,..., x1000. It seems awkward to get and process them one by one by request.GET.get('x0'), request.GET.get('x1'), ... Any idea to put them in a list, so that they can be processed in a loop....

Display only some of the page numbers by django pagination

django,django-pagination
I am using the django paginator in the template. Its working ok, but not good when there's large numbers of pages. views.py: def blog(request): blogs_list = Blog.objects.all() paginator = Paginator(blogs_list, 1) try: page = int(request.GET.get('page', '1')) except: page = 1 try: blogs = paginator.page(page) except(EmptyPage, InvalidPage): blogs = paginator.page(page) return...