Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to pass a variable to a form
So, I need to pass quantity to a corresponding form to be able to select quantity of books while adding them to a cart. Note that quantity is a Book model IntegerField. This solution cause a KeyError at self.choices = kwargs.pop('q') cart/forms.py class CartAddProductForm(forms.Form): choices = int() quantity = forms.TypedChoiceField(choices=[(i,str(i)) for i in range(1,choices)], coerce=int, label=_('Quantity')) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput, label=_('Update')) def __init__(self, *args, **kwargs): self.choices = kwargs.pop('q') super(CartAddProductForm, self).__init__(*args, **kwargs) bookstore/views.py def book_detail(request, id, slug): cart = Cart(request) language = request.LANGUAGE_CODE book = get_object_or_404(Book, id=id, translations__language_code=language, translations__slug=slug, available=True) cart_book_form = CartAddProductForm(q=book.quantity) r = Recommender() recommended_books = r.suggest_books_for([book], 4) return render(request, 'shop/book/detail.html', locals()) cart/views.py @require_POST def cart_add(request, book_id): cart = Cart(request) book = get_object_or_404(Book, id=book_id) form = CartAddProductForm(request.POST, q=book.quantity) if form.is_valid(): cd = form.cleaned_data cart.add(book=book, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') Traceback click here -
Do I need to backup a database after an upgrade?
I am using python and Django for my project. I have upgraded PostgreSQL version from 9.6 to 10. Before that, I made a backup of my database. ./manage.py dumpdata > db.json After a successful upgrade, I had no idea whether the database will intact. But upon checking, I found the database was okay. I think it is necessary to backup before an upgrade, but do I need (or recommended) to load the backup data back to the cluster again? Or is there any recommended way of upgrading the database. -
Is there any way to use elasticsearch with mongoengine?
I've got Django project using mongoengine. Large part of it uses aggregation pipeline queries to perform complex document search. I want to use elasticsearch in this project to speed up the search, but mainly for educational goal. I know that haystack is a good way to use ES in django projects, but it works with Django ORM only. So is there any way to use ES with mongoengine django apps? -
Django related problems with python
I am unable to understand what's happening in django I know python3 but I'm working on frameworks for the first time. Please help me -
Django admin 2.0 - Make a file downloadable in change view
I have a table with a FileField and some other attributes with information about the file. Currently, when i click on a row it sends me to the change page for that row, which has a link to visualize the FileField, which is a .txt file. I managed to make it display via the browser on click, but what I want it to do is to intercept the click event and return an HTTPResponse to let the user download it. How can I do that? -
How to auto-populate state dropdown in django-cities-light on choosing a country?
I have successfully integrated Django cities light into my app and all migrations are made, Also I have added the country field to my user profile form. How can I auto-populate the State and City Field on the basis of choice of Country and State by the user. Current Models: ``` class Country(AbstractCountry): pass connect_default_signals(Country) class Region(AbstractRegion): pass connect_default_signals(Region) class City(AbstractCity): timezone = models.CharField(max_length=40) connect_default_signals(City) class Profile(models.Model): class Meta: ordering = ('user',) verbose_name = 'Profile' verbose_name_plural = 'Profiles' GENDER_CHOICES = ( ('m', 'Male'), ('f', 'Female'), ('o', 'Other'), ('n', 'Not Specified') ) user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(blank=True, null=True, help_text='Your date of birth') gender = models.CharField(max_length=9, choices=GENDER_CHOICES, blank=True, null=True) mail_notifications_allowed = models.BooleanField(default=True, help_text='Get all your notifications via mail') newsletter = models.BooleanField(default=True, help_text='Get notifications our new services and features') use_gravtar = models.BooleanField(default=False, help_text='One avatar to rule them all!') beta_user = models.BooleanField(default=False, help_text='Test and help us find bugs in our unreleased features') avatar = models.URLField(null=True, blank=True, help_text='Profile picture URL') avatar_small = models.URLField(null=True, blank=True, help_text='Profile picture smaller URL') country = models.ForeignKey(Country, null=True, blank=True, on_delete=models.PROTECT) ``` -
django.db.utils.OperationalError: no such table: Schedule_swimmingscore
So, This is my model SwimmingScore: class SwimmingScore(models.Model): team = models.ForeignKey(Team, related_name='team_swimming', on_delete=models.CASCADE) gold = models.IntegerField(default='0') silver = models.IntegerField(default='0') bronze = models.IntegerField(default='0') fourth = models.IntegerField(default='0') points = models.IntegerField(default='0') I used the command python manage.py makemigrations and then python manage.py migrate . So when i am opening admin through website, it is showing "no such table", i have confirmed it through python manage.py dbshell >.table , there is actually no table forSwimmingScore, but when i am re-runnung python manage.py makemigrations, it is behaving as if model is actually migrated, for crosscheck , i have altered one field, and on terminal it is actually showing it: Migrations for 'Schedule': Schedule/migrations/0003_auto_20180707_0815.py - Alter field team on swimmingscore Whats the standard procedure to handle such cases? I am totally stuck in it. I am using sqlite3 as database in Django. -
django modifying database object
I am working on an attendance management system. I want to modify attendance of students. class Subject(models.Model): subject_name = models.CharField(max_length=20) #attendance = models.ForeignKey(Attendance, on_delete = models.DO_NOTHING) attendance = models.IntegerField(default=0) def __str__(self): return self.subject_name class Section(models.Model): section_name = models.CharField(max_length=20) subject = models.ManyToManyField(Subject) def __str__(self): return self.section_name class Student(models.Model): rollno = models.IntegerField() name = models.CharField(max_length=20) section = models.ForeignKey(Section, on_delete = models.DO_NOTHING, default=0) def __str__(self): return str(self.rollno) + self.name Here is my template. (Student.html) {% for i in data %} <tr> <td>{{ i.rollno }}</td> <td>{{ i.name }}</td> <td> <button class='btn btn-danger' id='{{i.rollno}}' on click = "{{ i.section.subject.get(subject_name='java').attendance)|add:1 }}"> </td> </tr> {% endfor %} I am getting error in using .get() method in template. I want to add (+1) attendance on a button click. -
Can I get Django model objects as singletons?
When I call Models.get() for the same id it returns different Python objects: print(Book.objects.get(id=1) is Book.objects.get(id=1)) >>> False I wonder if it is possible to change this behavior, maybe with some custom Model Manager. It could internally store some registry for all retrieved objects and override get_queryset() to make it use objects from this registry if they have already been retrieved. Why do I can be helpful I have a model ServerCredentials which stores login and password. I have multiple consumers that connect using the same credentials. Since only one connection to server is allowed, it would be convenient to store transient connection information (e.g. auth token) as a field of ServerCredentials object, but not in database. If model objects could be singletons, consumers could easily share auth tokens just by using a field of ServerCredentials. Without it, I have to make some registry manually, but I fell that it should be done on ModelManager's side. Is it a possible to cache objects in a registry on ModelManager's side? Is it a good idea? Are there implementations for that? Many thanks in advance! -
Redirect user to a custom link after login in Django
I have been going through lots of similar questions and solutions from the past couple of days but not able to find a working solution in my case. My code is : urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login ,{'template_name': 'login_template.html'}), url(r'^dashboard/(?P<slug>\w+)/$', login_required(DashboardHomeViewClass.as_view()),name = "dashboard"), ] views.py class DashboardHomeViewClass(View): def get(self, request, *args, **kwargs): device_user_objects = device_user_data.objects.filter(User_Name = request.user.username) device_parameter_objects = device_parameter_data.objects.all() device_alias_list = [] device_id_list = [] queryset = [] light_list = [] for device in device_user_objects: device_alias_list.append(device.Device_Alias_Data) device_id_list.append(device.Device_Id_Data) default_device = device_id_list[0] slug = self.kwargs.get("slug") for device_id in device_id_list: if slug == device_id: queryset = device_parameter_objects.filter(Device_Id = slug) for data_object in queryset: light_list.append(data_object.Light) recent_light = light_list[-1] context_logged = {'device_user_objects': device_user_objects, 'light_list': light_list, 'recent_light': recent_light} return render(request, "dashboardhometemplate.html", context_logged) class LoginViewClass(View): def get(self, request, *args, **kwargs): context = {} return render(request, "login_template.html", context) def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) user = form.get_user() login(request,user) return redirect('/') else: form = AuthenticationForm() context = {'form':form} return render(request,'login_template.html', context) HTML part in which this context is being used in dashboardhometemplate.html {%for item in device_user_objects%} <li> <a href="/dashboard/{{item.Device_Id_Data}}" aria-expanded="false"><i class="fa fa-bar-chart"></i><span class="hide-menu">{{item.Device_Alias_Data}}</span></a> {% endfor %} Now what I want to do is To redirect the user after login to the page … -
Running a django app. with gunicorn for the first time. No module named main
I am trying to run a django using gunicorn following a tutorial.This is what I type gunicorn main.wsgi:application and this is the error that I get 2018-07-07 06:28:34 +0000] [6826] [INFO] Starting gunicorn 19.9.0 [2018-07-07 06:28:34 +0000] [6826] [INFO] Listening at: http://127.0.0.1:8000 (6826) [2018-07-07 06:28:34 +0000] [6826] [INFO] Using worker: sync [2018-07-07 06:28:34 +0000] [6829] [INFO] Booting worker with pid: 6829 [2018-07-07 06:28:34 +0000] [6829] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/venvProfile/lib/python3.5/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) ImportError: No module named 'main' [2018-07-07 06:28:34 +0000] [6829] [INFO] Worker exiting (pid: 6829) [2018-07-07 06:28:34 +0000] [6826] [INFO] Shutting down: Master [2018-07-07 06:28:34 +0000] [6826] [INFO] Reason: Worker failed to boot. This is what my directory structure looks like venvProfile |__ProfileWeb |_manage.py |_db.sqlite3 |_main |___init__.py |_urls.py |_settings.py |_wsgi.py Why is the command gunicorn main.wsgi:application failing ? Am I doing something wrong here ? -
Server side Framework vs Client side Frameworks
So I've recently been learning Django and it took me a while to understand that it was a Server side framework, I had previously only worked with Vue/AngularJS and I assumed Django was similar because of the same offers (for loops, if statements etc...). Relating to that note, what does Django actually offer that Vue/etc do not? Are client-side frameworks really only useful to produce SPA's? -
Django admin site customization
I am new to django. I have searched a lot, but none of them solved my problem. I want to override admin site templates only and not functionality (only some UI enhancements). Most of topics said to create a new directory in root named templates and inside it, create an admin folder and inside that, copy the base_site.html from current admin directory. base_site.html that is copied: {% extends "admin/base.html" %} {% block title %} test new admin UI {% endblock %} {!-- I have changed this, but it is not applied --} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} and in my index.html, I cannot extend this base_site.html (it is not recognized by my IDE at all!) and in my settings.py I have: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates/admin', os.path.join(PROJECT_PACKAGE, 'templates'), ], 'APP_DIRS': True, . . . . . . . . . . . }, ] then I copied index.html from the admin folder and changed it a bit, but the previous admin templates are still loaded (even changing base.html in my new admin directory was not applied to loaded admin … -
Proper usage of viewset queryset
According to Django REST framework documentation, the following two code snippets should behave identically. class UserViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving users. """ def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() But the way I interpret it, in the first case the query User.objects.all() is run with every api call, which in the second case, the query is run only once when the web server is started, since it's class variable. Am I wrong ? At least in my tests, trying to mock User.objects.all will fail, since the UserViewSet.queryset will already be an empty Queryset object by that time. Someone please explain me why shouldn't the queryset class argument be avoided like pest and get_queryset be used instead ? -
Django Channels Frontend and Backend Integration
From what I understand, the frontend and backend are integrated via APIs where the frontend calls on the APIs built by the backend. How does this work when we use Django Channels? I am assuming that it works conceptually the same, where the frontend opens a websocket that calls on an API that is linked to the consumer class in the consumer.py file via the routing.py file. This is similar to Django's DRF where frontend calls on the API that links to views.py via the urls.py file. My question is: In Django's DRF, we could check if the APIs are working by literally typing the API in the browser. How could we check if the routes are working for Django channels? For example, in Django's official tutorial, the API for the websocket to the consumerclass is: ws://127.0.0.1:8000/ws/chat/lobby/ We can't exactly type this in the browser as they use different protocols -- Browsers use HTTP and websockets don't...right? So how would we check that the routes and django channels that we have build from the backend would work in the frontend when it is called in the html files? Because in projects, frontend and backend components are developed as separate projects, … -
Django file not Uploading Rest of the form fields are saved
I'm trying to upload a File with a task creation form. only the file is not being saved. rest of the fields are saved. models.py class Task(BaseModel): project = models.ForeignKey("projects.Project") staff = models.ForeignKey("staffs.Staff") task_start_date = models.DateField() task_end_date = models.DateField() description = models.TextField(blank=True,null=True) category = models.ForeignKey("tasks.TaskCategory") status = models.CharField(max_length=128,choices=TASK_STATUS,default="pending") is_deleted = models.BooleanField(default=False) thefile = models.FileField( upload_to="uploads/designtasks/", null=True, blank=True) technical_design = models.FileField( upload_to="uploads/designtasks/", null=True, blank=True) class Meta: db_table = 'task' verbose_name = _('task') verbose_name_plural = _('tasks') ordering = ('staff',) class Admin: list_display = ('staff',) def __unicode__(self): return self.description forms.py from django import forms from projects.models import Project from django.forms.widgets import TextInput, Select, Textarea from django.forms.fields import Field from tasks.models import Task, TaskCategory setattr(Field, 'is_checkbox', lambda self: isinstance(self.widget, forms.CheckboxInput)) from django.utils.translation import ugettext_lazy as _ import autocomplete_light from django.conf import settings from staffs.models import Staff class TaskForm(forms.ModelForm): task_start_date = forms.DateField( input_formats=settings.DATE_INPUT_FORMAT, widget=forms.widgets.DateInput(format="%d/%m/%Y",attrs={'placeholder': 'Enter start date','class':'required datepicker',}), error_messages = { 'required' : _("Task Start Date field is required."), } ) task_end_date = forms.DateField( input_formats=settings.DATE_INPUT_FORMAT, widget=forms.widgets.DateInput(format="%d/%m/%Y",attrs={'placeholder': 'Enter end date','class':'required datepicker',}), error_messages = { 'required' : _("Task End Date field is required."), } ) class Meta: model = Task exclude = ['creator','updator','status','is_deleted'] widgets = { 'project': autocomplete_light.ChoiceWidget('ProjectAutocomplete'), 'staff': autocomplete_light.ChoiceWidget('StaffAutocomplete'), 'description': Textarea(attrs={'placeholder': 'Enter description','class':''}), 'category': Select(attrs={'class': 'single … -
How to send JSON data from JS to views.py file in Django?
I have this javascript in my HTML template: <script type="text/javascript"> $('a[data-scrollto]').click(function(event) { //event.preventDefault(); var target = $(this).data('scrollto'); var position = $(target).offset().top - 70; // Target position - navbar height $('html, body').animate({ scrollTop: position }); }); $("#example-prompt-5").click(function() { bootpopup.prompt([ { label: "Device ID"}, { label: "Device Alias"}, ], function(new_device_data) { alert(JSON.stringify(new_device_data)); }); }); </script> I want to use the data of Device ID and Device Alias from the new_device_data JSON to POST it into my database. For this purpose, I need to send this JSON to my view.py file. Please help me with a way through this problem. Note: The function: function(new_device_data) is the function that is called when this data is submitted by the user in a modal popup. For modal popups, I am using Bootpopup -
patch Django db connection called from class attribute
Im trying to patch a django object that is an attribute of a Class: from django.db import connections class ClassName(object): db_connection = connections['db_name'] Im trying to patch: class OtherName(ClassName, Model): cursor = self.db_connection.cursor() cursor.execute(sql_query) how can I patch cursor.execute(sql_query)? I have tried: @patch('connections.cursor.execute', new=patch_pd_sql) I get the error ImportError: No module named connections.cursor If I try to patch the object: @patch.object(ClassName.db_connection.cursor.execute, return_value='Agent') I get: 'function' object has no attribute 'execute' How should I do it? -
How to pass data to database using WYSIWYG HTML Javascript Editor with Django.
After a lot of trial and error, I'm stuck. I am trying to create my own WYSIWYG editor with Django. I have created the WYSIWYG editor, I just can't seem to figure out how to incorporate my editor/HTML/Django form altogether. Here is my HTML: <!DOCTYPE html> {% extends "base1.html" %} <title>{% block title %} Create Information {% endblock %}</title> {% block body_block %} <form method="POST" enctype="multipart/form-data" autocomplete=off> <style> div#textEditor{ margin: 0 auto; width: 750px; height: 300px; } div#theRibbon{ border-bottom: none; padding: 10px; background-color: rgb(40,110,89); color: white; border-radius: 8px 8px 0px 0px; } div#richTextArea{ border: 2px solid rgb(40,110,89); height: 100%; width: 746px; background-color: white; } iframe#theWYSIWYG{ height: 100%; width: 100%; } div#theRibbon > button { color: white; border: none; outline: none; background-color: transparent; cursor: pointer; } div#theRibbon > button:hover{ background-color: rgb(20,90,70); transition: all 0.3s linear 0s; } input[type="color"]{ border: none; outline: none; background-color: transparent; } </style> <script> window.addEventListener("load",function(){ var editor = theWYSIWYG.document; editor.designMode = "on"; boldButton.addEventListener("click", function(){ editor.execCommand("Bold", false, null); },false); italicButton.addEventListener("click", function(){ editor.execCommand("Italic", false, null); },false); supButton.addEventListener("click", function(){ editor.execCommand("Superscript", false, null); },false); subButton.addEventListener("click", function(){ editor.execCommand("Subscript", false, null); },false); strikeButton.addEventListener("click", function(){ editor.execCommand("Strikethrough", false, null); },false); orderedListButton.addEventListener("click", function(){ editor.execCommand("InsertOrderedList", false, "newOL" + Math.round(Math.random() * 1000)); },false); unorderedListButton.addEventListener("click", function(){ editor.execCommand("InsertUnorderedList", false, "newOL" + … -
Using different css and removing items for mobile view of django_admin
I want to remove specific items from my Django admin when it's viewed on a mobile device as shown below. Also, when I open my web app on a mobile device I want it to be viewed a little bit different so I want a different css to be loaded. Is there a way of doing that? What I want to remove and what to leave on a mobile device For example I'm adding items like that: admin.site.register(Task, TaskAdmin) admin.site.register(Schedule, ScheduleAdmin) admin.site.register(PaymentAhead, PaymentAheadAdmin) I'm sorry if the question is super obvious and generic, but this is my first ever Django app and I haven't found a solution yet. -
Blog count in django
I am trying to get the count of blogs by author in views.py - author_blog_count but it is giving incorrect value. What can be the correct way of doing it ? Thanks models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogger') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) title = models.CharField(max_length=100) def __str__(self): return self.title views.py def get_queryset(self): return (Blog.objects.filter(published_date__lte=timezone.now()) .order_by('-published_date') .annotate( author_blog_count=Count('author__blogger') ) ) -
how class based views know that they need to call dispatch method
We know that dispatch is the first method that is called when our url hits the CBV(Class Based Views). We also know that to call these views we have to call as_view() with our CBV in our urls.py to make them callable. views.py is shown below class ProductListView(ListView): template_name = "products/list.html" model = Question #Question is a model that is defined in models.py urls.py is shown below urlpatterns = [ url(r'^$',ProductListhView.as_view(),name='list'), ] Now my question is 1. How the CBV(ProductListView) knows that it has to call dispatch() method since we only inherited a generic views class but haven't mention anywhere to call dispatch()? -
integrate PYZK with django
I am trying to add pyzk to my project URL: https://github.com/fananimi/pyzk I do test my finger machine with code example without Django its work well. I do copy to my views.py so my views look like this. here my views.py .... from zk import ZK, const import sys .... class RegEmployee(UpdateView): fields = ('regmachine',) model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) sys.path.append("zk") zk= ZK('192.168.1.201', port=4370, timeout=500) try: conn = zk.connect() conn.disable_device() zk.set_user(self.object.id, self.object.name, 0, '', '1', self.object.id) #zk.enroll_user(self.object.id) zk.enable_device() self.object.regmachine = 1 self.object.mac_IP = '192.168.1.201' except Exception, e: self.object.mac_reg = 'error' #error code finally: if conn: conn.disconnect() self.object.save() return super(ModelFormMixin, self).form_valid(form) .... but its gonna error, this part not executed. try: conn = zk.connect() conn.disable_device() zk.set_user(self.object.id, self.object.name, 0, '', '1', self.object.id) #zk.enroll_user(self.object.id) zk.enable_device() self.object.regmachine = 1 self.object.mac_IP = '192.168.1.201' whats wrong with my code?... thank you! -
Direct To S3 File Upload Django and Heroku
I am trying to setup direct to s3 upload in Django for larger audio files. I basically, followed the Direct To S3 Tutorial from Heroku here https://devcenter.heroku.com/articles/s3-upload-python which is geared more towards Flask. I can not find the get request Django debug is referring too. Thank you in advance for your help. I am getting the following error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/sign-s3/?file_name=piano.wav&file_type=audio/wav Django Version: 2.0 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'django.contrib.sites', 'crispy_forms', 'tinymce', 'storages', 'ckeditor', 'ckeditor_uploader', 'main', 'contact', 'accounts', 'events', 'news', 'project_settings', 'django_countries', 'publications', 'event_tracker', 'event_signup'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/Tommy/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/Tommy/anaconda3/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__ 97. response = self.process_response(request, response) File "/Users/Tommy/anaconda3/lib/python3.6/site-packages/django/middleware/clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /sign-s3/ Exception Value: 'str' object has no attribute 'get' Views.py File: def committee_new_podcast(request, id): template = "main/add_podcast.html" committee = get_object_or_404(Committee, comm_id=id) if request.user.is_authenticated: if Member.objects.filter(user=request.user).exists(): member = Member.objects.get(user=request.user) if CommitteeMember.objects.filter(Q(is_chair=True) | Q(is_deputy=True)).filter(abila=member, comm=committee.comm_id) or request.user.is_staff: if request.method == 'POST': form = CommitteePodcastForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.comm_id = committee instance.member = member instance.sound = request.form['avatar-url'] instance.save() messages.success(request, 'Committee Podcast Was Created', … -
Insert python string into Django template context with markup
If I render a static image in the .html template it works. But if I provide the static markup string as dictionary value to the template (the context), it will not work. It seems to be something to do with string formatting and not allowing me to use {% %} the way I need to. I have tried: 1. .format() 2. escaping the percent characters 3. raw strings 4. concatenation 5. autoescape 6. | safe and a number of other things Basically, I am constructing a multi-line string in view.py with '''{% %}''', and then rendering a template with this string as the context. Python 2.