Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a total number of objects inside each object using django markup
Using Django, I am trying to output the total number of lots in each community. A community has several lots, and there are several communities. Here is an example of what I am getting... Total lots: 99. This community only has 2 lots. There are 4 communities with a total of 9 lots between them. The models and views seem correct. Is there a filter I am missing or a different way of writing this to get the correct result? {% if community.is_active %} <a class="panel-link" href="{% url 'community-detail' pk=community.id %}" %}> <div class="col-md-6 community_col"> <div class="community_box"> <div class="row"> <br> <div class="col-md-4 community_img"> <img src="/media/{{ community.logo }}" alt=""> </div> <div class="col-md-7 col-md-offset-1"> <h1 style="margin-bottom: -10px; margin-top: -15px;"><small>{{ community.name }}</small></h1> <h4>{{ community.city }}, {{ community.state }}</h4> <h6>Total lots: {% for lot in community.lot_set.all %}{{ lots|length }}{% endfor %}</h6> <h6>Total Active lots: </h6> <h6>Total Sold lots: </h6> <h6>Total Inactive lots: </h6> </div> </div> </div> </div> </a> {% endif %} {% endfor %} -
Images not showing up when viewing HTML code
I have an index page for a django project I am working on but the images I attach to the buttons aren't showing up when I view it. <html> <head> <title>Support Tools</title> <style type="text/css"> .button { float: left; margin-left: 30px; margin-bottom: 30px; width: 350px; height: 150px; background: url('/media/img/blank.png'); background-repeat: no-repeat; cursor: hand; } .button img { position: relative; left: 20px; top: 10px; } .button div { font-family: Trebuchet MS, Calibri; color: white; font-weight: bold; font-size: 22pt; text-align: center; position: relative; top: -100px; left: 120px; width: 220px; } .title { font-family: Calibri, Helvetica, Arial, Verdana; font-size: 18pt; font-weight: bold; } a, a:link, a:visited, a:active, a:hover { text-decoration: none; } </style> <!--[if lte IE 6]> <script type="text/javascript" src="/media/js/supersleight-min.js"></script> <![endif]--> </head> <body id="b"> <p class="title">GAI Support Tools</p> <a href="/eam/"> <div class="button"> <img src="/media/img/tools.png" /> <div>EAM<br />Support Tool</div> </div> </a> <a href="/admin/minisar/"> <div class="button"> <img src="/media/img/database.png" /> <div>miniSAR<br />Administration</div> </div> </a> <a href="/ai_stats/"> <div class="button"> <img src="/media/img/chart.png" /> <div>Web Service<br />Dashboard</div> </div> </a> <a href="/health/production/"> <div class="button"> <img src="/media/img/monitor.png" /> <div>&nbsp;Web Service<br />Health</div> </div> </a> <a href="/toys/user/"> <div class="button"> <img src="/media/img/users.png" /> <div>User<br />Search</div> </div> </a> <a href="/toys/ud_data_extract/"> <div class="button"> <img src="/media/img/database.png" /> <div>UD Data<br />Extract</div> </div> </a> <a href="/solutions/"> <div class="button"> <img src="/media/img/solutions.png" … -
Get all model objects of a table and get corresponding related row from other table only for particular user/field value
Here are my models class Request(models.Model): song = models.ForeignKey(Song) requestee = models.ForeignKey(User) upvotes = models.IntegerField() downvotes = models.IntegerField() youtubeId = models.CharField(max_length=120) added = models.DateTimeField(auto_now_add=True) played = models.BooleanField(default=False) def __str__(self): return self.song.name class VoteRecord(models.Model): user = models.ForeignKey(User) request = models.ForeignKey(Request) upvoted = models.BooleanField(default=False) downvoted = models.BooleanField(default=False) up_difference = models.IntegerField(default=0) down_difference = models.IntegerField(default=0) class Meta: unique_together = ('user', 'request',) # db_table = 'voterecord' def __str__(self): return (self.user.username + '-' + self.request.song.name) Now I want all request objects (distinct) but for every request objects the corresponding voterecord should be for the current user. If the voterecord not exists the row should have voterecord fields as null. -
Django MySQL schema selection
In the same MySQL server we have a database for each client. This databases share the same table structure. We were able to create a Model for table Foo that looks like this: class Foo(models.Model): id = models.AutoField(primary_key=True) bar = models.CharField(max_length=50) class Meta: managed = False db_table = 'foobar' Our Django project needs to manage all of our clients. As all of them have the same structure we would also like to share the Foo model. At the begging we were able to handle this issue by defining in the project settings each client's database and using routers. At the moment we have too many clients to have them all defined in setting.py. Is there any reasonable way to tell the model which schema has to be used every time we use it? -
How do I write this query in Django
How would I write the following SQL query in Django. SELECT COUNT(*) FROM orion.accounts_transactions LEFT JOIN orion.accounts_notes ON orion.accounts_notes.accounts_core_id = orion.accounts_transactions.accounts_core_id WHERE email_status='clicked' AND email_template_id IS NOT NULL AND orion.accounts_transactions.creation_date >= orion.accounts_notes.creation_date AND orion.accounts_transactions.creation_date <= orion.accounts_notes.creation_date + INTERVAL 7 DAY; -
Django rest framework not creating object with FK to a model with unique=True field
I have two models like this: class Sector(models.Model): name = models.CharField(max_length=100, db_index=True, unique=True) class Address(models.Model): ... sector = models.ForeignKey(Sector, null=True, blank=True) And a serializer for the Address model: In the view, I have this: address_serialized = AddressSerializer(data=request.data) if address_serialized.is_valid(): address_serialized.save(client=client) It never gets to the create function. I have a serialized with a create function that looks like this: class AddressSerializer(serializers.ModelSerializer): city_gps = CitySerializer(required=False) sector = SectorSerializer(required=False) class Meta: model = Address fields = (..., "sector") def create(self, validated_data): ... sector_dict = validated_data.get("sector", None) sector = None if sector_dict and "name" in sector_dict and city_gps: if Sector.objects.filter(name=sector_dict["name"], city=city_gps).exists(): sector = Sector.objects.get(name=sector_dict["name"], city=city_gps) # pdb.set_trace() if "sector" in validated_data: validated_data.pop("sector") if "city_gps" in validated_data: validated_data.pop("city_gps") address = Address.objects.create(sector=sector, city_gps=city_gps, **validated_data) return address The code never touches this function, is_valid() returns False. And the message is {"sector":{"name":["sector with this name already exists."]}} I need to be able to create a new address with FK to the already existing sector. How can I achieve that? Any advice will help. -
set slug field form manually in views Django
I'm new in Django and I'm trying to pre fill one of the fields of my form with a slug. I'm getting the slug from another model. I'm not using ForeignKey because that shows me a list with my objects and I want to save in the form the same slug that I'm using in the url. Maybe I'm not thinking this right. What should I do? Thank you! This are my models: from django.db import models class Thing(models.Model): name = models.CharField(max_length=255,) rut = models.CharField(max_length=12, blank= True) cel = models.CharField(max_length=12, blank= True) slug = models.SlugField(unique=True) class Control(models.Model): id_p = models.SlugField() pa = models.CharField(max_length=3,) My forms from django.forms import ModelForm from collection.models import Thing, Control, Medicamento class ThingForm(ModelForm): class Meta: model = Thing fields = ('name', 'rut','cel','pet',) class ControlForm(ModelForm): class Meta: model = Control fields = ('id_p', 'pa',) This is what I'm doing in the views def add_control(request, slug): thing = Thing.objects.get(slug=slug) form_class = ControlForm form_class(initial={'id_p':thing}) if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): form.save() return redirect('thing_detail', slug=thing.slug) else: form = form_class() return render(request, 'things/control.html', { 'thing': thing, 'form': form, }) -
How to put disabled attribute inside input?
In my form I use MultipleChoiceField. It shows data from tuple CHOICES. forms.py: CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) class SomeForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=CHOICES,) class Meta: model = SomeModal fields = ('symbol',) MultipleChoiceField generate in template this html: <ul id="id_symbol"> <li> <label for="id_symbol_0" disabled=""> <input id="id_symbol_0" name="symbol" value="A" type="checkbox">Name A </label> </li> <li> <label for="id_symbol_1" disabled=""> <input id="id_symbol_1" name="symbol" value="B" type="checkbox">Name B </label> </li> <li> <label for="id_symbol_2" disabled=""> <input id="id_symbol_2" name="symbol" value="C" type="checkbox">Name C </label> </li> </ul> QUESTION: Is it possible to add disabled attribute to one of input element?! For example: <input id="id_symbol_2" name="symbol" value="C" type="checkbox" disabled> -
How to pass parameter to view method using {% 'url' %} syntax in django
In my url.py: url(r'hardware/common_report/(?P<line_id>[a-zA-Z]+)', 'Report.views.hardware_common_report', name='hardware_common_report'), In my view.py: def hardware_common_report(request): return render_to_response('Report/hardware/common_report.html') HTML: {% for report in reports %} <div class="col s12 m4 l4 waves-effect waves-green"> <div class="card cardMarPad light-green darken-4"> <a href="{% url 'hardware_common_report' report.report_display_name %}"> <div class="card-content white-text"> <span class="card-title">{{ report.report_display_name }}</span> <p class="descri">&nbsp;</p> </div> </a> </div> </div> {% endfor %} I'm getting this error: NoReverseMatch at /report/hardware/ Reverse for 'hardware_common_report' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['report/hardware/common_report/(?P[a-zA-Z]+)'] -
sending json from django to d3.js
i am trying to pass a queryset in django's views.py to d3.js. views.py : def index(request): qs = DCPOWERSTATS.objects.all().values('TS','PuE').order_by('TS') return render(request, 'dashboard/dash.html', context=qs}) dash.html : <!DOCTYPE html> <meta charset="utf-8"> <style> .chart div { font: 10px sans-serif; background-color: steelblue; text-align: right; padding: 3px; margin: 1px; color: white; } </style> <div class="chart"></div> <script src="//d3js.org/d3.v3.min.js"></script> <script> var data = {{ data_json }}; var x = d3.scale.linear() .domain([0, d3.max(data)]) .range([0, 420]); d3.select(".chart") .selectAll("div") .data(data) .enter().append("div") .style("width", function(d) { return x(d) + "px"; }) .text(function(d) { return d; }); </script> I need to make changes in views.py and dash.html to create something like : https://bl.ocks.org/mbostock/3885304 All previous answers are confusing.I need a solution for views.py as well as dash.html. I also need to know the perfect way of sending queryset results to javascript. Thanks! -
Django multiple pluralization
Im quite new to django so can`t really figure out how to define multiple pluralization forms for some object. Here is my models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class Bancnote(models.Model): HRYVNA = 'Гривня' KARBOVANETS = 'Карбованець' TYPE_CHOICES = ( (HRYVNA, 'Гривня'), (KARBOVANETS, 'Карбованець') ) type = models.CharField(max_length=11, choices=TYPE_CHOICES, default=HRYVNA) par = models.PositiveIntegerField() year_from = models.PositiveIntegerField() year_to = models.PositiveIntegerField() size = models.CharField(max_length=7) sign = models.CharField(max_length=20) desc = models.TextField(max_length=200) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) + ' ' + self.type + ' ' + str(self.year_from) + '-' + str(self.year_to) As you can see there will be 2 options of type: HRYVNA, KARBOVANETS. And the form of this words depends on bancnote par. So the rule for possible forms in ukrainian language could be next: if Bancnote.par == 1: name = 'Гривня' elif Bancnote.par == 2 or 3 or 4: name = 'Гривні' elif Bancnote.par > 4: name = 'Гривень' The same for KARBOVANETS. I was reading django docs here: https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#pluralization But didn`t find step by step solution for this. Please help! Thaks a lot in advance for any help. Here is my template 'index.html' if needed {% extends 'catalogue/base.html' %} {% load i18n %} {% block title … -
How can I select records n-at-a-time for multiple users to edit?
I am using a Django backend with postgresql. Let's say I have a database with a table called Employees with about 20,000 records. I need to allow multiple users to edit and verify the Area Code field for every record in Employees. I'd prefer to allow a user to view the records, say, 30 at a time (to reduce burnout). How can I select 30 records at a time from Employees to send to the front end UI for editing, without letting multiple users edit the same records, or re-selecting a record that has already been verified? I don't need comments on the content of the database (these are example table and field names). -
Django and docker, ImportError: Could not import settings '"config"' Is it on sys.path?
I'm step by step switching my django project to work on local from vagrant to docker. With docker, you don't need a virtualenv. Even if I find it very convenient I'm facing some new troublesome issues. The main one is this error on ./manage.py cmd: ImportError: Could not import settings '"config"' (Is it on sys.path? Is there an import error in the settings file?): No module named '"config"' So when I start the python console code and type: >> import sys >> sys.path >> ['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] But my path project is: /var/www/webapps/wrapper_website/app I've a setup environment loaded on docker-compose up which contain: DJANGO_CONFIGURATION="LocalContent" And that's what I'm trying to reach. The config folder is in: /var/www/webapps/wrapper_website/app/config I've tried this in the wsgi.py: import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config") os.environ.setdefault("DJANGO_CONFIGURATION", "Production") sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) <- this line from configurations.wsgi import get_wsgi_application application = get_wsgi_application() Without success. -
django ajax post to unexpect url
my ajax as follow: <script> $(document).ready(function () { $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}'} }); $("#submit").submit(function () { var title = $("#title").val(); var body = $("#body").val(); var images = $("#browsefile")[0].files[0]; $.ajax({ type: "POST", data: {title: title, body: body, images: images}, url: "{% url 'xxxxx' %}", success: function (result, statues, xml) { alert(result); }, error: function () { alert("false"); } }) }) }) </script> and my urls pattern as follow: url(regex=r'^add/$', view=views.add, name='bbb'), url(regex=r'^newBlog/$', view=views.addblog, name='xxxxx'), I except ajax post data to the method addblog, but I get POST /add/ HTTP/1.1 instead. anyone can told me where i made a mistake, thanks! -
Do dynamically drop down filtering from queryset of a models.ModelChoiceField on a forms.Form
Hi I'm trying to build a drop down template where we can filtering. The order is the following one: University --> degree --> markDegree When we will choose a University in the following select or dropdown menu we only can choose the dregree of this University and in the markDegree we will see the mark of this degree recently select. My model is te following one: class Universitys(models.Model): university = models.CharField(max_length=50) degree = models.CharField(max_length=50) degreeMark = models.DecimalField(decimal_places=3,max_digits=5) the form: class Universities(forms.Form): #class Meta: Universidades = forms.ModelChoiceField(label='Escoge Universidad',queryset=Universitys.objects.values_list('university',flat=True)) Carreras = forms.ModelChoiceField(label='Escoge Carrera',queryset=Universitys.objects.values_list('degree',flat=True)) #class Carreras(forms.Form): def __init__(self, *args, **kwargs): qs = kwargs.pop('Universitys') super(Universities, self).__init__(*args, **kwargs) self.fields['Carreras'].queryset = qs#Universitys.objects.values_list('degree',flat=True) and the views: def prueba(request): universitys = Universities(request.POST or None) context = {"form":universitys, } return render(request,"prueba.html", context) I've tried to do different foms, but without solution, is the first time that I try to built this if you can help me I'm grateful with you. -
Page not found with Django (404)
in my django project,when i access localhost:8000 it say: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ the urls.py is: from django.conf.urls import include, url from django.contrib import admin from polls import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace="polls")), ] polls urls.py is: from django.conf.urls import url, include from django.contrib import admin from polls import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'), url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'), url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'), url(r'^admin/', admin.site.urls), ] the django version is 1.10 what's problems ,thanks in advance -
Django static files do not resolve constant 404 errors
I am new to Django current version I'm running is 1.11 with python 3. I have configured the static file stuff as the docs suggest. Inside installed apps I have 'django.contrib.staticfiles' nonprofit/nonprofit/settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIR = ( os.path.join(BASE_DIR, "static/"), ) And django seems to be working as far as putting the right path in the template. Though even if I hardcode the path into the template the browser still gives a 404 not found. I have a base.html template, with some css. {% load staticfiles %} <!--Bootstrap--> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="/static/css/bootstrap-theme.css"> My directory structure is -- nonprofit - goals - nonprofit - static - css bootstrap.css bootstrap-theme.css - templates base.html db.sqlite3 manage.py From the browser it shows both 404 not found errors as well as not being able to go straight to the files- GET http://127.0.0.1:8000/static/css/bootstrap.css 127.0.0.1/:19 GET http://127.0.0.1:8000/static/css/bootstrap-theme.css 127.0.0.1/:20 I don't think the problem is with django because it shows the right path, but even the hardcoded one cannot be accessed through the browser. I'm running the development server. Whats going on with this stuff? Do I have something wrongly … -
Djano group by month name
I want to get an output of {'month': 'jan', 'count': 1600} but I get the following with the current code {'month': 1, 'count': 1600}. How do I do this so I get the name of the month and not the integer. class Month(Func): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = IntegerField() Note.objects.filter( email_status__in=status_list, email_template__isnull=False, creation_time__gt=one_year ).annotate( month=Month('creation_time') ).values('month').annotate( total_count=Count( 'email_id', distinct=True) ).values('total_count', 'month') -
Django for loop in html template not displaying
So I am trying to get the latest post and I ran into a problem where it will not display the post views.py def latest_post(request): latest = Post.objects.all().order_by('-id')[:1] context = {'latestPost': latest} return render(request, 'latest_post.html', context) Note: I also tried it with this, latest = Post.objects.all() There are entries in the database, I tested with the shell from blog.models import Post >>> Post.objects.all() <QuerySet [<Post: test>, <Post: okay so>, <Post: okay-okay>]> latest_post.html {% for newest in latestPost %} <section class="hero is-primary is-medium"> <div class="hero-body header"> <div class="container"> <div class="font"> <h1 class="title is-1"> <span id="blog_title">{{ newest.title }}</span> </h1> <h2 class="subtitle is-3 subup"> <span id="blog-subtitle">{{ newest.content|truncatechars:20|safe }}</span> </h2> <h2 class="subtitle is-5 dateup"> <span id="blogdate">{{ newest.timestamp }}</span><br><br> <a href="{{ newest.blog_url }}" class="button is-danger is-large is-inverted">Read More >></a> </h2> </div> </div> </div> </section> {% endfor %} in my blog_index.html I have the following {% extends "blog_base.html" %} {% block blog_main %} {% load staticfiles %} {% include 'latest_post.html' %} <p> other html here </p> {% endblock %} Latest_post.html displays when i use {% include 'latest_post.html' %} only if I don't use {% for newest in latestPost %} {% endfor %} So i am sure there aren't any typos somewhere that prevents the latest_post.html from … -
How can I make search form to filter items by location with Django?
I want to make search location form like Gumtree. In this website, if we put some words like "sy" to search location box, it shows "Inner Sydney, NSW", "Mount Sylvia 4343, QLD" like this. How can I make this with Django? And How can I prepare name of states, regions, cities? Is this made by using geo something and jQuery? -
Django template not displaying looped keys, values
I'm very new to Django and am trying to figure out why I can call the keys in a dict in my template as expected, but looping through the dict does not produce any text, nor any error messages. I don't want to hard code the key names (i.e. below msgid in my template, because the dict is dynamic and so I only want to loop through it. views.py class Pymat_program(View): def get(self, request, *args, **kwargs): selected_xml = 'a_directory_to_my_file' smsreport_dict = self.parse_xml_file(selected_xml) html = self.populate_html_text(smsreport_dict) return HttpResponse(html) def populate_html_text(self, smsreport_dict): t = get_template('template2.html') html = t.render(smsreport_dict) return html template2.html <p>MSGID: {{ msgid }}</p> <p> Begin {% for key, value in smsreport_dict %} <tr> <td> Key: {{ key }} </td> </tr> {% endfor %} </p>End In the template2.html you can see the msgid value (one of several values in smsreport_dict) being called, which is displayed on my page. But for some reason the smsreport_dict looping produces no text. Where am I going wrong? -
Django latex template with images
I'm trying to generate pdf from django latex template. To do so I'm using the code from here: So I have this code in views.py context = {....} template = get_template('my_latex_template.tex') rendered_tpl = template.render(context).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: for ppp in range(2): process = Popen( ['pdflatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, stderr=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) Here is my_latex_template.tex {% autoescape on %} \documentclass[a4paper,12pt]{article} \usepackage[T1,T2A]{fontenc} \usepackage[utf8]{inputenc} \usepackage[english,russian]{babel} \usepackage{graphicx} \begin{document} blabla \includegraphics{img.png} \end{document} {% endautoescape %} The structure of my directories: myapp |..templates |..|..my_latex_template.tex |..|..img.png |..views.py ... When compiling this latex template without \includegraphics{img.png}, everything works perfect. When compiling it with the image, I'm getting error that [Errno 2] No such file or directory: '/var/folders/73/r8hl47ld11l68v_1kjh_m61m0000gn/T/tmprfp7wf_x/texput.pdf' That basically means that this temporary file is not generating correctly by running pdflatex on rendered template... When I'm just running locally in terminal "pdflatex my_latex_template.tex" everything works fine and I'm getting pdf with the image. Do you have any ideas on what can I do? I would be super grateful if someone could help me. Thank you -
create site as alltop.com with django
way or package for create a site example site: www.alltop.com with framework django. for Implementation of these sites with Django framework, what measures should be taken? this site alltop use rss for give post tnx -
What is the "Best Practice" for invoice calculations in Django 1.10+?
If one has two models: class Invoice(models.Model): class Meta: ordering = ('-date_added', ) number = models.CharField(max_length=10,) comments = models.TextField(blank=True, help_text="Notes about this invoice." ) total = models.DecimalField(max_digits=9, decimal_places=2, default="0" ) date_added = models.DateTimeField(_('date added'), auto_now_add=True) date_modified = models.DateTimeField(_('date modified'), auto_now=True) def __unicode__(self): return "%s: total %s" % (self.number, self.total) class Part(models.Model): for_invoice = models.ForeignKey(Invoice) description = models.CharField(max_length=200, blank=True, help_text=_("Briefly describe the part.") ) supplier = models.CharField(max_length=100, blank=True, help_text=_("Supplier Name.") ) supplier_number = models.CharField(max_length=100, blank=False, help_text=_("Supplier's order number.") ) qty = models.DecimalField(max_digits=3, decimal_places=0, blank=False, null=False, help_text=_("How many are needed?") ) cost = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True, help_text=_("Price paid per unit") ) line_total = models.DecimalField(max_digits=9, decimal_places=2, default="0") date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __unicode__(self): return "%s: total %s" % (self.for_invoice, self.line_total) First choice I see is one could implement "line_total" or "total" as a calculated model field. But if you do that, then you cannot ever sort the change list by "line_total" or "total", and the users want to be able to do that. So I made them a saved field on the model. Reading the Django 1.10 docs I see 3 places where code can be defined to calculate and update the "total" and "line_total" fields: ModelAdmin.save_model(request, obj, form, change) … -
Django celery scheduled task django.core.exceptions.ImproperlyConfigured
I am trying to run this scheduled task and when i run this command the following error occurs. celery -A Htweetprod2 beat According to celery4.0 documentation to start the schedule this command should run, yet i am getting this error: C:\Users\hisg316\Desktop\Htweetprod2>celery -A Htweetprod2 beat Traceback (most recent call last): File "c:\python27\lib\runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "c:\python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\Scripts\celery.exe\__main__.py", line 9, in <module> File "c:\python27\lib\site-packages\celery\__main__.py", line 14, in main _main() File "c:\python27\lib\site-packages\celery\bin\celery.py", line 326, in main cmd.execute_from_commandline(argv) File "c:\python27\lib\site-packages\celery\bin\celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "c:\python27\lib\site-packages\celery\bin\base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "c:\python27\lib\site-packages\celery\bin\celery.py", line 480, in handle_argv return self.execute(command, argv) File "c:\python27\lib\site-packages\celery\bin\celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "c:\python27\lib\site-packages\celery\bin\base.py", line 285, in run_from_argv sys.argv if argv is None else argv, command) File "c:\python27\lib\site-packages\celery\bin\base.py", line 367, in handle_argv *self.parse_options(prog_name, argv, command)) File "c:\python27\lib\site-packages\celery\bin\base.py", line 403, in parse_options self.parser = self.create_parser(prog_name, command) File "c:\python27\lib\site-packages\celery\bin\base.py", line 419, in create_parser self.add_arguments(parser) File "c:\python27\lib\site-packages\celery\bin\beat.py", line 114, in add_arguments '-s', '--schedule', default=c.beat_schedule_filename) File "c:\python27\lib\site-packages\celery\utils\collections.py", line 130, in __getattr__ return self[k] File "c:\python27\lib\site-packages\celery\utils\collections.py", line 431, in __getitem__ return getitem(k) File "c:\python27\lib\site-packages\celery\utils\collections.py", line 280, in __getitem__ return mapping[_key] File "c:\python27\lib\UserDict.py", line …