Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a User object when creating another object with OneToOne relationship in Wagtail
Not sure if the title is descriptive enough, sorry for that. I have added a model called 'Client' to Wagtail's ModelAdmin. In client/models.py: class Client(models.Model): # Every client is a user user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("Pessoa") ) phone_number = PhoneNumberField( _("Número telemóvel"), null=False, blank=False, unique=True ) company = models.CharField(_("Empresa"), null=True, blank=True, max_length=20) NIF = models.CharField(max_length=9, validators=[validate_nif]) def __str__(self) -> str: return self.user.get_full_name() In client/admin.py: class ClientAdmin(ModelAdmin): """ Client Admin """ model = Client menu_label = "Clientes" menu_icon = "fa-users" menu_order = 290 add_to_settings_menu = False exclude_from_explorer = False list_display = ( "NIF", ) search_fields = ( "NIF", ) modeladmin_register(ClientAdmin) When I go to Clientes admin page, and try to create a new one, I have the following: Is it possible to have the corresponding fields to create a 'Person', instead of selecting a new one? Thanks in advance -
Can't configure django TinyMCE in settings.py while it's possible in html script
I used TinyMCE for django for a prior project and as far as I remember, it was possible to configure in django settings.py file. Now, I'm working on another project but couldn't find any solution to make it done except adding the TinyMCE configuration js script to the template I want to use it on. It's not a big deal to configure from HTML but looks like it's having some performance issues while getting static requests. And, I haven't had any loading problem while I was configuring in settings.py. Here you can check my project files here. Hope to find a solution. models.py from tinymce.models import HTMLField class Article(models.Model): ... message = HTMLField() ... forms.py from django import forms from tinymce.widgets import TinyMCE from . import models class ArticleForm(forms.ModelForm): class Meta(): abstract = True model = models.Article fields = ('title', 'message', 'tags') widgets = { 'title': forms.Textarea(attrs={'placeholder': 'Başlık'}), 'message': TinyMCE(attrs={'class': 'tinymce', 'id': 'myeditablediv', 'contenteditable': 'true', 'style': 'position: relative;'}), } def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) form.html {% extends "articles/article_base.html" %} {% load bootstrap4 %} {% load static %} {% load widget_tweaks %} {% block article_content %} <div class="container"> <div class="articleForm"> <form method="POST" action="{% url 'articles:create' %}" … -
Pass Django template variable in url template tag
I'm still a bit new to Django and have been stuck on trying to figure out a way to add a template variable to a Django url template tag. I can better explain with an example... I have a help center/knowledge base that currently has articles along with tags associated with that article. The goal is to allow users to click on those associated tags to perform a search on the help center using the tag that was clicked on and return a new set of articles in the search. This is my url pattern: urlpatterns = [ ... path('search/', views.search, name='search'), ... ] My html: <div id="tags uk-margin-bottom"> {% for tag in article.tags.all %} <a href="{% url 'search' %}" class="badge badge-pill badge-primary">#{{ tag }}</a> {% endfor %} </div> My search view function: def search(request): if request.user.is_authenticated: # get all articles queryset_list = Article.objects.all() if 'search' in request.GET: search = request.GET['search'] if search: tags = [] queryset_list_tags = queryset_list.filter(tags__name__icontains=search).distinct() try: queryset_list_title = queryset_list.filter(title__icontains=search).distinct() except: print("Testing - Couldn't grab titles.") search_results = queryset_list_tags | queryset_list_title # get all tags from query_list_title search for title in queryset_list_title: article = Article.objects.get(title=title) queryset_tags = article.tags.all().values_list('name') for tag in queryset_tags: # add all tags in … -
Get serialized response of all models related to base model instance using Django REST framework
I have 3 models class Project(models.Model): project_name=models.CharField(_("Project Name"), max_length=50) ............................................................... class Calculations(models.Model): project = models.ForeignKey("address.Project", verbose_name=_("Project"), on_delete=models.CASCADE) ................................................................................................... class Finances(models.Model): project = models.ForeignKey("address.Project", verbose_name=_("Project"), on_delete=models.CASCADE) ................................................................................................... each entry in model Project is connected to 2 entries in Calculation model. Also, each entry of Calculation is connected to 4 entries of Finance model Is there any way to get serialized response by using only the primary_key of the base Project model -
{% include %} doesn't pass " for loop " data in other html pages - Django
i want pass data from an html page that i use for loop inside this page and show all data in other html pages so i tried this but it doesn't pass for loop data from my model why side_bar_good_posts.html : {% for post in best_posts %} <div class="card rounded mx-auto d-block" style="width: 18rem;margin-bottom:50px;border-color:#7952b3"> <div class="card-body" id="mobile_design_card"> <a href="{{post.url}}"><p class="card-text" id="mobile_design_card_name">{{ post.name }}</p></a> </div> <a href="{{post.url}}"><img src="{{ post.get_image }}" class="card-img-top" alt="..." height="290px" width="300px"></a> </div> &nbsp; &nbsp; {% endfor %} views.py : from .models import BestArticals def Best_Articals(request): best_posts = BestArticals.objects.all() context = {'best_posts' : best_posts} return render(request,'android/side_bar_good_posts.html',context=context) in other html pages : {% include "android/side_bar_good_posts.html" with best_posts=best_posts %} it show just html tags , but data from for loop doesn't appear why -
Django views show same content. Where are django views controlled?
I have a django application with two views that display the same content, but they shouldn't. I created the second by duplicating the code from the first and cannot figure out how to unhook these from each other. I am pretty sure the problem is in the views.py file of my app. I have two views, 'journals-by-discipline' and 'journals-by-discipline-elsevier' Here is the urls.py file: from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from . import views app_name = 'app' urlpatterns = [ # Journals by Discipline path('journals-by-discipline/', views.journals_by_discipline, name='journalsByDiscipline'), path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data), path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline/disciplines-list/', views.disciplines_list), # Journals By Discipline (Elsevier) path('journals-by-discipline-elsevier/', views.journals_by_discipline_elsevier, name='journalsByDisciplineElsevier'), path('journals-by-discipline-elsevier/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data_elsevier), path('journals-by-discipline-elsevier/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline-elsevier/disciplines-list/', views.disciplines_list), ] Here is the views.py file from django.shortcuts import get_object_or_404, render from django.contrib.auth.decorators import login_required from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response import datetime as datetime from dateutil.relativedelta import relativedelta from urllib.parse import unquote import json from .onefigr_analysis import Data # Instantiate Data object to fetch data across all views data = Data() # Journals by Discipline Page def journals_by_discipline(request): template_name = 'app/journals-by-discipline.html' return render(request, template_name) @api_view(['GET']) def journals_by_discipline_chart_data(request, discipline): if request.method == 'GET': query_discipline = unquote(discipline) return Response(data.journals_by_discipline_chart_data(discipline)) … -
Django: Get User profile from User serializer
I have a basic UserProfile model that has a OneToOne relationship with a User model. My User serializer works well, though how do I go about retrieving the related UserProfile model from the same serializer and viewset? Here is my UserProfile Model: class UserProfile(models.Model): bio = models.CharField(max_length=1000) cellphone = PhoneNumberField(null=True) useraccount = models.OneToOneField(User, on_delete=models.CASCADE) My current viewset: class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = CurrentUserSerializer permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user queryset = User.objects.filter(username = user) return queryset My User serializer: class CurrentUserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'groups') def to_representation(self, instance): return { 'username': instance.username, 'email': instance.email, 'first_name': instance.first_name, 'last_name': instance.last_name, 'groups': GroupSerializer(instance.groups.all(), many=True).data, } I attempted the following with my Serializers, but got an attribute error stating that my User model does not have the field profile: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('dashboards', 'fullname') class CurrentUserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) profile = TeamMemberDashboardSerializer() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'groups', 'profile') def to_representation(self, instance): return { 'username': instance.username, 'email': instance.email, 'first_name': instance.first_name, 'last_name': instance.last_name, 'groups': GroupSerializer(instance.groups.all(), many=True).data, 'profile: instance.profile } Thanks for your time! -
Path conflict between server and client
I have a client React app (Electron) that is running on http://localhost:3000/ My Django server has this path in the whitelist: CORS_ORIGIN_WHITELIST = [ "http://localhost:3000" ] The problem is that Python doesn't let me add the / at the end of the path. If I'm calling the server like it is right now it won't work. So can I force Django to accept my url with the / at the end? or maybe change it from my React client. -
Devnagiri/Hindi (indic fonts) Font Are Not Rendering Correctly In Pdf
Output Of Pdf original text is: आसिफ शिख पिख text in output pdf : आसफि शखि पखि text is ok in django console but in pdf it's wrong searched everywhere got some answer suggesting harfbuzz but they are not clear ''' from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter, A4 from reportlab.lib import pdfencrypt from django.http import FileResponse from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont def Genrate_pdf(request): data = Voter_detail.objects.last() BASE_DIR = Path(__file__).resolve().parent.parent buffer = io.BytesIO() p = canvas.Canvas(buffer) pdfmetrics.registerFont(TTFont('Noto', 'static/fonts/NotoSans-Regular.ttf')) pdfmetrics.registerFont(TTFont('barcode', 'static/fonts/LibreBarcode128-Regular.ttf')) pdfmetrics.registerFont(TTFont('marathi_test1', 'static/fonts/NotoSans-Bold.ttf')) pdfmetrics.registerFont(TTFont('marathi_test2', 'static/fonts/MROTBimaB_Ship.ttf')) pdfmetrics.registerFont(TTFont('sakal', 'static/fonts/Eczar-Medium.ttf')) p.setPageSize((153, 243)) # EPIC NAME IN REGIONAL p.setFont('sakal', 9) p.drawString(8,78,"मतदाराचे नाव : %s " % data.rname) print(data.rname) ''' -
__init__() takes 1 positional argument but 8 were given
class Transaction(models.Model): slug = models.SlugField(max_length=200, db_index=True) order_type = models.CharField(verbose_name="Order Method", max_length=200, choices=ORDER_METHODS) paid = models.BooleanField(verbose_name="Paid", default=False) closed = models.BooleanField(verbose_name="Closed", default=False) created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True) id_num = models.IntegerField(verbose_name="Transaction ID", db_index=True) def __init__(self): super().__init__() self.set_transaction_id() def set_transaction_id(self): self.id_num = int(str(self.created.year) + str(self.created.month) + str(self.created.day).zfill(2) +\ str(self.created.hour) + str(self.created.minute).zfill(2) + str(self.created.second).zfill(2)) When I create this model in a view like this: transaction = Transaction(order_type='Choice_1', paid=False, closed=False) transaction.save() I got this error __init__() takes 1 positional argument but 8 were given. The method set_transaction_id() uses the date and time to set the id_num. Is there something wrong with the way I declare __init__ and using super() or calling set_transaction_id()? -
how to give the adress of subdomain on gunicorn_config file
I am trying to deploy a django app. I a m using gunicorn . I used gunicorn_config.py : command='/root/m/bin/gunicorn' pythonpath='/root/m' bind='xxxxxx.net' workers=3 for the main domain which works well but for subdomain named admin. I tried bind = 'admin.xxxxx.net' which doesn't works bind = 'xxxx.net/admin' which also doesn't works. Can anyone help how to write bind for subdomain -
How to display a Foreign Key in django template?
My template is set up like this: {% for deck in deck %} <a href='{% url 'deck_detail' deck.title %}'> <li class='deckCards'> <div class='deckText'> <div class='deckTitle'>{{deck.title}}</div> <div class='deckCreator'>{{deck.creator}}</div> <div class='deckSubject'>{{deck.subject}}</div> <div class='deckQuestion'>{{deck.questions.count}} Questions</div> <div class='deckAccuracy'>{{The part I need help with}}%<div> </div><!-- end of deckText --> My model is like so: class DeckAccuracy(models.Model): deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name='accuracy') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='attempted_deck') deck_accuracy = models.IntegerField(default=0) num_of_attempts = models.IntegerField(default=0) total_score = models.IntegerField(default=0) def __str__(self): return str(self.deck) My view: def DashboardView(request): user = request.user deck = Deck.objects.all() return render(request, "cards/dashboard.html", {'deck': deck, 'user': user}) I can't figure out how to display the deck accuracy directly within the for loop of my template. Thank you so much for your help! -
Set a timer to know how long the unknown face was on the screen in face recognition using opencv in python?
I'm learning face recognition using opencv in python and wondering If I can set a timer to know if the unknown face gets detected for more than 5 seconds than I will call some function(). So I used start time and end time inorder to get the difference of 5 but it's not working properly. Any clue to make this code working ? def gen(camera1): startTime = time.time() while True: label, frame = camera1.get_frame() if label=="unknown": endTime = time.time() if (endTime - startTime > 5): print("Inside If condition Longer than 5 seconds") function() else: yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' yield frame yield b'\r\n\r\n' yield label -
how to update data only if the sql query we have entered exists through python?
I want to update one table in mysql which has 3 rows what i want is to update any row with update command but this has to be happened only when there exists a particular row i.e.if i update it like updatedata = "update table12 set name='Dhiraj', city='Delhi' where id=25" then it should give me an error Here is my code: import pymysql db = pymysql.connect('localhost','root','','firstdb') print("database connected successfully") cur = db.cursor() updatedata = "update table12 set name='Dhiraj', city='delhi' where id=25" if updatedata: try: cur.execute(updatedata) db.commit() print("Data updated successfully...") except: print("Something went wrong!") else: print("There is no any data you entered!") -
"Forbidden (CSRF cookie not set.)" in Django dev env using https without valid certificate
Pretty sure this is the reason I'm getting the Forbidden (CSRF cookie not set.) error in my development environment: Working on Azure AD authentication URI Redirects require either localhost or https:// Since I'm developing in a local k8s cluster with skaffold, it has an minikube ip like 192.168.64.7 Thus, I'm having to do https://192.168.64.7/ for my URI redirects and not using a valid SSL certificate since I'm just in dev I'm at the point where I'm sending the accessToken from the React FE to the our API for it to be validated again there Pretty sure Django is seeing https:// and that it is not valid causing this error So my questions are: Am I correct about why this error is coming up? Is there a setting I can enable in development to ignore this? Or is my only option to get a valid SSL certificate for my dev environment? I have verified that doing the following does not work: ALLOWED_HOSTS = [ '*' ] Also, GET requests are working but POST are not. #views.py from django.shortcuts import render from django.views import View from django.http import HttpResponse # Create your views here. class TestView(View): def post(self, request): return HttpResponse('Hello World') … -
Django readonly fields are not getting autopopulated in TabularInline admin while saving
In Django models.py, I have model A and B class A (models.Model): Name = models.CharField(max_length=100) Location = models.CharField(max_length=100) def__(str)__(self) : return "%s" %(self.Name) class B(models.Model): Name = models.ForeignKey(A, on_delete=models.cascade) Added_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Added_by") Added_date = models.DateTimeField(default=datatime.now) Modified_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Modified_by") Modified_date = models.DateTimeField(editable=False,blank=True) class B_admin(admin.TabularInline): model = B extra = 0 readonly_fields=["Added_by","Added_date","Modified_by","Modified_date"] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) def save_model(self, request,obj form, change): if getattr(obj, '', None) is None: obj.Added_by = request.user obj.Modified_by = request.user obj.Added_date = datetime.now() obj.Modified_date = datetime.now() else: obj.Modified_by = request.user obj.Modified_date = datetime.now() obj.save() class A_admin (admin.ModelAdmin): Inline = [B_admin] list_display = ['Name','location'] list_filter = ['Name','location'] search_fields = ['Name','location'] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) The admin page A is working fine with Model B as TabularInline. Also, the readonly_fields looks good inside TabularInline. The problem is when the admin page gets saved, the readonly_fields (Added_by, Modified_by, Modified_date) are showing blank and are not getting autopopulated. Added_date is working correctly since i have mentioned default=datetime.now while declaring inside model B. Other 3 fields are not getting autopopulated. Any idea? Thanks in advance -
Connect a domain to a Django app deployed with google cloud
I made a Django app and deployed it with google app engine. It is working and I can indeed access it with the URL google is providing me. I also have a domain name I bought on Ionos and I'd like to connect my domain to my Django app. I'm pretty sure I should configure the DNS. But I can't find the parameters in google cloud platform that would allow me to do so. Anyone knows where to find the DNS parameters on google cloud platform ? Thanks -
How do i send alert email in django?
I want to create a property rental app where users can search property by location. If the property is not found in the particaular time, the user is notified via email when the property in that particular location is added. so how can i solve this problem?` -
Check if the /profile page is redirecting to /login page and add a warning message
Just an FYI that I'm currently at day 4 learning Django (Thanks to Corey Schafer's amazing playlist) I just completed creating the Login-logout system and was trying to add a warning message when a user tries to access the /profile without being logged in which successfully redirects to the /login page . And since the @login_required decorator doesn't have that built-in, I was trying to think of a logic which would check, if the /profile page redirects to the /login page > add a warning message. (I tried creating my own decorator but the messages.warning fxn would require a user request which would throw an error) Kinda like this noob-ey code I tried : @login_required def profile(request): if LOGIN_URL == 'login': messages.warning(request, 'You need to login in order to access this page.') return render(request, 'users/profile.html') -
Django Rest pass variable not in model for logic in overridden save method
In DRF how can I pass for example a boolean which isn't in my model from ModelViewSet so it can be used in a overridden save method for some logic? I know with a model instance you can just assign it, but I'm unsure if this is possible from ModelViewSet or goes against the general flow of DRF. -
How to shift time during django-tests
Hello I wonder is there a way to shift time during tests, globally. during tests when I call django.utils.timezone.now() to return shifted time, I need it because the software I am testing is pretty complex and if I could shift times just to be sure if all tasks and api calls are doing their jobs. For testing I am using django.tests.TestCase Thank you any help will be apprecated! -
Django views confusion, two views show same content
I have a python django application. I had a view, which I duplicated and changed slightly to create a second view. But they seem to be hooked together and duplicate the page content, when they should be different. Here is my urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from . import views app_name = 'app' urlpatterns = [ # Journals by Discipline path('journals-by-discipline/', views.journals_by_discipline, name='journalsByDiscipline'), path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data), path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline/disciplines-list/', views.disciplines_list), # Journals By Discipline (Elsevier) path('journals-by-discipline-elsevier/', views.journals_by_discipline_elsevier, name='journalsByDisciplineElsevier'), path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data_elsevier), path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline/disciplines-list/', views.disciplines_list), ] I have two views, journals_by_discipline and journals_by_discipline_elsevier Here is my views.py from django.shortcuts import get_object_or_404, render from django.contrib.auth.decorators import login_required from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response import datetime as datetime from dateutil.relativedelta import relativedelta from urllib.parse import unquote import json from .onefigr_analysis import Data # Instantiate Data object to fetch data across all views data = Data() # Journals by Discipline Page def journals_by_discipline(request): template_name = 'app/journals-by-discipline.html' return render(request, template_name) @api_view(['GET']) def disciplines_list(request): if request.method == 'GET': return Response(data.get_disciplines_list()) @api_view(['GET']) def journals_by_discipline_chart_data(request, discipline): if request.method == 'GET': query_discipline = unquote(discipline) return Response(data.journals_by_discipline_chart_data(discipline)) @api_view(['GET']) def get_journals_and_disciplines_map(request): if request.method == 'GET': … -
Django - saving model via a form is not working
I'm having a little problem with the .save() method in Django. For 1 form it works, for the other it doesn't. And I can't find the problem. views.py @login_required def stock_add(request, portfolio_id): if request.method == 'POST': print('request.method is ok') form = StockForm(request.POST) print('form is ok') if form.is_valid(): print('form is valid') stock = form.save(commit=False) stock.created_by = request.user stock.portfolio_id = portfolio_id stock.save() return redirect('portfolio-overview') else: print("nope") else: print('else form statement') form = StockForm() context = { 'form':form } return render(request, 'portfolios/stock-add.html', context) forms.py class StockForm(ModelForm): class Meta: model = Stock fields = ['quote', 'amount'] html {% extends 'core/base.html' %} {% block content %} <div class="container"> <h1 class="title">Add Stock</h1> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <button type="submit" class="button is-primary">Submit</button> </form> </div> {% endblock %} models from django.db import models from django.contrib.auth.models import User # Create your models here. class Portfolio(models.Model): title = models.CharField(max_length=56) description = models.TextField(blank=True, null=True, max_length=112) created_by = models.ForeignKey(User, related_name='portfolios', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Portfolio' def __str__(self): return self.title class Stock(models.Model): Portfolio = models.ForeignKey(Portfolio, related_name='stocks', on_delete=models.CASCADE) quote = models.CharField(max_length=10) amount = models.IntegerField() created_by = models.ForeignKey(User, related_name='stocks', on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.quote If you look at the views.py file, when I submit … -
Django HttpResponse "expected a bytes-like object, str found"
I'm getting the above TypeError from a healthcheck route on Django 3.1.2 on python 3.6. The full error logged is: ERROR 2020-11-02 16:09:50,154 /home/centos/venv/lib/python3.6/site-packages/django/utils/log.py log_response Internal Server Error: /healthcheck/ Traceback (most recent call last): File "/home/centos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/centos/venv/lib/python3.6/site-packages/sentry_sdk/integrations/django/middleware.py", line 134, in __call__ return f(*args, **kwargs) File "/home/centos/venv/lib/python3.6/site-packages/sentry_sdk/integrations/django/middleware.py", line 90, in sentry_wrapped_method return old_method(*args, **kwargs) File "/home/centos/venv/lib/python3.6/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/home/centos/venv/lib/python3.6/site-packages/django/middleware/common.py", line 113, in process_response response['Content-Length'] = str(len(response.content)) File "/home/centos/venv/lib/python3.6/site-packages/django/http/response.py", line 315, in content return b''.join(self._container) TypeError: sequence item 0: expected a bytes-like object, str found That error is raised every time the route is requested. The full view definition is: def healthcheck_view(request): response = HttpResponse("OK", content_type="text/plain") return response What on earth have I done?? -
How to get data from a form written directly in the template not in forms.py?
I have a page with images and I want to be able to delete some of them so I wrote this form: <form method="post"> {% for img in images %} <img src={{img.image.url}}> <input type="checkbox" id={{img.id}} value={{img.id}}> {% endfor %} <button type="submit">DELETE</button> </form> and this the views.py: def lemqes(request, iid): images = IMAGE.objects.filter(id=iid) if request.method == 'POST': #how can I continue to delete multiple images return render(request, 'del.html', {'images' : images})