Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Html/Django - loading static image from disk failure
I am trying to load an image into html from my disk. sending the template 'context': context = { 'photo': "'projectweekapp/images/1.jpg'" } Referencing the image statically works correctly as so: <img src="{% static 'projectweekapp/images/1.jpg' %}" alt=""> but when I try this: <img src="{% static {{photo}} %}" alt=""> I receive an error. That read "Could not parse the remainder: '{{photo}}' from '{{photo}}'" Likewise, if I change my python to look like this: context = { 'photo': "{% static 'projectweekapp/images/1.jpg' %}" } And reference the context as so: <img src="{{photo}}" alt=""> I receive another error reading "Failed to load resource: the server responded with a status of 404 (Not Found)" I'd like some help figuring this out before I waste my whole night running in circles. Thankyou! -
Download a file to heroku process it and send as an attachment
I'm trying to do the following: 1. Download a pdf file from S3 to my heroku. 2. Process the pdf. 3. Email the pdf as an attachment. Is it possible? If yes, could you please give me a tip how? I'm running Django app. Thank you in advance -
Django Admin 'regroup' tag takes five arguments
I am trying to add a chart on django admin and i got this error. If someone could help, i would owe you a lot! This is the line that fires the error: {% regroup cl.queryset | dictsort: "location" by get_location_display as location_list %} {% extends "admin/change_list.html" %} {% load staticfiles %} {% block extrahead %} <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script> <script> var randomColorGenerator = function () { return '#' + (Math.random().toString(16) + '0000000').slice(2, 8); }; var options = { responsive: true, maintainAspectRatio: true, legend: { position: 'left' }, title: { display: true }, animation: { animateScale: true, animateRotate: true } }; window.onload = function () { var ctx = document.getElementById("location-chart"); {% regroup cl.queryset | dictsort: "location" by get_location_display as location_list %} var lineChart = new Chart(ctx, { type: 'doughnut', data: { labels: [{% for location in location_list %}'{{ location.grouper }}',{% endfor %}], datasets: [{ data: [{% for location in location_list %}'{{ location.list|length }}', {% endfor %}], backgroundColor: [{% for location in location_list %}randomColorGenerator(), {% endfor %}] }] }, options: options }); </script> {% endblock %} {% block content %} <h1> Graphs </h1> <hr> <div class="row"> <div class="col-sm-4"> <canvas id="location-chart" style="width: 100px !important;"></canvas> </div> </div> {{ … -
Database problems with heroku/django. Won't keep information after every push
So everytime I make a change to the database in production on heroku, and then I do a push, the database gets reset to whatever is on my local computer. I have tried adding the db.sqlite3 and "pycache" to the gitignore, but that doesn't work. Anyone know what to do with this problem? -
How to render html in Django RSS/Atom feeds for embedding html? (CDATA)
Overview: Hi, I read this page: What is the best way to embed HTML in an RSS feed?, and the django syndication docs, for tips on whether or not I could embed html into RSS/Atom feeds. One of the fields of my BlogPost is an about = models.TextField() field, which has an {% autoescape off %} tag for it's html template, so I could use raw html in there to render some <ol> and <ul>'s, and the objects render just fine when I go to those html pages. Now, I have both feeds set up properly with django's syndication framework. And when I click one of the links to a feed, even though it's an xml page, the BlogPostRSSFeed and BlogPostAtomFeed both return the item.about field the way I want it to look according to the html I wrote. Viewing the source code shows all of the characters are escaped, which I'm fine with as long as it's going to work. But the problem is that I read around that I need CDATA in a template for this to work properly (see the SO link above).` Question: Are feed readers able to render this html properly??? Or maybe only just … -
saving the form within a formset with custom save method having parameters
I have a form with custom save method with parameters. The form is included in an inline formset. How can I save the included form? I have tried multiple ways, none is working. forms.py class FileForm(forms.ModelForm): class Meta: model = File fields = ('filename',) def save(self, user, commit=True, *args, **kwargs): file = super(FileForm, self).save(commit=False,*args, **kwargs) file.user = user if commit: file.save() return file views.py FileFormSet = inlineformset_factory(Contact, File, form=FileForm, extra=1) if request.method == 'POST': contact = Contact() form = ContactForm(request.POST, request.FILES, instance=contact) formset = FileFormSet(request.POST, request.FILES, instance=contact) if form.is_valid() and formset.is_valid(): form.save() instances = formset.save(commit=False) instances[0].save(user=User.objects.get(username=request.user)) This is throwing an error that- save() missing 1 required positional argument: 'user' at instances = formset.save(commit=False). What am I missing here? -
Use generic UpdateView to always edit a single configuration object
What I Need I want to have a global configuration for my app and I want to reuse a generic UpdateView. What I Tried For this purpose I created a model (example fields): class Configuration(models.Model): admin = models.ForeignKey('User', on_delete=models.CASCADE) hostname = models.CharField(max_length=23) A generic Updateview: class ConfigurationView(UpdateView): model = Configuration fields = ['admin','hostname'] And urls.py entry path('configuration/', views.ConfigurationView.as_view(queryset=Configuration.objects.all().first()), name='configuration'), As you can see I want the configuration/ path to link to this configuration and always only edit this one object. I get the error Problem AttributeError: 'Configuration' object has no attribute 'all' Questions How can I hardcode the object into the path in urls.py so that always the first Configuration object is used for the UpdateView? Is there a better way to do this? I simply want to have a global configuration object and want it to be editable and displayable with a template of my choice. -
Difference between hosts
I am building a django backend and I was looking for someone to host it. I am wondering what is the difference between hosts like AWS and GCP and others like a2 hosting ? Because their pricing are a little bit different :/ -
How to view actual redis data with redis channels
I am using Channels Redis for websocket operations. However, I'd like to view exactly what it's saving in redis. How would this be done? Here is what I have so far: >>> import redis >>> r = redis.Redis() >>> r.keys() ['asgi::group:chat_hello', 'asgi::group:chat_lobby', 'asgi::group:chat_hi', 'iTunes+1068285837'] >>> r.get('asgi::group:chat_hello') redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value -
image in block of StreamField is not recognized
This error is shown: 'image' tag should be of the form {% image self.photo max-320x200 [ custom-attr="value" ... ] %} or {% image self.photo max-320x200 as img %} with line 19 {% image block.value as mein_bild %} My template: {% extends "base.html" %} {% load static wagtailcore_tags wagtailimages_tags %} {% block content %} <div class="notiert"> <header> <h1>{{ page.title }}</h2> </header> <div class="body"> {{ page.kurzfassung|richtext }} <p>{{ page.first_published_at }}</p> {% for block in self.notiert_feld %} {% if block.block_type == 'image' %} <p>in if image {{ block.value }}</p> {% image block.value as mein_bild %} <img {{ mein_bild }} width=530 > {% else %} {{ block.value }} {% endif %} {% endfor %} </div> </div> {% endblock %} Line 18 I have used for debugging. If I delete line 19 and 20 the name of the image is shown. -
Overriding UserChangeForm in django
Due to the fact that i don't need to edit all the fields in my form i ve searched for a way to exclude some fields from Userchangeform and i found out that overriding the forms works forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm class UserChangeForm(UserChangeForm): class Meta: model = User fields = ('email',) the problem is that i need to delete that message after the email input Any ideas? -
.txt files in mydocs folder in django doesnt reflect any changes or additions
i became i guess whats called a community memeber today sept 30 2018 becux i want to post a question for a django project problem i still cant really fully solve i am just writing about my situation here if ok with the rules of this forum 1st i will describe the folders and file design/archetieture/structure i guess you call it CONTAINER FOLDER readme.md (inside container folder) sqlite.db (inside container folder) manage.py (inside container folder) MYPROJECT FOLDER (inside container folder) init.py(inside myproject folder) settings.py(inside myproject folder) urls.py(inside myproject folder) wsgi.py(inside myproject folder) MYWEBAPP FOLDER (inside container folder) MYDOCS folder(inside mywebapp folder) many.txt files MIGRATIONS folder(inside mywebapp folder) init.py 0001_initial.py STATIC folder(inside mywebapp folder) some .js and .css files TEMPLATES folder(inside mywebapp folder) teststatic.html MYWEBAPP folder(inside templates folder) home.html init.py(inside top level mywebapp folder and all other .py files below) admin.py apps.py models.py mainlookupinfo.py tests.py filter_docs.py urls.py views.py so if i add or modify .txt files in the MYDOCS folder..it doesnt reflect when i call or look for words in the new added or modifyied .txt files...all that i can look up are the exisiting .txt files that i started with when i created the django project..either with or without a … -
get_absolute_url not working in django 1.7?
I am trying to navigate to my product page by clicking on the href link under the displayed product. But for some reason, the absolute url that is generated is giving me a 404. This is what i tried so far. models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text='Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return 'catalog_category', (), {'category_slug': self.slug} class Meta: ordering = ['-created_at'] verbose_name_plural = 'Categories' class Product(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True,help_text = 'Unique value for product page URL, created from name.') brand = models.CharField(max_length=50) sku = models.CharField(max_length=50) price = models.DecimalField(max_digits=9, decimal_places=2) old_price = models.DecimalField(max_digits=9, decimal_places=2,blank = True, default = 0.00) image = models.CharField(max_length=50) is_active = models.BooleanField(default=True) is_bestseller = models.BooleanField(default=False) is_featured = models.BooleanField(default=False) quantity = models.IntegerField() description = models.TextField() meta_keywords = models.CharField(max_length=255,help_text = 'Comma-delimited set of SEO keywords for meta … -
Set first_name, last_name and email from User model as default value in field
I'm trying to set default values for first_name, lastname and email in my model Got the following model from django.db import models from django.contrib.auth.models import User class Project(models.Model): firstname = models.CharField(max_length=30, blank=True, verbose_name=_("label_general_firstname"), default=User.first_name) lastname = models.CharField(max_length=30, blank=True, verbose_name=_("label_general_lastname"), default=User.last_name) email = models.EmailField(blank=True, verbose_name=_("label_general_email"), default=User.email) When running the migration, I get the following error: ValueError: Cannot serialize: <django.db.models.query_utils.DeferredAttribute object at 0x7f459e8aac50> I got users coming in via an SSO, and they already have certain fields filled out. I want to use these as default values when using a form which uses this model. Have tried several ways, but never got a working result. -
How to do urlconf in django 2.0+
I have created a view at example.views.py, and here is my urls.py file: from django.urls import path urlpatterns = [ path('/', example.views.index, name='index'), ] However, when I run django's runserver, I get the following error: path('/', example.views.index, name='index'), NameError: name 'example' is not defined What do I need to do to fix this? Quoting the view doesn't help either. -
Django won't connect to remote RDS
When I run 'python manage.py runserver', I get: File "/Users/myusername/.virtualenvs/dashboard-server-PG7390RB/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/Users/myusername/.virtualenvs/dashboard-server-PG7390RB/lib/python3.6/site-packages/psycopg2/init.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) " to address: nodename nor servname provided, or not known name "rdsaddress.us-east-1.rds.amazonaws.com This happened when I updated iterm2, but downgrading did not fix it. I am able to successfully connect to the database using Postico. I am unable to connect to a similar rds using Django as well. I deleted my repository and repulled... Not sure what to do next. -
Elastic Beanstalk - running npm install and webpack on every deployment of Django
I'm trying to use Elastic Beanstalk to deploy my Django server. My problem is that part of my deployment process is to "npm install" from my package.json, and then executing webpack (npx webpack ..... --output main.js) How can I do that while maintaining an easy deployment process (eb deploy) and without committing main.js to the repository? -
TemplateDoesNotExist at /poll/poll/result.html
I get this error TemplateDoesNotExist at /poll/poll/result.html {'Gender': <QuerySet [{'Gender': 'female', 'Diseases': 'Malaria', 'Number': 1}, {'Gender': 'female', 'Diseases': 'cholera', 'Number': 2} I am new to django but what possibly am I doing wrong here.This is the file structure for template.html: mysite/polls/templates/polls/template.html and for result.html its mysite/polls/templates/polls/result.html Views.py from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from . models import MyModel from . forms import MyModelForm from django.db.models import Count from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views.generic.list import ListView class CreateMyModelView(CreateView): model = MyModel form_class = MyModelForm template_name = 'poll/template.html' success_url = 'poll/result.html' class MyModelListView(ListView): model = MyModel def get_queryset(self): queryset = MyModel.objects.values('Gender', 'Diseases').annotate(Number=Count("Gender")) return render('poll/result.html', {'Gender': queryset}) urls.py from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ url(r'^$', views.CreateMyModelView.as_view(), name='abc'), path('poll/result.html', views.MyModelListView.as_view(), name='result'), ] models.py from django.db import models Gender = ( ('male', 'MALE'), ('female', 'FEMALE'), ) Diseases = ( ('cholera', 'CHOLERA'), ('hiv', 'HIV'), ('Malaria', 'MALARIA'), ('Typhoid', 'TYPHOID'), ) class MyModel(models.Model): Gender = models.CharField(max_length=16, choices=Gender, default='MALE') Diseases = models.CharField(max_length=16, choices=Diseases, default='MALARIA') vote = models.IntegerField(default=0) def __str__(self): return self.Gender def __str__(self): return self.Diseases result.html {% extends 'polls/base.html' %} {% block main_content %} <h1></h1> <ul> … -
Designing a MCQ in Django using Forms paradigm?
I'm trying to design a simple MCQ tool in django. My aim is to get something similar to: https://www.w3schools.com/quiztest/quiztest.asp?qtest=CSS in terms of design and behaviour (ie a question with several checkboxes and a submit button which directs me to the next question, until the end where the answers and my score are displayed) so that I can build my own MCQ for revising courses. So far, I managed to store the data (i.e. questions, answers, ...) in a database. I was considering using a form as per the below: [forms.py] from django import forms from .models import Proposition, Question class ReadOnlyText(forms.TextInput): input_type = 'text' def render(self, name, value, attrs=None): if value is None: value = '' return value class QuestionForm(forms.Form): q1 = Question.objects.filter.all()[0] propositions = Proposition.objects.filter(question=q1) choices = ((p.index, p.proposition) for p in propositions) question = forms.CharField(widget=ReadOnlyText, label=q1.question) propositions = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices=choices, ) So in this code, the problem is that I only look at the first question (q1) in my database. And I'm not too sure how to pass in the number of next question for when the user will hit the submit button. But maybe I'm having a hard time here because a Form is not … -
What is the biggest and smallest decimal number that can be stored using Django's DecimalField?
I could not really find anything in the doc. For the field, we need to provide two parameters: max_digits, and decimal_places. class Product(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) The above config stores upto 99999999.99. However, I was wondering if there is a maximum or minimum limit for this field, similar to how these constraints exist for other fields. For instance, IntegerField can store only from -2147483648 to 2147483647. -
2 similar views and templates but only one template shows form options
I'm really stuck on this one. I have a working view/template that has a form select option that populates options from my model views.py def random(request): classroom = Classroom.objects.filter(teacher=request.user).order_by('course_block') classblock = request.GET.get('class_block') students = Student.objects.all().filter(classroom__course_block=classblock) nicknames = [s.nickname for s in students] data = serializers.serialize("json", students, fields = ("nickname", "attend")) student_names = json.dumps(list(nicknames)) context = {'students': students} context['classroom'] = classroom context['student_names'] = student_names context['data'] = data template = loader.get_template('randomizer/randomize.html') print (data) return render(request, 'randomizer/randomize.html', context) ramdomize template {% extends 'randomizer/base.html' %} {% load static %} {% block body %} <div id="djangorandom"> {{ classroom.id }} <form action="{% url 'randomizer:random' %}" method="get"> {% csrf_token %} <div class="form-group"> <select class="form-control" name="class_block"> {% for room in classroom %} <option value={{ room.course_block }}>{{ room.get_course_block_display }}</option> {% endfor %} </select> </div> <span><input class="btn btn-default" type="submit" value="Submit"></span> </form> </div> Page source returns: <div class="form-group"> <select class="form-control" name="class_block"> <option value=11>Block 1-1</option> <option value=13>Block 1-3</option> <option value=14>Block 1-4</option> <option value=P13>Pair 1-3</option> </select> </div> Now I've copied a lot of this code for a slightly different template and purpose: def pair(request): classroom = Classroom.objects.filter(teacher=request.user).order_by('course_block') classblock = request.GET.get('class_block') students = Student.objects.all().filter(classroom__course_block=classblock) nicknames = [s.nickname for s in students] data = serializers.serialize("json", students, fields = ("nickname", "attend")) student_names = json.dumps(list(nicknames)) context= {'classroom': … -
Update User informations (Django user model ) in a modal (Bootstrap modal) (django 1.8)
So what i m trying to do is to edit the extended user model information in a modal and get the result without refreshing the page , I ve managed to do the edit in another page using the UserChangeForm and it worked fine , I ve tried to use a bootstrap modal but it didn't work , Any help or recommandations please I m working with Django 1.8 -
How can I reference to model field in Django using String?
Consider my model (MODEL) has field has attribute NAME. I want to reference to that model attribute using string. eg. var = Model.objects.get( pk=1 ) var.str('NAME') = value while trying with string it's giving me error : can't assign to function call P.S.: I know for finding a value of attribute from string I can use getattr() but since I want to assign value, this method isn't helpful. -
Django (v2+) and Django REST Framework: what to do with "path" interferes?
I am new to Django REST Framework... but am figuring it out via the tutorials, quick start, internet and fiddling. However, I did not find a clear solution to the following problem. Suppose one wishes to write an api that requires an integer. Using Django's path in the url patterns one might try: urlpatterns = [ ... path('my_api/<int:integer_argument>', views.my_api, name='my_api'), ... ] and in their view @api_view(['GET']) def my_api(request, integer_argument): # do stuff return JsonResponse({'int': integer_argument}) Note: here I use JsonResponse just to keep this simple, but most likely that/those argument(s) go into a class/model and into serializer to be returned by Response(serializer.data). So now if they were to test an application which calls this api (in development mode) http://localhost:8000/my_api/1 they should get {'int':1}. However, if they were to call http://localhost:8000/my_api/e they get the either the debug page or Bad Request (400) as html. Lets assume that the person making the api did have proper error handling in place for to validate the arguments (in this case that integer_argument is an integer). Now path is getting in the way, whereas for a django website this might be the desired result. What is the RESTful and django REST framework endorsed way … -
Performance Django/Python calling modules
To the experts on Django/Python: Is there a significative difference in performance between calling, as an example: from foo.views import foo, foo2, #... and son on than: from foo import views path('foo', views.foo, name="my_view"), path('foo2', views.foo2, name="my_view") # ... and so on Having in mind of course that you have tons of views or other classes, methods, etc.