Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to copy a PlaceholderField in Django CMS
We are using Django CMS on our site with the PlaceholderField on a custom model. I'm looking to add Draft / Timed Edits to a custom model that uses the PlaceholderField. But as part of that I need to be able to copy the PlaceholderField. I saw this is possible in the web interface, and tried to use the PlaceholderAdminMixin class and it's copy_plugins method, but it looks to be too tied to the web site (ran into issues faking the 'admin_site' variable :) I need to do this outside of the web interface/just in code. Anyone have any suggestions/thoughts on how to best do this? Thanks for your time! -
Automatic rerun of flask app on localhost
Is there a way to automatically rerun flask app on localhost on every code edit/save? In order to abandon the need for stopping local server and doing flask run again. If not, how can I make such a 'daemon' program myself ? -
Django Migration Error without DateTime field
I tried to insert a new field in my model and I got a DateTime Migration error, So I deleted those two fields and am trying to run "migrate" function which is not working , Make migration still work though. Below is my Models.py file. from django.db import models from django.core.urlresolvers import reverse class Invoice(models.Model): active = models.BooleanField() bu_field = models.CharField(max_length=10) invoice_name = models.CharField(max_length=500) sow_name = models.CharField(max_length=500) probability = models.IntegerField() sow_type = models.CharField(max_length=50) sow_start_date = models.DateField() sow_end_date = models.DateField() project_id = models.CharField(max_length=500) project_manager = models.CharField(max_length=500, null=True) po_number = models.IntegerField() sow_value = models.DecimalField(max_digits=8, decimal_places=2) current_month = models.CharField(max_length=20) current_year = models.CharField(max_length=5) month_value = models.DecimalField(max_digits=8, decimal_places=2) q1_value = models.IntegerField() q2_value = models.IntegerField() q3_value = models.IntegerField() q4_value = models.IntegerField() total_value_ofyear = models.IntegerField() probability_month_value = models.IntegerField() def __str__(self): return self.invoice_name def get_absolute_url(self): return reverse("invoice:detail", kwargs={"id": self.id}) There are no new fields , everything is back as it was but not i am getting this error. -
Django-admin: MoneyField doesn't show currency
I have a model Product and model Price. The Price has a ForeignKey(Product...) and original_price and eur_price which are MoneyField's (Django-money). So one Product object can have multiple Price objects related. I tried to inline the Price objects into Product model admin which works correctly, but when I set original_price and eur_price to be readonly_fields, it shows amounts but not currencies. This is without making them readonly: class PriceInline(admin.TabularInline): model = Price max_num = 10 #readonly_fields = ('original_price','eur_price') class ProductAdmin(admin.ModelAdmin): inlines = [ScanInline,] And this with readonly: class PriceInline(admin.TabularInline): model = Price max_num = 10 readonly_fields = ('original_price','eur_price') class ProductAdmin(admin.ModelAdmin): inlines = [ScanInline,] Do you have any idea how to show currency there if those fields are readonly? -
Appending html with a django link in ajax
I have an ajax function that adds data to my python database without refreshing the page (I'm using the django web framework). I return the data and add this to my template with a html append to avoid a page refresh. However, I want to link this newly appended data to the actual record it belongs to. So when a user clicks the 'newly added row' they can go to the record view and add things to it. So this is where I have a problem... I can't just throw in a django link without getting errors... Here is my ajax: $( document ).ready(function() { $('#timesheet-form').on('submit', function(event){ event.preventDefault(); console.log("add a timesheet"); createtimesheet(); }); function createtimesheet() { console.log("create timesheet is working!") $.ajax({ url : "{% url 'tande:createtimesheet' %}", type: "POST", data: { datestart : $('#start').val(), dateend : $('#end').val()}, success : function(json) { var html = '<tr><td>'+json.startdate+'</td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>'; console.log("success"); $('#timesheet-list').append(html); }, error : function(xhr,errmsg,err) { // what to do when there is an error } }); }; }) What I would want to do is something like this - even though it's hideous: var html = '<tr><td><a href='{% url "tande:timesheet" timesheet_id=sheet.id %}' class="class2">'+json.startdate+'</a class="class2"></td><td>'+json.enddate+'</td><td>'+json.status+'</td><</tr></br><p>'+json.error+'</p></br>'; But I can't put a django link in... Are … -
Django - Checking if objects exists and raising error if it does
I need to check if an object exists in a table. If the object doesn't exist I want to save it, if it does exist I want to refresh the page and tell the user that the identifier (quote number) already exists. I have this example code: def some_method(request): if request.method == 'POST': form = SomeForm(request.POST) if form.is_valid: quote = request.POST.get('quote') if SomeModel.objects.get(quote_number = quote).exists(): refresh with error #not sure how to do else: save object #I can do this part The problem I am running into is that when I check if the object exists (and it does) then the code will raise an error saying the object doesn't exist before it hits the if. Which means on the webpage is full of coding information rather than the refresh with a message for the user. I want to be able to have a little pop up message or something for the user to enter a new quote number rather than having the developer error page show up. Am I going about this the correct way? -
Django context : local variable referenced before assignment
Good afternoon everybody, I'm getting a little problem with my context variables in my Django project. I have a function which let me to make some processes. Especially some reasearches over my database and display the result. But I have a problem with one variable : folderId I'm getting this error and I don't find a way to overcome it. My function looks like : @login_required def Identity_Researching(request) : ####################### # Display some arrays # ####################### identitys = Identity.objects.order_by("-id") identity = identitys[:3] #The 3 last created forms identity_France = identitys.filter(country=64)[:3] #The 3 last created form with BirthCity = France ############################ # People searching process # ############################ query_lastname = request.GET.get('q1') query_firstname = request.GET.get('q1bis') query_birthday = request.GET.get('q1ter') if query_lastname or query_firstname or query_birthday : query_lastname_list = Identity.objects.filter(lastname__contains=query_lastname, firstname__contains=query_firstname, birthday__contains=query_birthday) title = str(query_lastname + "_" + query_firstname + "_" + query_birthday) ########################################## # Look if people directory already exist # ########################################## url = 'http://demodoc/services/rest/folder/listChildren?folderId=8552450' payload = {'folderId': 8552450} headers = {'Accept': 'application/json'} r = requests.get(url, params=payload, headers=headers, auth=('etatcivil', '100%EC67')) rbody = r.content data = json.loads(rbody) longueur = len(data) i=0 list = [] while i < longueur : if data[i]["name"] == title : list = [data[i]] i = i+1 ############################################ # We have correspondance, … -
Django Flashcard App Database Setup
I'm creating a Flashcard App in Django. It will allow multiple users to study the same deck of cards (Question, Answer, Category). Each card also has a difficulty rating (1 to 4). Of course, the difficulty rating of each card is unique for each user, depending on how many times they get the card right or wrong. How do I go about setting up the database? Do I need to make a new table with a deck for each user? Thanks! -
Concatenate URL link with Django variable
I would like to concatenate my url with a Django variable but I don't find a way to do that. My url link looks like : http://demoged.datasystems.fr/frontend.jsp?docID= and I would like to add after = the following variable : {{ids}} So I tried something like this : <a href="http://demoged.datasystems.fr:8090/frontend.jsp?docID=" + {{ids}} ">Link</a> Have you an idea ? Thank you -
Python manage.py ImportError: No module named django
I can't seem to get my manage.py script to recognize the django module. pip install req/dev.txt installs all of the modules I would expect it to into my my python virtual environment (stored at .venv). I think I've narrowed it down to a problem with either my $PYTHON_PATH or with my pip requirements files. I've looped through sys.path, and I see that one of the values points to a folder in .venv that I can confirm contains the django module. I'm unfortunately at a loss. I've searched through a dozen related questions on Stack Overflow and have yet to find a solution that works. Does anyone have any clues to point me in the right direction? Error message: $ python manage.py syncdb Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/nathan/www/zumo_admin/.venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/nathan/www/zumo_admin/.venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/Users/nathan/www/zumo_admin/.venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/nathan/www/zumo_admin/.venv/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/nathan/www/zumo_admin/.venv/lib/python2.7/site-packages/django/apps/config.py", line 119, in create import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named django Contents of reqs/dev.txt -r common.txt django-debug-toolbar==1.3.2 Contents of reqs/common.txt django==1.8 Fabric==1.10.2 ShopifyAPI>=2.1.5 Sphinx==1.3.1 celery>=3.1.20 django-compressor>=1.5 django-toolbelt>=0.0.1 jdcal>=1.0 … -
Display custom queryset in django list view
views.py class ListSkills(generic.ListView): model = Skill template_name = 'profile/skills_list.html' context_object_name = 'skill_list' def get_queryset(self): return Skill.objects.all().filter(user=self.request.user) My app works like this: localhost:8000/username locahost:8000/username/skills In the skills list view i want to display the skills of the username on the url not the skills of the logged in user. I know .filter(user=self.request.user) will get the skills of the logged in user. any methods to override the filter to filter the skills of the user mentioned in the URL. -
Managing database routers in Django
I am new to Django and am trying to create a simple CRUD for an existing table in a database. The thing is, that database is not local and I do not want Django to create its built-in tables in it -- I want it to create its tables in a local database. The correct way to do that is by using database routers, right? I created an app myapp, and declared the external table I want to write the CRUD for in its models.py. Now, I have written two routers (in two separate files) -- one that routes myapp to the external database (the DataRouter), and another one that routes all other requests to the local database (the SystemRouter). Is that the correct way to do that? Where should I place those files? I have tried placing them in multiple different directories inside my project, but can't make the DATABASE_ROUTERS list in settings.py find them. For example, if I place them in the root directory for the project and make: DATABASE_ROUTERS = ['DataRouter', 'SystemRouter'] I get: ImportError: DataRouter doesn't look like a module path I am really lost. Is that the best way to solve my problem? How do … -
Easy Thumbnails Custome Namer example for django easy_thumbnails
I found one question in StackOverflow. Specify a filename suffix with easy-thumbnails in django It has the answer but i need implementation. how to use in Templates and how to setup function and how to setup in settings.py file. Thanks In Advance. -
django- how to deploy same project different url
i want to develop two project with same look with different data because of that i duplicated my poject as project2. now i have two projects like project1 and project2. i configure like below. if i call www.xyz.com/project2 i am getting project2 result(no problem getting correct result). if i call www.xyz.com/project1 i am getting project2 only not getting project1 result. Help me how to solve this. is there any change require to conf file? apache2.conf Include sites-enabled/ WSGIPythonPath /var/www/project2/blog:/var/www/project1/blog ServerName 107.170.00.04 <Directory "/var/www/"> options Indexes FollowSymLinks AllowOverride None # Require all granted </Directory> /etc/apache2/sites-available/default <VirtualHost *:80> ServerName xyz.com ServerAlias www.xyz.com ServerAdmin xyz@gmail.com Errorlog /var/www/logs/error.log CustomLog /var/www/logs/custom.log combined WSGIScriptAlias /project2 /var/www/project2/blog/blog/wsgi.py <Directory "/var/www/project2/"> Options FollowSymLinks AllowOverride None </Directory> WSGIScriptAlias / /var/www/project1/blog/blog/wsgi.py Alias /static /var/www/project1/blog/static # Set access permission <Directory "/var/www/project1/"> Options FollowSymLinks AllowOverride None </Directory> </VirtualHost> -
Django - model method "keeps" old parameters [duplicate]
This question already has an answer here: “Least Astonishment” and the Mutable Default Argument 29 answers I am unsure if the title is correct because I don't really understand what is happening (but I believe this seems to be the case?). I have a category model which has a ForeignKey to itself (Category). What I am trying to do is get a list of all subcategories. Example: Food -> Fruit, Food.get_subcategories() would give me [Fruit]. I have a model like so: class Category(models.Model): title = models.CharField(max_length = 100) subcategory = models.ForeignKey("self", blank=True, null=True) user = models.ForeignKey(User) objects = CategoryManager() def get_lowest_category(self): if self.subcategory: return self.subcategory.get_lowest_category() return self def get_subcategories(self, out_list=list()): if self.subcategory: if self.subcategory == self: return out_list out_list.append(self.subcategory) return self.subcategory.get_subcategories(out_list=out_list) print(out_list) return out_list And the relevant view part like so: if "search" in request.POST: categories_left = Category.objects.for_title(request.POST["left-search"], user=request.user) categories_right = Category.objects.for_title(request.POST["right-search"], user=request.user) elif "create" in request.POST: Category.objects.create(user=request.user, title=request.POST["title"]) elif "add-subcategory" in request.POST: left = Category.objects.for_id(request.POST["left-category"], user=request.user) right = Category.objects.for_id(request.POST["right-category"], user=request.user) try: new_category = deepcopy(left) new_category.pk = None new_category.save() Category.objects.filter(id=new_category.id).update(subcategory=right) except IntegrityError: print("This combination already exists.") # TODO Template: <p>Search categories form</p> <div id="searchboxes"> <form action="/category/" method="post"> {% csrf_token %} <input type="text" name="left-search"> <select multiple="multiple" id="left-category" name="left-category"> {% for category … -
Django CMS Plugin Development: __init__() got an unexpected keyword argument 'instance'
I am in process of creating Django CMS plugin. So far I have created a form, model and plugin file. I want to save SETTINGS info, but when I go to save it it gives error as mentioned above. Below are details. cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models import CMSPlugin from src.survey.forms import SurveyForm from . import models class SurveyPluginPublisher(CMSPluginBase): """Show Polls entered by Admin.""" cache = False form = SurveyForm model = models.SurveyPluginModel # Must add to show stuff. module = "Survey" name = "Awesome Survey v1.0" render_template = 'survey/_hello.html' plugin_pool.register_plugin(SurveyPluginPublisher) forms.py from django import forms from src.survey.models import Survey models.py class SurveyForm(forms.Form): # all_surveys = Survey.objects.only('name') # surveys = forms.ModelChoiceField(queryset=all_surveys) headline = forms.CharField(max_length=255, help_text='Enter Headline') description = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}),help_text='Enter Description') models.py class SurveyPluginModel(CMSPlugin): name = models.CharField("Survey Name", max_length=255, default='Survey Name', help_text='Enter Survey Name') description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here') def __str__(self): return "Returning some Survey Text" -
systemctl strange error: Invalid arguments
Here's my service file: [Unit] Description=Daphne Interface [Service] ExecStartPre=cd /home/git/hsfzmun/server ExecStart=/bin/bash/ -c "cd /home/git/hsfzmun/server && /home/git/virtualenvs/hsfzmun/bin/daphne -b 0.0.0.0 -p 8001 -v2 config.asgi:channel_layer" Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target When I execute sudo systemctl start daphnei I get: Failed to start daphnei.service: Unit daphnei.service is not loaded properly: Invalid argument. See system logs and 'systemctl status daphnei.service' for details. And the result of systemctl status daphnei.service: * daphnei.service - Daphne Interface Loaded: error (Reason: Invalid argument) Active: inactive (dead) (Result: exit-code) since Mon 2017-02-13 19:55:10 CST; 13min ago Main PID: 16667 (code=exited, status=1/FAILURE) What's wrong? I am using Ubuntu Server 16.04. -
How to translate multiline string in Django models
I use ugettext_lazy as _ , and in a models file my string is represented in this way: s = _("firstline" "secondline" "thirdline") But after running makemessages I found that in the .po file only "firstline" is marked for translation, the rest are absent. I wouldn't like to avoid using multilining, so is there any way to make translation work with this? -
Names with dash does not work in django-haystack
I'm working on an application based on django 1.8 and search engine django-haystack 2.4.1. A strange situation because when I search for the words "New York" - everything is OK. When there is a strange name in the name of the event for example. "Zo-zo on" (with dash) search does not show correct results, only pages isolated instances of letters, for example: "zo ..." I made rebuild_index. -
Is there a best practice way to direct output of the development server to stdout for a front-end dev server?
Let's say I have a a hybrid application (the django templater is required to serve the page with the form widgets, data, etc, however there is still a decent amount of js/ejs/lodash/etc wizardry going on in the front-end). The front-end engineers would prefer to develop on npm's purpose-built front-end dev server, but need the output from the django templater. What is the correct way to simulate a browser request, and direct the page body to stdout (to be picked up by webpack or whatever else is going on in the front-end dev environment)? Should I manage.py runserver, and simulate a request with curl? Or is there a better way? It strikes me as difficult to manage authentication and csrf this way. -
Django request is_ajax return false on admin change_list view
Now I added a button to admin panel like in this which open a modal like this with form that takes a pin and I want to return with a value in an alert or a modal, but when debugging request.is_ajax it returns false, what can I do here is my code and it return 'NoneType' object has no attribute 'has_header' and this is because it returns none because is_ajax returns false This is my template in admin change_list.html .... <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $('#PinInput').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check var csrftoken = getCookie('csrftoken'); var pin = $('#inputPin').val(); $.get({ url : window.location.href, // the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken : csrftoken, pin : pin, }, // data sent with the post request // handle a successful response … -
Error: coercing to Unicode: need string or buffer, long found
I am currently working on a Calendar in python django web framework. I am trying to print something and raising the following error: TypeError: coercing to Unicode: need string or buffer, long found I have seen people with similar problems but not with 'long' and a solution that works.... Here is my code: class HolidayCalendar(HTMLCalendar): def __init__(self, holiday): super(HolidayCalendar, self).__init__() self.holiday = self.holiday_days(holiday) print holiday # for something in holiday: # print something def holiday_days(self, holiday): field = lambda holiday: holiday.start_date.day return dict( [(day, list(items)) for day, items in groupby(holiday, field)] ) I am trying to see what self.holiday is setting as... I tried a for loop aswell because I thought it would be a list of items and it raised the same error. Here is the view that calls the above @login_required def holiday(request): # get persons username # get month and year today date_today = datetime.now() year = date_today.year month = date_today.month # get holiday objects in the current month my_holidays = Holiday.objects.order_by('start_date').filter( Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month) ) cal = HolidayCalendar(my_holidays).formatmonth(year, month) # forms... render template...etc Thanks! -
Filtering a reverse relationship by user, and returning only one object in Django Rest Framework
Given these models: class Product(models.Model): name = CharField(max_length=255) class Order(models.Model): product = models.ForeignKey(Product) user = models.ForeignKey(User) quantity = models.PositiveIntegerField() A user can only have a single Order object per product. I would like an API call to show a list of products, with the user's order where available. Is there a way to do that? The default serialisation lists ALL orders under order_set. I did get a bit ahead with this to filter by user: class FilteredOrderSerializer(serialisers.ListSerializer): def to_representation(self, data): data = data.filter(user=self.context['request'].user) return super(FilteredOrderSerializer, self).to_representation(data) class OrderSerializer(serialisers.ModelSerializer): class Meta: model = Order list_serializer_class = FilteredOrderSerializer So now it only shows the authenticated user's order, but the resulting JSON looks something like [ { "name": "prod1", "order_set": [ { "quantity": 4 } ], } ] i.e. the field is still called order_set and it's a list, while I would like it to be called order and be either an object or null. So I'm not sure where this filtering should take place, nor how to define the field. -
Error while syncdb django-mongo
I am trying to sync mongodb in django framework and have gone through many sites and SO questions but couldn't get a proper answer. When I try to sync database, python manage.py syncdb, (migrate not working) I get following error Creating tables ... /home/shachi/env/local/lib/python2.7/site-packages/django_mongodb_engine/query.py:3: DeprecationWarning: A() queries are deprecated as of 0.5 and will be removed in 0.6. DeprecationWarning) Installing custom SQL ... Installing indexes ... /home/shachi/env/local/lib/python2.7/site-packages/django_mongodb_engine/creation.py:98: DeprecationWarning: 'descending_indexes', 'sparse_indexes' and 'index_together' are deprecated and will be ignored as of version 0.6. Use 'indexes' instead. "Use 'indexes' instead.", DeprecationWarning) Installing indices for auth.Group_permissions model. OperationFailure: command SON([('createIndexes', u'auth_group_permissions'), ('indexes', [{'sparse': False, 'unique': True, 'name': u'_id_1', 'key': SON([('_id', 1)])}])]) on namespace admin.$cmd failed: The field 'sparse' is not valid for an _id index specification. Specification: { ns: "admin.auth_group_permissions", v: 1, sparse: false, unique: true, name: "_id_1", key: { _id: 1 } } And following are the permissions in mongo table db.auth_permission.find() { "_id" : ObjectId("589da1d0962fd90eb5f5e78c"), "codename" : "delete_logentry", "name" : "Can delete log entry", "content_type_id" : ObjectId("589da1d0962fd90eb5f5e78b") } { "_id" : ObjectId("589da1d0962fd90eb5f5e790"), "codename" : "delete_user", "name" : "Can delete user", "content_type_id" : ObjectId("589da1d0962fd90eb5f5e78f") } { "_id" : ObjectId("589da1e5962fd90eb5f5e792"), "codename" : "delete_contenttype", "name" : "Can delete content type", "content_type_id" : ObjectId("589da1e5962fd90eb5f5e791") } … -
Django extend template
I still very new to Django. I have 4 .html files: header.html(generic header for every page), body.html(load necessary css file and generate navigation button according to user roles), home.html and apply.html Here is what I want to do: 1)header.html(generic title for every page) parent of body.html. 2)body.html parent of home.html and apply.html here is my code in header.html: <!DOCTYPE html> <html> {% load staticfiles %} <head> <link rel="shortcut icon" href="{% static "favicon.ico" %}"/> <link rel="stylesheet" href="{% static 'loginTemplate.css' %}" /> {% block body %}{% endblock %} {% block content %}{% endblock %} Here is my code in body.html: {% extends "header.html" %} {% block body %} {% for role in roles %} {% load staticfiles %} <link rel="stylesheet" href="{% static 'bodyTemplate.css' %}"/> </head> <body> <div><!--place my button here</div> {% endfor %} {% endblock %} Here is my code in home.html and apply.html: {% extends "body.html" %} {% block content %} <div>load user detail<div> {% endblock %} Question: When i login to my test user, home.html showed the interface design that I want because bodyTemplate.css is included. But when I press a button that will link to apply.html, it showed me a white page with empty styling words and no button.