Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating data tables in Django from JSON
I'm pretty new to web development, and I'm trying to implement a webpage in Django that displays a dynamic data table. I would like the data table to display all objects in the database, and when a new object comes in through JSON, the data table would update itself without the user refreshing the page. Here's what I have right now: <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Room</th> <th>Request</th> <th>Time</th> <th>Mark as Done</th> <th>Cannot Do</th> </tr> </thead> <tbody> {% for request in requests %} <tr> <td>{{ request.room }}</td> <td>{{ request.request }}</td> <td>{{ request.time }}</td> <td>{{ request.done }}</td> <td>{{ request.cannot }}</td> </tr> {% endfor %} </tbody> </table> This data table (using the dataTables framework) shows all the request objects in the Django database, but only loads them once. (The Django view for the page passes in 'requests' based on a database query when the page is loaded.) I tried researching the problem and it seems like I'll need to use jQuery and/or Ajax, but I'm not sure how. I saw that dataTables has a row.add() function, but again, I'm not sure how I can implement this to update the data table with information from JSON pushed to the site. Also, … -
fixed render() must be called with a dict, not a Context but can't seem to render the variable in template why? django
I am using the built in email system in django but then now I get such warning.. RemovedInDjango110Warning: render() must be called with a dict, not a Context my code used to be get_template(html_template).render(Context(body['ctx'])) I already fixed it by doing this get_template(html_template).render({Context(body['ctx'])}) but after I fixed it, somehow I cannot call the variable needed in my email template anymore. body['ctx'] actually contains something such as {'type': 'type1', 'field': 'field1} before, when I was still using the warning way to send emails, in the email template I can just use {{type}} or {{field}} but now after I fixed the warning, I cannot call the variable anymore. I tried changing code into get_template(html_template).render({'content': Context(body['ctx'])}) this still didn't work, in email template then I tried {{content}} I would then get something like this [{'False': False, 'None': None, 'True': True}, {'type': 'type1', 'field': 'field1'}] so I thought I can call the type variable by doing {{ content.1.type }} but still getting nothing. can someone please give me an idea what I might be doing wrong or what else I can try here? Thanks in advance -
Reverse Iterating over Foreign Key
I am trying the tutorial for Django on making a local library website with books. One of the challenges is to make an author detail view which lists all the books that author has written. I am having trouble displaying any book information for the author. Model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.urls import reverse import uuid # Create your models here. class Genre(models.Model): """ Model resprenting the book genre """ name=models.CharField(max_length=200, help_text="Enter a book genre") def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description") isbn = models.CharField('ISBN', max_length=13, help_text="13 character ISBN field") genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) def display_genre(self): return ', '.join([genre.name for genre in self.genre.all()[:3] ]) display_genre.short_description = 'Genre' class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique book number") book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('d', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text="Book Availability") class Meta: ordering = ['due_back'] def __str__(self): return ('%s (%s)' %(self.id, self.book.title)) class … -
Merge two different API calls into One
I have two different apps in my django project. One is "comment" and an other one is "files". A comment might save some file attached to it. The current way of creating a comment with attachments is by making two API calls. First one creates an actual comment and replies with the comment ID which serves as foreign key for the Files. Then for each file, a new request is made with the comment ID. Please note that file is a generic app, that can be used with other apps too. What is the cleanest way of making this into one API call? I want to have this as a single API call because I am in a situation where I need to send user an email with all the files as attachment when a comment is made. I know Queueing is the ideal way to do it. But I don't have the liberty to add queing to our stack now. So this was the only way I could think of. -
Sending data from form to about page django
I am assigned the task to fetch all the data from the form field of(experiment.html page) to destination page(about_experiment) after clicking submit button. So basically whatever is entered in the form needs to be outputted there Since I am a beginner in Django, I don't have much knowledge about it. My current views.py def about_experiment(request, ex_link_name): exp = get_object_or_404(Experiment,link_name = ex_link_name) high_scores = ScoreItem.objects.filter(experiment=exp,active=True) context = { 'request': request, 'exp':exp, 'high_scores': high_scores, 'awards':AwardItem.objects.filter(experiment=exp,visible=True), } if exp.about_file: context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path() return render(request,'about_experiment.html', context, ) urls.py url(r'^about/(?P<ex_link_name>\w+)', lazer.views.about_experiment, name='lazer.views.about_experiment'), source page experiment.html <h1>Experiment: {{ exp.name }}</h1> <h2>Status -- {{ exp.get_status_display }}</h2> <!--<h2>Consent Form: {% if exp.current_consent_form %}{{ exp.current_consent_form }}{% else %}<span style="color:red;">No Consent Form</span>{% endif %}</h2> <h2>Amt Consent Form: {% if exp.current_amt_consent_form %}{{ exp.current_amt_consent_form }}{% else %}<span style="color:red;">No Consent Form</span>{% endif %}</h2>--> {% if pi_instructions %} {% load ssi %} {% ssi pi_instructions %} {% endif %} <h2><a href="{% url 'lazer.views.about_experiment' exp.link_name %}">About</a></h2> <!-- Form below About --> <form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="post"> <label>Researcher Name(s):<input type="text" name="researcher-name"> <lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study-summary"></textarea> //<label>Upload your IRB approval letter: <input type="file" id="irb-file" size="50"> <input type="submit" value="Submit"> </form> <!-- Form ends About --> destination page about_experiment.html <div class="tab-content"> … -
ProgrammingError when deploying django
I have an application i built that runs perfectly on local machine but once I deploy it I get a 500 server error. The logs print this error... ProgrammingError: relation "land_property" does not exist LINE 1: ...video", "land_property"."featured_video_url" FROM "land_prop... ^ I think it's a problem with my postgres db since my local machine runs the app just fine with sqlite. I'm fairly new to programming and am brand new to django so your help is appreciated -
zurb foundation into an existing django project
i would like to use Foundation 6 in my django project but it seems hard to do. To work with sass, I have to use the cli and create a foundation project and it's not what I want because I already have a django project. I tried to copy all files from scss folder into django but I always have errors when sublim text compile files to css. Do someone has an experience with the same case ? -
[Consul-template]Config file added extra space line when launch to filesystem via consul-template
all: I tried to use consul-template as a part of configuration center solution as following: local config -(push)-> git -(webhook write kv)-> consul -(consul-template)-> pro-env i added md5sum funtion in git-webhook(django) for check. I found out the md5 value of local config and value read directly from consul are the same, but the config launch into pro env via consul-template will have one extra space line, so the md5 value is different from the value in other steps, does any one met similar problems or have any idea to handle it? Tks a lot~~ -
jquery and css code isnot working in django proj
i was trying to create a slider using jquery and css in django (python 3).However, the jquery and css code isn't working! here is the code for css * {box-sizing:border-box} /* Slideshow container */ .slideshow-container { max-width: 1000px; position: relative; margin: auto; } .mySlides { display: none; } /* Next & previous buttons */ .prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; margin-top: -22px; padding: 16px; color: white; font-weight: bold; font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0; } /* Position the "next button" to the right */ .next { right: 0; border-radius: 3px 0 0 3px; } /* On hover, add a black background color with a little bit see-through */ .prev:hover, .next:hover { background-color: rgba(0,0,0,0.8); } /* Caption text */ .text { color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; bottom: 8px; width: 100%; text-align: center; } /* Number text (1/3 etc) */ .numbertext { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: 0; } /* The dots/bullets/indicators */ .dot { cursor:pointer; height: 13px; width: 13px; margin: 0 2px; background-color: #bbb; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease; } .active, .dot:hover { background-color: #717171; } /* Fading animation */ … -
How to use subprocess module in Django website
I am developing a website in Django and I need to run some R scripts in the background thread. But I want this thread to be in another process and not the main one. Only because whenever I use os.chdir(), a rare error comes stating that manage.py file was not found. So I want to use change directory function for a child process and not the main one. -
PostOffice Django cannot find template when sending mail
I'm running into this exception: Exception: EmailTemplate matching query does not exist. The code responsible to sending emails: matching_keywords = filter(lambda keyword: keyword.keyword in instance.headline, Keyword.objects.all()) for subscription in KeywordSubscription.objects.filter(keywords__in=matching_keywords).distinct(): user = subscription.user send_articles([user.email], 'keyword_email_match', {'article': instance}) def send_articles(emails, template, context): return mail.send( emails, 'Messenger <no-reply@externalthreats.com>', template=template, context=context, ) And when I check the db for the email template: keyword_email_match keyword match Somestuff here - {{ article.headline }} March 2, 2017, 6:12 a.m. I definitely see the template. Any reason why this would happen? -
<picture> tag doesn't work in django
I found out today about the <picture> tag, which can be used to change to a smaller image when the display width gets too small. Anyways, I followed this example: <picture> <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg"> <source media="(min-width: 465px)" srcset="img_white_flower.jpg"> <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;"> </picture> And I implemented it in Django as such: <picture> <source media="(max-width:768px)" srcset="{% static 'img/keyclubsmall.png' %}"> <source srcset="{% static 'img/key.png' %}"> <a href = "/"><img src = "{% static 'img/key.png' %}" style = "margin-right: auto; margin-left: auto;" class = "img-responsive"></a> </picture> I double checked on the urls in Chrome and they both work. The issue is that if I shrink the display width, Chrome ignores <picture> and defaults straight to the image I defined using <img>. Given it's been about 3 ~ 4 years since <picture> was introduced into HTML5, I'm not sure at all why <picture>'s having problems loading. -
Sending a file as an attachment for email in Django
I am trying to send a file as an attachment in an email, the file is submitted through a web form. My views.py is as shown below, the problem I am facing is the attached file when seen in the outlook mail doesn't have any content in it. Is there something that I am missing here? if request.method == 'POST': form = RequestForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.info(request, '') subject = 'abc' message = 'xyz' attachment = request.FILES['attachment'] mail = EmailMessage(subject, message, '', ['']) mail.attach(attachment.name, attachment.read(), attachment.content_type) mail.send() -
Django inclusion tag takes_context TemplateDoesNotExist error
Does anybody know how to correct the error when takes_context is used with inclusion tag? I believe the problem may lie with the variable associated with context[] for the template tag output, but I'm not exactly sure what should go inside the bracket. The logic for rendering is in views.py (\mysite\blog\views.py): def DJ_LastDay(request): p = Post.objects.latest('Day') posts = Post.objects.filter(Day=p.Day) return render(request, 'blog/DJ_LastDay.html', {'posts': posts}) The inclusion tag (\mysite\blog\templatetags\index_table.py): from django import template from blog.models import Post register = template.Library() @register.inclusion_tag('index_table.html', takes_context=True) def DJ_LastDay(context): return {'posts': context['posts']} Parent HTML snippet for the inclusion tag (\mysite\blog\templates\blog\DJ_LastDay.html): <div id="section" style="white-space:nowrap;"> <!--Margin added to keep element to the right of aside bar--> <ul> <li>Period to display:</li> <li><a href="{% url 'blog:DJ_LastDay' %}">Last Trading Day</a></li> <li><a href="{% url 'blog:DJ_LastWk' %}">Last Week</a></li> <li><a href="{% url 'blog:DJ_LastMnth' %}">Last Month</a></li> <li><a href="{% url 'blog:DJ_LastQtr' %}">Last Quarter</a></li> <li><a href="{% url 'blog:DJ_LastYr' %}">Last Year</a></li> </ul> </div> {% load index_table %} {% DJ_LastDay %} {% endblock %} Child HTML template (\mysite\blog\templates\blog\index_table.html): <table id="myTable" border="8" style="border-collapse: collapse; width:1000px;"> <caption>DJ Index ({{ posts|length }} symbols returned) - Last Day ({% with posts.0 as 1st %} {{ 1st.Day }} {% endwith %}) </caption> <thead> <tr style="color:white;background:black;"> <th>Symbol</th> <th>Price</th> <th>Name</th> </tr> </thead> <tbody> {% for post … -
How to run a separate thread on app startup in Django 1.11
I have a Django project that I requires the database being updated daily. I want to do this by having a separate thread, instantiated at startup in apps.py, that downloads a large (>2GB) csv file every day, then adds all entries in that file to the project's MySQL database. After Googling, it seems the preferred way of doing this (at least as of ~3 years ago) is by using Celery to create a distributed task queue and incorporating it with a broker. However, having no experience with Celery, or any distributed systems, this seems overly complex and is definitely overkill for my project. Is there a simpler way to achieve this? -
Schema of an inventory tracking system: should I use Addresses or GPS coordinates?
I'm designing the schema for an inventory tracking system, and I'm using Django. I want to track the location of the stock, which can be in storage or in the delivery vehicle, so that if a new order pops up and a delivery vehicle is in the vicinity, I can tell the delivery vehicle to send the stock there instead of looking at the 'nearest possible storage'. But now a Stock can have both an Address and a GPS coordinate, and depending on the stock status, one of them is more important than the other. e.g. if the stock is in storage, the address is important, the GPS coordinates aren't. if the stock is in the vehicle, there is no address, and only GPS coordinates. if the stock is with the customer, the address is important. I'm not sure how to setup the schema in this case. Should a Stock have both address and gps coordinate columns, or should I put the address and GPS coordinates into a separate model called Location? Or is there a better way? -
Handling Django/Postgres Natural Foreign Key Cascading Updates
In my application and database, I have Compound and Name models. # possible names of compound class Name(models.Model): compound_name = models.TextField(primary_key=True) # compound class Compound(models.Model): # unique id for the compound compound_id = models.AutoField(primary_key=True) # name representing the compound primary_name = models.ForeignKey(Name, db_column='compound_name', null=True, db_index=True, on_delete=models.PROTECT) What I'd like to have happen is when I change a name, say 'apsirin' to 'aspirin', this change would cascade to my Compound. Currently, because of the way Django handles these FK relationships, this doesn't work. If I update a name entry in django, it actually just creates a new entry, and the old compound retains the linkage to the compound. I've thought of 3 possible solutions, but I'm not quite sure what all the drawbacks are of each. make a custom 'update' function for my names, that first gets/creates the new name entry, finds all the compounds/other link tables with references to the old name, and then replaces all of the old name values with the new name values, before finally deleting the old name. Possible drawback is that I don't know how this would work if someone was using django admin to update names. Use signals to intercept an update before it … -
Custom SQL functions in Django test database
I'm creating unittest tests for Django with PostgreSQL database. I'm trying to invoke a function which is in the project database, but the test fails because it doesn't find that function. I think the reason is because the test database is created when the test is running, and it not load the functions in the original database. My question is, ¿how could I include that function in the Django test database? -
Add new default permission project wide Django
I need to add a new "read" permission for all models in my project including third party ones and searching for a DRY solution I came up with this: from django.apps import AppConfig Class CoreConfig(AppConfig): name = 'core' def ready(self): from django.contrib.auth import management from django.db.models.options import Options _get_django_builtin_permissions = management._get_builtin_permissions def _get_cate_builtin_permissions(opts): if set(Options(None).default_permissions) <= set(opts.default_permissions): opts.default_permissions += ('read',) return _get_django_builtin_permissions(opts) management._get_builtin_permissions = _get_cate_builtin_permissions This code lives in the apps.py module of my first django app and i'ts working flawlessly, hoever it's annoying to me cause I'm accesing and mokey patching a private member of the management module and that looks too hacky to me, is there another DRY solution which allows me to do the same thing? I know I can redefine the class Meta of all models like this: class Foo(models.Model): class Meta: default_permissions = ('add', 'change', 'delete', 'read') But that doesn't feel right either cause my project have 30+ models that would need the same change, including third party ones. -
Cannot set field in serializer with context and SerializerMethodField
So the back story is I have a model that contains 3 fields. One is just filled in with a default, the other is passed in with the API request, the last is calculated in the view. I can't figure out how to get both the request.data and the calculated value into the serializer. Here is my model: import re from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.db import models from django.utils import timezone URL_MAX_SHORT_ID_LEN = 12 # Maximum length for IE and several other search engines and protocols is # 2047/2048. URL_MAX_URL_LEN = 2047 class URL(models.Model): short_id = models.CharField(max_length=URL_MAX_SHORT_ID_LEN, primary_key=True) url = models.URLField(max_length=URL_MAX_URL_LEN) added_date = models.DateTimeField('date added', default=timezone.now) def clean(self): # TODO: make max length and possible chars a setting or global variable if re.match('^[a-zA-Z0-9]{1,' + str(URL_MAX_SHORT_ID_LEN) + '}$', self.short_id) is None: raise ValidationError({'short_id': 'only a-zA-Z0-9 valid chars and max length of ' + str(URL_MAX_SHORT_ID_LEN) }) def save(self, *args, **kwargs): self.full_clean() super(URL, self).save(*args, **kwargs) def __str__(self): return str(self.__class__) + ': ' + str(self.__dict__) Here's is my serializer: from rest_framework import serializers from url_shortener.models import URL class URLSerializer(serializers.ModelSerializer): short_id = serializers.SerializerMethodField() class Meta: model = URL fields = ('short_id', 'url', 'added_date') read_only_fields = ('added_date',) def get_short_id(self, obj): return … -
Django form tools Form Wizard - Saving to database
I'm using the django-formtools more specify Form Wizard to split a form into multiple steps. I have this two model Forms class StrategicDnaValuePropositionForm(forms.ModelForm): title = "Adn Estratégico y Propuesta de valor" class Meta: widgets = { 'familiar_enterprise':forms.RadioSelect, 'enterprise_concepts':forms.RadioSelect, 'value_purpose_target':forms.RadioSelect, 'competition_differentiation':forms.RadioSelect, 'goals_objectives':forms.RadioSelect, 'avoid_competition':forms.RadioSelect, 'enterprise_strategy':forms.RadioSelect, } model = StrategicDnaValueProposition fields = ('familiar_enterprise', 'enterprise_size', 'enterprise_concepts', 'value_purpose_target', 'competition_differentiation', 'goals_objectives', 'avoid_competition') class MarketingSalesForm(forms.ModelForm): title = "Mercadeo y Ventas" class Meta: widgets = { 'key_activities':forms.RadioSelect, 'new_clients_strategies':forms.RadioSelect, } model = MarketingSales fields = ('key_activities', 'new_clients_strategies',) In my views.py I've subclass SessionWizardView of this way: class DiagnosticToolWizard(LoginRequiredMixin, SessionWizardView): template_name = 'enterprise_process/diagnostic_form.html' def done(self, form_list, **kwargs): # We process the form data with the process_form_data function form_data = process_form_data(form_list) return render_to_response('done.html', {'form_data': form_data}) My process_form_data function is: def process_form_data(request, form_list): user = request.user # Populate the forms and Instances form_list_topics=[] # We create a list with all clean information of the forms which will # be processed form_data = [form.cleaned_data for form in form_list] # Add all form instances created to form list topics form_list_topics.append({ 'form1': MarketingSalesForm, 'title': "Mercadeo y Ventas", 'form2': StrategicDnaValuePropositionForm, 'title': "Adn Estratégico y Propuesta de valor", 'instance': user.enterpriseprofile, }) if request.method == 'POST': # We iterate by each form_list_topics dictionary element and # compose a … -
How to use two databases with django application?
I am building a django blog and i need to use .sql database to be able to use a table named users. I put the database in the same directory with sqlite.db file and edited the settings like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'must-knowledge': { 'ENGINE': 'django.db.backends.sql', 'NAME': os.path.join(BASE_DIR, 'must-knowledge.sql'), }, } then based on this question Using existing database in Django, i tried to run the command: python manage.py inspectdb --database=must-knowledge ,but a strange error appeared up which is: from .models import Post,Comment ImportError: cannot import name 'Post' so how to solve the error and make my application use both sqlite databse and a table from the .sql database "users" to allow the user to login in my application without the need to registration? -
How do I add a background image for a div container?
So I am having a bit of trouble inserting an image inside of a div container. At the top of my page I have a fixed navbar and, underneath the navbar, I have a jumbotron div with a div container with the name of the company as well as the tagline. Instead of there being a bg color for the div jumbotron/div container, I would like there to be an image instead that relates to the services and products that are being provided. I am using Python Django to create the site and thus am using Jinja to implement static files such as images. Below is the code that I've used that does not work. I would like to be able to implement the image using this same Jinja method of static files rather than url(path to image here)... help? <div> <div class="jumbotron"> <div class="container" style="background-image:{% static 'company/img/familypic.jpg' %}"> <center><h2>Whatever Text Here</h2></center> <center><h4>Whatever Tagline Here</h4></center> </div> </div> </div> -
Adding javascript to an extended django template for google analytics
I have a nice little index.html file, it is an extended template and its parent is a base.html file (well in my case base2.html). I was trying to add a google analytics code snippet to some files on my site and it turns out, if I add anything in the tag on my extended templates, it is like the script code is ignored. Is there something I am doing wrong? I know I can add it just fine to base2.html, but then that would track for ever single hit since that is the parent for a lot of my pages on the site. -
has_many polymorphic relationship where our _type field is an int?
We have an app in Rails 4 (but soon to be Rails 5) that has a polymorphic log class that we inherited from a Django app. In a traditional polymorphic relation, the objects would have source_type and source_id, which would be things like 'some_class' and 123. In our little model, we have content_type and content_id which unfortunately map to two ints, where the int in content_type further points to a ContentType model that -- to further complicate things -- dont map to Rails-ey types ('some_type' but rather django-ey 'some type class'. It's a mess. Is there any way to override the value used in looking in a polymorphic association (e.g. instead of using 'some_class', use 11) -- but just for the association? There is an answer for a problem somewhat similar to ours, but it is 4 years old and it overrides association_class. We still use some of this strange Django voodoo elsewhere in our codebase, so overrides feel like they'd cause more problems than solve.