Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When cloning a large django project, to set up the local database is it recommended to run all of the migrations since forever, or start fresh?
I just cloned a large django project and if I run the migrations I get errors. I wanted to know if it's necessary to go into each migration file and fix it, or to somehow skip them. I know in rails that in a situation like this one is advised to load the schema instead of running all of the past migrations, and wondered if it was the same for django. I know that one option is to delete all of the migrations, but since I am on a team that already has their local databases set up, I cant commit a deletion of all the migrations for my whole team, just so I can migrate my local database. How do I migrate my new local database given there are tons of migrations with tons of bugs and I mustn't delete the migration files for my git repo? -
I can not Install pyscopg2 with sudo yum install django pyscopg2. on centos7
Installation will endup with this message. Command "/usr/bin/python3.4 -u -c "import setuptools, tokenize;file='/tmp/pip-nbderdof-build/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-p07ubkfd-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-nbderdof-build/ (myprojectenv) [anyuser@localhost myproject]$ -
Django MultiValueDictKeyError in for loop
I have the following view, which should be used to upload image files to a form on one of the Django webpages: def upload_budget_pdfs(request, project_id): project = Project.objects.get(id=project_id) print("Value of project in 'upload_budget_pdfs()': ", project) if request.method == 'POST': presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', '-vn') print("Value of presentations in 'upload_budget_pdfs()': ", presentations) drawing_formset = DrawingUploadFormset(request.POST, request.FILES, prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created')) print("Value of drawing_formset in 'upload_budget_pdfs()': ", drawing_formset) if drawing_formset: print 'Saving drawing_formset' print "Before", [b.id for b in project.budget_versions.all()] for drawing_form in drawing_formset: if drawing_form.instance.budget: print 'Instance', drawing_form.instance.budget drawing = drawing_form.save(commit=False) drawing.budget = drawing_form.instance.budget drawing.save() print drawing, [b.id for b in project.budget_versions.all()] else: print("Drawing formset not valid. ", drawing_formset.errors) budget_formset = BudgetPresentationFormset(request.POST, request.FILES, instance=project, prefix="presentations") if budget_formset.is_valid() and budget_formset.has_changed(): updated_budget_presentations = budget_formset.save() elif budget_formset.has_changed(): print 'Budget formset not valid.',budget_formset.errors return HttpResponseRedirect(reverse('projects:concept', args=[project_id])) However, currently, when pressing the 'Upload' button to upload the form, having attached an image to it using the 'Choose file' dialog to select the image file, I get an error page that indicates that I'm getting a MultivalueDictKeyError, and the particular line it's complaining about is the line: for drawing_form in drawing_formset: drawing_formset is an instance of DrawingUploadFormset, which I have defined in the forms.py … -
Autospeccing mocked Celery function with patch
I am trying to autospec a mocked Celery function, but ran into the problem that delay is actually getting mocked, which accepts anything for its args. I found How can i autospec a mocked Celery function which offers a solution (which I don't understand). How do I get it to work with the patch decorator? Here is some code I have: @patch('simcontrol.organisations.tasks.send_account_balance_threshold_exceeded_mail.delay') def test_check_all_organisations_for_insufficent_funds_sends_mail_if_insufficient_funds( mock_send_account_balance_threshold_exceeded_mail, ): active_organisation = mommy.make_recipe( 'simcontrol.organisations.tests.organisation', balance=10, balance_threshold=20 ) inactive_organisation = mommy.make_recipe( # noqa 'simcontrol.organisations.tests.inactive_organisation', balance=10, balance_threshold=20 ) user = mommy.make_recipe('simcontrol.users.tests.user') active_organisation.add_user(user) # Preconditions assert active_organisation.insufficient_funds() assert inactive_organisation.insufficient_funds() # >>>>>>>>>>. This call in turn calls the mock incorrectly by passing two instead of three args. # >>>>>>>>>> Yet the test still passes tasks.check_all_organisations_for_insufficient_funds() -
Django cms url pattern without apphook
I need to create an application to display the list of projects and project details. Information on the project is stored in a separate database, which is not connected with the base model. I created two plug-in to display the list of projects, and output details for a specific project. for teachers to cooperate each should have its own page with a URL r '^ (? P <project_title> \ w +) / $' And I thought to use a URL for choosing with project will be shown in project details plugin. After reading docs, I found only one way to make it. Make it by apphook. But if I'll do it this way, it will lose any sense to use CMS. Because in fact I will do the same work as I won't use CMS. So my question is about is there any solution to make pattern urls without using apphooks. -
Creating visualization for Neo4j in Django using Vis.js
I am trying to create a visualization in Django for a neo4j data with some code example i got on the internet. I am able to retrieve the data coming through but I am unable to see the graph. I am using vis.js library. here is my views.py def index(request): graph = Graph("http://localhost:7474/db/data/") entries_list = Mnode.objects.all() options = {"Person": "name", "Drink": "name", "Manufacturer": "name"} p= draw(graph, options) return render(request, 'index.html', {"p": p}) def vis_network(nodes, edges, physics= False): html="" unique_id = str(uuid.uuid4()) id = unique_id nodes = json.dumps(nodes) edges = json.dumps(edges) physics = json.dumps(physics) data = html.format(id=unique_id, nodes=json.dumps(nodes), edges=json.dumps(edges), physics=json.dumps(physics)) return (nodes, edges, physics) def draw(graph, options, physics=False, limit=100): query = """ MATCH (n) WITH n, rand() AS random ORDER BY random LIMIT {limit} OPTIONAL MATCH (n)-[r]->(m) RETURN n AS source_node, id(n) AS source_id, r, m AS target_node, id(m) AS target_id """ data = graph.run(query, limit=limit) nodes = [] edges = [] def get_vis_info(node, id): node_label = list(node.labels())[0] prop_key = options.get(node_label) vis_label = node.properties.get(prop_key, "") return {"id": id, "label": vis_label, "group": node_label, "title": repr(node.properties)} for row in data: source_node = row[0] source_id = row[1] rel = row[2] target_node = row[3] target_id = row[4] source_info = get_vis_info(source_node, source_id) if source_info not in … -
Formatting hours and minutes in django backend
I have a method in my django app (1.8). From date recived from date_start field: 2017-01-26 18:00:00+00:00 I want to get hours and minutes. But my code didn't works: @property def time(self): return '{%H:%M}'.format(self.date_start) -
Group permissions in HTML Template with Django
I'm getting a little problem with my project. I would to authorize a part from my Django website to all groups (visitor, customer, ...) except one (Superadmin). This is my HTML template : <!-- Home tab --> <ul class="nav navbar-nav"> <li><a href="{% url "accueil" %}"> <span class="glyphicon glyphicon-home"></span> Accueil </a></li> {% if request.user|has_group:"admin" %} <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Informations Mairie <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "{% url "Mairieform" %}"> <span class="glyphicon glyphicon-pencil"></span> Créer/Editer les informations de la Mairie </a></li> <li><a href = "{% url "Mairieresume" %}"> <span class="glyphicon glyphicon-home"></span> Consulter les informations de la Mairie </a></li> </ul> </li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Actes Etat Civil <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "{% url "home" %}"> <span class="glyphicon glyphicon-user"></span> Fiches Individuelles </a></li> <li><a href = "{% url "BChome" %}"> <span class="glyphicon glyphicon-baby-formula"></span> Actes de Naissance </a></li> <li><a href = "{% url "BCnotfound" %}"> <span class="glyphicon glyphicon-heart"></span> Actes de Mariage </a></li> <li><a href = "{% url "BCnotfound" %}"> <span class="glyphicon glyphicon-fire"></span> Actes de Divorce </a></li> <li><a href = "{% … -
uwsgi & Django with port 80
If I run uwsgi with uwsgi --ini kb_uwsgi.ini --http :80 it gives me an error: [uWSGI] getting INI configuration from kb_uwsgi.ini *** Starting uWSGI 2.0.14 (64bit) on [Thu Jan 26 12:34:51 2017] *** compiled with version: 5.4.0 20160609 on 06 January 2017 11:55:37 os: Linux-4.4.0-53-generic #74-Ubuntu SMP Fri Dec 2 15:59:10 UTC 2016 nodename: ip-172-31-16-133 machine: x86_64 clock source: unix detected number of CPU cores: 4 current working directory: /home/ubuntu/webapps/kenyabuzz detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/webapps/kenyabuzz your processes number limit is 64137 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) bind(): Permission denied [core/socket.c line 769] the site loads however if i preceed the command with sudo or use port :8000 eg uwsgi --ini kb_uwsgi.ini --http :8000 Now I tried to make the site live with nginx and uwsgi I get a 502 Bad Gateway nginx/1.10.0 (Ubuntu) nginx works okay because the favicon loads and I can access static files with \static\... I know this is Django having an issue rendering. I've tried also loading uwsgi --ini kb_uwsgi.ini --http :8000 … -
custom query and alter data
I have OBJ in my template and its id is used to build the URL. I want to base64 the ID of the OBJ. So in my view I used to do that objs = ObjsModel.objects.filter( blabla ) for obj in objs: obj.id = base64.urlsafe_b64encode(str(obj.id)) This code works. Unfortunately I have to use RAW SQL for the query. When I use the RAW query the loop is not changing the IDs sql_raw_query = "SELECT * FROM blabla more blabla" objs = ObjsModel.objects.raw(sql_raw_query) for obj in objs: obj.id = base64.urlsafe_b64encode(str(obj.id)) With that code the IDs are not changed and I don't understand why. How to change the IDs from the view ? -
too many values to unpack django
I am creating the Django polls app. I want the user to be able to choose from "yes" or "no" to each question. I am displaying "yes" and "no" in a drop down box. When I select a value from the drop down box, I get the error in the title above. views.py def test_form(request, question_id): question = get_object_or_404(Question, pk=question_id) if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): vote = request.POST.get('user_choice') selected_choice = question.choice_set.get(vote) if vote == 'yes': print 'vote is:' + vote selected_choice.votes += 1 selected_choice.save() else: print 'vote is ' + vote return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) else: form = TestForm() return render(request, 'polls/test_form.html' ,{'form': form ,'question':question}) forms.py from django import forms from .models import Choice,Question class TestForm(forms.ModelForm): class Meta: model = Question fields = ["user_choice"] test_form.html <h1>{{ question.question_text }}</h1> <form method="post"> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {{form.choice_text}} {{form.user_choice}} <input type="submit" value="send"> </form> models.py from __future__ import unicode_literals import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') Yes = 'Yes' No = 'No' CHOICES = ( (Yes, 'Yes'), (No, 'No'), ) user_choice = models.CharField( max_length=3, choices=CHOICES, default=Yes, ) def __str__(self): return self.question_text def was_published_recently(self): return … -
Modsecurity causing django admin to send empty response
I am fairly new to using uwsgi, nginx with modsecurity and pagespeed, and django. When I comment out the lines: ModSecurityEnabled on; ModSecurityConfig modsec_includes.conf; in my mysite_nginx.conf I am able to log into the django admin account as expected, but when I enable them, I get my.server.ip.address didn’t send any data. ERR_EMPTY_RESPONSE in my browser when I try to log in. Looking in my nginx error log shows no modsecurity errors. The error it is showing is: 2017/01/26 12:08:13 [alert] 3521#0: worker process 8640 exited on signal 11 Since everything seems to be working fine when modsecurity is off, presumably the problem is arising here. -
Django - sort records by custom column
I can't figure out how to make admin able to sort records using custom column - hours_to_deadline (when they clicks on the column header). In my case, it's timedelta. class JobAdmin(SuperModelAdmin): ... list_display = ['id', 'identificator', 'created', 'invoice__estimated_delivery','hours_to_deadline','customer__username', 'language_from__name', 'language_to__name', 'delivery__status', 'confirmed', 'approved', 'invoice__final_price'] ... def hours_to_deadline(self,obj): try: return (obj.invoice.estimated_delivery - now()) except: return None I found this solution: http://stackoverflow.com/a/15935591/3371056 But in my case, I can't just do sum or something similar. Do you know what to do? -
Django formset not valid
I have a Django website, and on one of the pages there is form which users can use to enter details about a presentation for a specific project. A project can have multiple presentations (each presentation is for an individual budget for that project), but only one of the presentations will be for the 'current' budget (i.e. the currently 'accepted' budget). There is the functionality to upload a 'PDF package' for the budget for each presentation- this is done by clicking a 'Choose File' button on the form, selecting the PDF to upload using the dialog box that opens, and clicking the 'Upload' button on the form. Once done, a 'PDF' icon is displayed in the place where the 'Choose File' button was displayed, and clicking this icon opens a new tab in the browser, in which a preview of the PDF file is displayed. I am now trying to add a second button to the form to allow the user to upload a 'drawing' file (which is likely to also be a PDF file) to the form. I have the 'Choose file' button in place on the form, and clicking it opens up a dialog which allows the user … -
Compile embedded C in Django (Python)
I developed PWM dimmer in C for 220v light on Raspberry Pi 3 and i want to run this embedded C program on Django Web. How i can do this? I am a beginner. -
Django restframework posts api not returning post titles in angularjs
I have a working api in django that i am trying to access through angularjs.Problem is the browser is not showing anything and am not seeing any errors in chrome debugger. models.py class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, #used for urls,short label containing letters,numbers,hyphens unique_for_date = 'publish') author = models.ForeignKey(User,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add = True) updated =models.DateTimeField(auto_now_add = True) photo = models.FileField(upload_to = '.',blank = True,null = True) status = models.CharField(max_length = 10, serializers.py from rest_framework import serializers from blog.models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title','slug','author','body','photo',) viewsets.py from blog.models import Post from .serializers import PostSerializer from rest_framework import viewsets from django.shortcuts import get_object_or_404 from rest_framework.response import Response class PostViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving posts. """ queryset = Post.objects.all() serializer_class = PostSerializer def list(self, request): queryset = Post.published.all() serializer = PostSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Post.published.all() post = get_object_or_404(queryset, pk=pk) serializer = PostSerializer(post) return Response(serializer.data) angularjs app.js var myApp = angular.module('postsApp',['ngResource']); myApp.config(function($resourceProvider) { $resourceProvider.defaults.stripTrailingSlashes = false; }); //main controller of our app //displays all posts from backend myApp.controller('MainCtrl', function($scope, Posts) { console.log('showing posts'); $scope.posts = Posts.query(); … -
Django doesn't create models fields
I'm getting a problem very strange from my point of view and I would like to get your mind. I'm building a Django website and I want to create a new app with his models.py file. I wrote this script to my Mairie models application : # -*- coding: utf-8 -*- from django.db import models from django.utils.encoding import force_text from django_countries.fields import CountryField ############################################### # Choix à l'utilisateur pour le sexe du maire # ############################################### SEX_CHOICES = ( ('Masculin', 'Masculin'), ('Feminin', 'Féminin') ) TITLE_CHOICES = ( ('Mr', 'Monsieur'), ('Mlle', 'Mademoiselle'), ('Mme','Madame'), ('Dr','Docteur'), ('Me','Maître'), ) INSTITUTION_CHOICES = ( ('Mairie','Mairie'), ('Prefecture','Préfécture'), ('Autre','Autre') ) DEVISE_CHOICES = ( ('EUR','EUR (€)'), ('USD','USD ($)'), ('CFA','CFA') ) MANDAT_CHOICES = ( ('2011','2011'), ('2012','2012'), ('2013','2013'), ('2014','2014'), ('2015','2015'), ('2016','2016'), ('2017','2017'), ('2018','2018'), ('2019','2019'), ('2020','2020'), ('2021','2021'), ('2022','2022'), ('2023','2023'), ('2024','2024'), ('2025','2025'), ('2026','2026'), ('2027','2027'), ('2028','2028'), ('2029','2029'), ('2030','2030'), ('2031','2031') ) #################################################################################### # Création d'une table permettant de renseigner toutes les # # informations concernant la mairie et le maire # #################################################################################### class Mairie(models.Model): institution = models.CharField(max_length=30, choices=INSTITUTION_CHOICES, null=False, verbose_name='Nom/Enseigne/Raison Sociale') adress = models.CharField(max_length=30, null=False, verbose_name='Adresse') zip = models.IntegerField(verbose_name='Code Postal', null=False) city = models.CharField(max_length=30, verbose_name='Ville', null=False) country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays', null=False) department = models.CharField(max_length=30, verbose_name='Département/Canton') devise = models.CharField(max_length=30, choices=DEVISE_CHOICES, null=False, verbose_name='Devise') fixe = models.CharField(max_length=30, … -
empty string prints None
I am running Django 1.9 I have RAW SQL query. My issue is with the empty strings. When I print the empty strings in the template I am getting NONE. I know that I can use {{ smt|default_if_none:""}} but for me will be more comfortable if this is resolved in the view When I use Model.objects.filter() to do the query I don't have this issue. What is the difference between the RAW queries and DJANGO ? How can I solve it without using filter tag Thank you -
django 1.9 Cannot resolve keyword 'roomtype' into field
I'm trying to make a search field in admin panel searching correct. Here is my code models.py class Hotel(ServioResource): name = models.CharField( max_length=200, blank=True, verbose_name=_('Name')) class RoomType(ServioResource): hotel = models.ForeignKey( Hotel, related_name='room_types', verbose_name=_('Hotel')) admin.py @admin.register(RoomType) class RoomTypeAdmin(TranslationAdmin): list_select_related = ('hotel',) list_display = ('id', 'hotel', 'class_name') search_fields = ['roomtype__hotel__hotel__name'] list_filter = ('hotel',) group_fieldsets = True inlines = [ RoomTypeImageTabular, ] -
Quick way to add a class to a django admin field?
Is there a quicker way to append a class name to an input field in Django Admin? e.g. I have a text field called 'markdown', and I want to add the class markdown to it, so I can easily apply a markdown editor in admin. The result of this code is perfect. Just a bit of a PITA to apply this across all my admin forms.. I can't use formfield_override since not all my textareas are markdown. class MyModelAdmin(forms.ModelForm): class Meta: model = models.MyModel widgets = { 'markdown': forms.Textarea(attrs={'class': 'markdown'}) } class MyModelAdmin(admin.ModelAdmin): form = MyModelAdminForm -
Django urls, views, regex configuration for multiple parameters
My Problem is that I'm currently unable to track particular post with these codes: in urls.py: url(r'^class/(?P<class_name>[\w-]+)/(?P<subject_name>[\w-]+)/(?P<slug>[\w-]+)/$', highschool.lessonBasedHome, name='lesson_based_home'), in views.py: def lessonBasedHome(request, class_name, subject_name, slug): qs = Content.objects.filter(class_name__name = class_name, subject_name__name = subject_name) qs1 = get_object_or_404(qs, slug = slug) context = { "qs1":qs1, } return render(request, 'lesson_based_home.html', context) in lesson_based_home.html: {% block content_area %} {{qs1.title}} {% endblock content_area %} But I don't know where's the problem. Please help. -
Mezzanine Cartridge rating form customization?
Hello i'm trying to customize product page in Mezzanine Cartridge shop. I have a problem with the rating form customization. Now it looks like this rating form To get this look, I used some CSS code /* Ratings */ .rating {margin:15px; text-align: center;} .rating * {display:inline !important; list-style-type:none;} .rating label {margin-right:15px;} .rating p {margin-right:20px;} .rating ul {margin-left:0 !important; padding:0 !important;} .rating li {border:none !important; background:none !important; padding:0 !important;display: inline-block;} .rating li input {margin-top:-4px;} #comments .rating {padding:0 !important; margin:10px 0 0 0 !important; border:none !important; background:none !important;} My goal is to make simple rating form with stars instead of number. Can any body help? -
Why not working filter escape in django 1.10
I have django 1.10.4, python 3.5.2 This is my template {% extends 'base.html' %} {% block content %} <div class="main"> <div class="container"> <h3>{{ note.title }}</h3> {{ note.text|escape }} {% autoescape off %} {{ note.text }} {% endautoescape %} </div> </div> {% endblock %} In database i have those note.text = '<a href="#">some_link</a>'. When i add filter escape {{ note.text|escape }} it's don't work and i see original string from database <a href="#">some_link</a> Work only with this construction {% autoescape off %}{% endautoescape %}. Why? -
Django ImportError: cannot import from models
I have a utils.py file in an app directory at the same level as models.py. I am trying to import a class (a model) in utils.py: from models import TeamConstraint My IDE does not report any conflict, however when running the server I am getting an ImportError: ImportError: cannot import name TeamConstraint I tried checking for circular dependencies, there is a file tasks.py also in the same level as the rest that imports from utils.py: from scheduler.utils import current_indie_teams, matchcount_by_week Although I don't understand why here scheduler needs to be included explicitly, while when trying to import a model it is not required (or so says PyCharm at least). I am trying to figure out how to solve this. -
Django regular expression
music.urls.py url(r'^(?P<album_id>[0-9]+)$', views.detail, name='detail'), Is there any fault in this piece of code because the server cannot detect it. It checks in the url if there is an integer. http://127.0.0.1:8000/music/1/ Like in this url, it must redirect to different page but is not detecting it.