Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        UserProfileInfo matching query does not exist DjangoI need to have extra information about a person, more than the default User model provides. That's why I've created the UserProfileInfo model that's supposed to hold all this extra info, such as house_number, phone_number, full_name, and community. Now, an instance of UserProfileInfo is created whenever a user registers. But when I run this route called all_books in views.py, I get an error: UserProfileInfo matching query does not exist. Here's my all_books view: def all_books(request): if request.user.is_authenticated: context = { "books": Book.objects.all(), "request": request, "user_profile": UserProfileInfo.objects.get(user=request.user), } else: context = { "books": Book.objects.all(), "request": request, "user_profile": False, } if request.GET.get("context") == "mail_sent": context["mail_sent"] = True return render(request, 'main/all_books.html', context) This error happens only when I've signed in, and not when I'm not signed in. When I head over to the admin, I see that the profile has been created. But I don't understand why this isn't able to get that.
- 
        docker + REST API in djangoi have API project with python that work OK. after building a docker image it return this error: module 'keras.backend' has no attribute 'get_session' and then it doesn't work anymore. does anybody have an idea what should i do? I am on Ubuntu with python=3.8.10 requirments: tensorflow==2.4.0 tensorflow-gpu==2.4.0 keras==2.4.3 numpy==1.19.3 pillow==8.1.1 scipy==1.4.1 h5py==2.10.0 matplotlib==3.3.2 keras-resnet==0.2.0 Django==3.2.10 djangorestframework==3.13.0 opencv-python imageai
- 
        Django to Heroku, How to migrate sqlite3 data to postgresI tried to host a website on heroku but I keep getting this error File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "home_product" does not exist LINE 1: ...home_product"."price", "home_product"."slug" FROM "home_prod... whenever I tried to use heroku run python manage.py migrate -a appname I mainly used this video as a reference to hosting: https://www.youtube.com/watch?v=UkokhawLKDU&t=964s and also these articles which didn't really help tbh: Heroku Django Database Error https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment Here's my settings.py Django settings for Corbett_Jewelry project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from decouple import config import psycopg2 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', …
- 
        How to prevent form update conflict among multiple users in Django?I have a form like a student form. It can be updated by a function in view. There are multiple users that have the update permission for this form. The problem is when 2 users open the form of a student(id=1) at the same time. They can change fields and save the form. All changes of a user will be ignored and lost. How to prevent this conflict. I want if a user opens a specific student form, other users can not open it until the first user close the form or it's time for the update be expired.
- 
        How to convert javascript object to python readableI'm trying to parse below object from javascript post data into python using ast.literal_eval(obj) but ending up into below error Error: malformed node or string: <_ast.Name object at 0x7fb484eb8070> Object Value: '[{"dose":"1","duration":"2","name":"Item1","code":"pharma2","usage":{"morning":true,"afternoon":false,"evening":false,"night":false,"sos":false}},{"dose":"1","duration":"4","name":"Item2","code":"pharma1","usage":{"morning":false,"afternoon":false,"evening":false,"night":true,"sos":false}}]'
- 
        How to choose one item in many to many relationship as special?What is the best practice to choose one item from a m2m relationship? Lets say I've got an album of photos: class Photo(models.Model): img = models.FileField() class Album(models.Model): photos = models.ManyToManyField("Photo") But now I also want to pick one photo as a cover. I could use a Foreign Key in Album to one Photo, but then I'd always need to check whether this photo is actually in the photos of that album. Is there a better way? Sorry for the basic question I just somehow can't find the right words to google it. Thanks, Michael
- 
        How to pass Django InMemoryUploadFile to serializer in case with images?I'm creating an API using Django Rest Framework to save images from file directly or from url. I've got no problem with first case but with second. So, my models looks like this: class Image(models.Model): picture = models.ImageField(upload_to="site_media", blank=True) url = models.URLField(null=True, blank=True, max_length=255) parent_picture = models.IntegerField(null=True, blank=True) @property def name(self): return os.path.split(self.picture.name)[-1] @property def width(self): return self.picture.width @property def height(self): return self.picture.height Next, my serializer class: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'id', 'name', 'url', 'picture', 'width', 'height', 'parent_picture' ] The main idea is if you pass the URL while post request, API needs to download image from this URL and store it in database. To do this I overwrote create method in Django Rest Framework ModelViewSet class: from io import BytesIO import urllib import os from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image as PILImage from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from .models import Image from .serializers import ImageSerializer class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer queryset = Image.objects.all() def create(self, request, *args, **kwargs): if request.data["url"]: url = request.data["url"] image_extensions = { ".jpg": "JPEG", ".jpeg": "JPEG", ".png": "PNG", ".gif": "GIF" } image_path = urllib.parse.urlparse(url).path image_filename = image_path.split("/")[-1] extension = os.path.splitext(image_filename)[-1] …
- 
        Django Admin Templates - How to add a "back to list" button?Working with Django admin - still pretty new. I need to add a button to the footer (that appears when editing or adding an object) that sends the user back to the list page for that object. I am able to add the button itself to the footer by adding templates/admin/submit_line.html: {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" {{ onclick_attrib }}/>{% endif %} {% if show_delete_link %}<p class="deletelink-box"><a href="{% url opts|admin_urlname:'delete' original.pk|admin_urlquote %}" class="deletelink">{% trans "Delete" %}</a></p>{% endif %} {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" {{ onclick_attrib }}/>{%endif%} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" {{ onclick_attrib }}/>{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" {{ onclick_attrib }}/>{% endif %} <input type="submit" value="{% trans 'Go Back' %}" {{???}}/> </div> But I don't know where to go from there. Presumably it is possible because Django breadcrumbs exist (and the relevant page is always the most recent link in the breadcrumbs), but I don't know how I'm supposed to get the link to the relevant page.
- 
        when ever i am adding def str function to name it the model gives errordef __str__(self): return self.category_name when ever i am adding this str function in my model class Category(models.Model): category_name = models.CharField(max_length=50, unique=True,blank=True,null=True) slug = models.SlugField(max_length=100, unique=True,blank=True,null=True) description = models.TextField(max_length=255, blank=True,null=True) cat_image = models.ImageField(upload_to='photos/categories', blank=True,null=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('core:category', args=[self.slug]) then it gives me error TypeError at /admin/core/product/ str returned non-string (type NoneType)
- 
        Passing Django view data to JavaScript ChartI have some data that is returned via Django view, I'm trying to render the data in an Apex Pie Chart. So I need to pass the data into JavaScript as this is where the data series is. var pieColors = getChartColorsArray("#pie_chart"), options = { chart: { height: 320, type: "pie" }, series: [44, 55, 41, 17, 15], labels: ["Series 1", "Series 2", "Series 3", "Series 4", "Series 5"], colors: pieColors, legend: { show: !0, position: "bottom", horizontalAlign: "center", verticalAlign: "middle", floating: !1, fontSize: "14px", offsetX: 0 }, responsive: [{ breakpoint: 600, options: { chart: { height: 240 }, legend: { show: !1 } } }] }; (chart = new ApexCharts(document.querySelector("#pie_chart"), options)).render(); How do I pass the data in as it needs to be dynamic in the sense that the data in the pie chart could change based on other actions within the app? Should just embed the JS into my HTML template and then set the series values to series: [{{ value.1 }}, {{ value.2 }}, ...], Thanks
- 
        LeaderboardAPI : I want to show only Today's record by comparing it with the created dateMy Modely.py I am storing playername, TotalPoints, created_date by POST API from django.db import models from django.utils.translation import ugettext as _ # Create your models here. class leaderboard(models.Model): name = models.CharField(_("playername"), max_length=255) TotalPoints = models.IntegerField(_("TotalPoints")) created_date = models.DateTimeField(auto_now_add=True) My Serializers.py file: This is my Searializer: from rest_framework import serializers from .models import leaderboard class leaderboardSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', ] class lwithcdateSerializers(serializers.ModelSerializer): class Meta: model = leaderboard fields = [ 'name', 'TotalPoints', 'created_date', ] My Views class Leaderboard(APIView): def get(self, request, formate=None, **kwargs): today = datetime.date.today() serializer = lwithcdateSerializers(leaderb.objects.all().order_by('-TotalPoints') [:40], many=True) return Response(serializer.data) Please check the above code and let me know how can I display only Today's record
- 
        Django - Changed DB from Sqlite3 to Postgres - do I need to do something else to reflect changes?In my server, I changed the DB to Postgres from SQlite3. Because this is a new website and doesn't have much data yet (except test stuff) I didn't have to do DB migration or whatever else it is called. I just changed settings.DATABASES to include Postgres. Here's my settings.DATABASES in settings.py: from sys import platform if platform == 'darwin': # OSX DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR + '/db.sqlite3', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pfcbookclub', 'USER': 'admin', 'PASSWORD': 'g&zy8Je!u', 'HOST': '127.0.0.1', 'PORT': '5432', } } I develop on an M1, and psycopg2 doesn't seem to work for me, how many ever times I try to install libq or openssl with Homebrew on Rosetta, which is why I decided to use Sqlite on my Mac and Postgres on my server. Now, when I pulled these changes with git onto my server, I refreshed the page on my domain, but all the test data I had filled in my Sqlite3 database still showed. I thought it would be empty because I haven't filled up the Postgres DB with anything and I didn't do any sort of migration that would convert db.sqlite3 into Postgres …
- 
        This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405I am getting the following error message when I fill the form: This page isn’t working right now. If the problem continues, contact the site owner. HTTP ERROR 405. Kindly advise. views: from django.shortcuts import render, get_object_or_404 from .models import Post from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView from .forms import CommentForm from django.views import View class UltimatePostView(View): def get(self, request, slug): post = Post.objects.get(slug=slug ) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : CommentForm() } return render(request, "gold-blog/post-detail.html", context ) def post(self, request, slug): comment_form = CommentForm(request.POST) post = Post.objects.get(slug=slug ) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.save() return HttpResponseRedirect(reverse("post-detail-page", args=[slug])) context = { "post": post, "post_tags" : post.tag.all(), "comment_form" : comment_form } return render(request, "gold-blog/post-detail.html", context)
- 
        Django admin is very slow when loading from the OneToOne user modelI think I am doing admin model wrong because it is taking like 30 seconds to load and I think its because my sql queries are too inefficient and there may be creating more look ups than needed. Is there a way that I can speed this up? class UserInformationAdmin(admin.ModelAdmin): list_display = ( 'user_username', 'user_first_name', 'user_last_name', 'major' ) @admin.display(description='user.username') def user_username(self, obj): try: return obj.user.username except Exception: return None @admin.display(description='user.first_name') def user_first_name(self, obj): try: return obj.user.first_name except Exception: return None @admin.display(description='user.last_name') def user_last_name(self, obj): return obj.user.last_name```
- 
        how to trigger email to admin panel in django through contact form using form.is_valid()?Whenever a user sends email through the contact form, it should be displayed to the admin in the admin panel. Now, when I click submit, it goes back to "contact.html" as stated in function, what are the possible reasons it is not being valid when it is saved? I'm pretty sure I'm filling the form correctly from the web. here is the model: class Contact(models.Model): name = models.CharField(max_length=100) email = models.EmailField(default="default") subject = models.CharField(max_length=100) message = models.CharField(max_length=100) def __str__(self): return self.name the function in views.py: def display3(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return render(request, 'success.html') form = ContactForm() context = {"form": form} return render(request, 'contact.html', context) lastly, this is in forms.py: class ContactForm(ModelForm): class Meta: model = Contact fields = '__all__'
- 
        Unable to fetch row elements values using JavascriptI'm little new to Javascript. This is using django as backend. I'm trying to capture data from table columns like 'dose', 'duration' and 'usage' which uses text box and checkbox. Whenever I hit the button with id='qty', then I'm able to see correct value for first click but when I click the button for another element it still submits same previous data instead of data on the same row. Below is the sample output that I captured from console log #Item 1 Log [Log] Object (e28c8d12-1a95-44e5-9813-dfc2f4bf3bb1, line 502) code: "" dose: "1" name: "PARACIP" price: undefined quantity: "2" total: NaN usage: {morning: false, afternoon: false, evening: false, night: false, sos: false} #Item 2 Log [Log] Object (e28c8d12-1a95-44e5-9813-dfc2f4bf3bb1, line 502) code: "" dose: "1" name: "Paracetamol" price: undefined quantity: "2" total: NaN usage: {morning: false, afternoon: false, evening: false, night: false, sos: false} Object Prototype HTML Code <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Item</th> <th>Dose</th> <th>Duration</th> <th>Usage</th> <th>Action</th> </tr> </thead> <tbody> {% for item in inventory %} <tr> <td>{{ item.brand }} {{ item.item_name }}</td> <td> <input type="text" class="form-control" name="dose", id="dose"> </td> <td> <input type="text" class="form-control" name="duration" id="duration"> </td> <td> <div class="form-check form-check-inline"> <input class="form-check-input" type="checkbox" id="morning" name="morning"> <label class="form-check-label" …
- 
        Error in DRF only! UNIQUE constraint failed: questions_question.idHere is the model, serializer and view. When I try to create a new question with the API endpoint It's showing the UNIQUE constraint failed: questions_question.id but It's going to be saved into the admin panel. Please share an idea to solve the error! models.py class Question(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='all_questions') title = models.CharField(max_length=225) desc = models.TextField() slug = models.SlugField(max_length=225, # unique=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.title}" serializers.py class QuestionsSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) class Meta: model = Question fields = "__all__" view.py class QuestionCreateAPI(generics.CreateAPIView): model = qs_models.Question queryset = qs_models.Question.objects.all() serializer_class = own_serializers.QuestionsSerializer permission_classes = (permissions.IsAuthenticated, ) def perform_create(self, serializer): return super().perform_create(serializer.save(author=self.request.user)) Terminal Error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: questions_question.id But it still saving on the admin panel
- 
        Django Button HandlingI only want to display 2 buttons which should submit on click. If the buttons are clicked it should only display form 2 on the User button or else another form on Doctor button(add field to form 2). Currently it does work if I used radios if I used another submit button but I'd like for button click handling in the wizard which I'm unsure of. flow: form1-> show_message_form_condition {'is_doctor': True} for both buttons clicks and for radio it's is_{'is_doctor': True} and {'is_doctor': False}-> display form 2 if value is false. forms.py class PickUserType(forms.Form): is_doctor = forms.BooleanField(required=False) class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) Both of them {% block content %} <form method = "POST" action='.' enctype="multipart/form-data"> {% csrf_token %} <!-- A formwizard needs this form --> {{ wizard.management_form }} <!-- {{form_as_p}} --> <button type="submit" value="Doctor" name="0-is_doctor">Doc</button> <button type="submit" value="User" name="0-is_doctor">User</button> <!-- {% for field in form.visible_fields %} {{ field.errors }} {% for radio in field %} <div class="form-check form-check-inline"> {{ radio }} </div> {% endfor %} {% endfor %} <input type="submit" …
- 
        wagtail No module named wagtail.contribI did start wagtail fresh installation after I did and I want to use python instead python3 pip3 install wagtail wagtail start wagtail02 cd wagtail02 pip3 install -r requirements.txt when I try to do python manage.py migrate I get an error message Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/lotfi/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/lotfi/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/lotfi/.local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/lotfi/.local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/lotfi/.local/lib/python2.7/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named wagtail.contrib I don't find a solution on internet but if I do python3 manage.py migrate it work, is there a solution to make it working using python instead of python3
- 
        Add new page function does not work as it should. How can I add new page? DjangoI am trying to create a Addpage function with the following features; Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry. When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message. Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) def add_page(request): if request.method == "POST": form = AddPageForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] # saveInput = SaveInput(title=data['title'], content=data['content']) # saveInput.save() entries = util.list_entries() for entry in entries: if title.upper() == entry.upper(): return render(request, "encyclopedia/errorpage.html") else: return redirect('encyclopedia:entrypage', title=title) util.save_entry(title, content) else: return render(request, "encyclopedia/addpage.html", { "form": AddPageForm() }) URL.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("add_page", views.add_page, name="addpage"), ADDPAGE.HTML <h1>Add Page</h1> <form action="{% url 'encyclopedia:addpage' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-secondary"> </form> {% endblock %} UTILS.PY def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If …
- 
        DJango Python deployment on Heroku stopped workingWe have django based python 3.7 version application was running properly on heroku but suddenly since 2 week all new deployment fails with following error. Its working on my local machine with runserver command. Here is errors logs for more reference. please help me as my prod app needs new changes to deployed and now everything is blocked. Updated Pipfile.lock (599d25)! Installing dependencies from Pipfile.lock (599d25)… To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. Removing intermediate container 2125752d2f35 ---> a3b53b037080 Step 10/11 : RUN pipenv install --system ---> Running in fcb5350323a4 Installing dependencies from Pipfile.lock (599d25)… An error occurred while installing importlib-metadata==4.10.0 ; python_version < '3.8' --hash=sha256:92a8b58ce734b2a4494878e0ecf7d79ccd7a128b5fc6014c401e0b61f006f0f6 --hash=sha256:b7cf7d3fef75f1e4c80a96ca660efbd51473d7e8f39b5ab9210febc7809012a4! Will try again. An error occurred while installing zipp==3.7.0 --hash=sha256:9f50f446828eb9d45b267433fd3e9da8d801f614129124863f9c51ebceafb87d --hash=sha256:b47250dd24f92b7dd6a0a8fc5244da14608f3ca90a5efcd37a3b1642fac9a375! Will try again. Installing initially failed dependencies… [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/cli/command.py", line 254, in install [pipenv.exceptions.InstallError]: editable_packages=state.installstate.editables, [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 1874, in do_install [pipenv.exceptions.InstallError]: keep_outdated=keep_outdated [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 862, in do_install_dependencies [pipenv.exceptions.InstallError]: _cleanup_procs(procs, False, failed_deps_queue, retry=False) [pipenv.exceptions.InstallError]: File "/usr/local/lib/python3.7/dist-packages/pipenv/core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: ['Collecting importlib-metadata==4.10.0 (from -r /tmp/pipenv-01ok21hj-requirements/pipenv-lkap3a1h-requirement.txt (line 1))'] [pipenv.exceptions.InstallError]: ['Could not find a version …
- 
        Django ChoiceField get choice value in templateI have a radio button which is a yes / no. YES_NO_CHOICES = [(False,'No'),(True,'Yes')] I also have a choicefield in my ModelForm show_game = forms.ChoiceField(widget=forms.RadioSelect, choices=YES_NO_CHOICES, required=True) I dislike the HTML provided by Django; hence, I made a custom html with css which looks like this: <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="id_show_game" id="{{radio.id_for_label}}" value="{{radio.id}}" {% if forloop.counter0 == 0 %}checked="checked"{% endif %}> <label class="form-check-label" for="{{radio.id_for_label}}">{{radio.choice_label}}</label> </div> However, value is appearing empty: How do I access the value of radio which is a ChoiceField WITHOUT using the following: {{radio}} <- result from {% for radio in gameInfoForm.show_game %} {{form}} <- ModelForm type
- 
        I can't center <textarea>I try to center my <textarea> elements in my pet project but I can't find a way to do that. I have tried using the following approaches: Changing my textarea in CSS: textarea { display: flex; justify-content: center; align-items: center; } Using the text-align property: <div style="text-align: center"><textarea>I am <textarea></textarea></div> Using also <center> tag. Surprisingly, it worked. But I don't like this solution because it is condemned to use. Down here is link of the picture from my project (I can't post one due I don't have enough reputation). Here you can see I have two blocks: textarea provided by Django framework and standard HTML textarea. Both of them are not centered. (https://i.imgur.com/1AzKrWJ.png) Here is my code: <p>Write the reason(s) for refusal:</p> {% render_field form.refusal_reason placeholder="Text..." %} <div style="text-align: center"><textarea>I am <textarea></textarea></div> I have been finding for a solution for a long time but haven't succeed. I will be happy for any useful answer.
- 
        Django - Displaying Images in TemplatesI have a Django Website and I am currently working on a delete view that has to be a function-based view for later use. I need to display a name and an image in the template of the data I am deleting at that moment. I had it working as a class-based view but now I need it to be a function-based delete view. The code below works and displays the name but when it comes to the image(which is an image field so I cant just type in a URL in the src) it just displays that little miscellaneous image box on the screen and not my actual image. In the templates, if I put {{ image.url }} it displays nothing. How can I get and image to display in the template from a specific pk in a function-based view. views.py def deleterepo(request, pk): context = {} context['name'] = Add_Repo.objects.values_list('name', flat='True').filter(user=request.user).get(pk=pk) context['image'] = Add_Repo.objects.values_list('image', flat='True').filter(user=request.user).get(pk=pk) obj = get_object_or_404(Add_Repo, pk=pk) if request.method == "POST": obj.delete() return HttpResponseRedirect("/front_page/sheets/") return render(request, "sheets/repo/delete_repo.html", context) {{ name }} <img src="{{ image }}"/>
- 
        Django. I can't download filesI am creating a function to download the created text file when the button is selected on HTML. I created it, but it doesn't download. Is it correct to understand that if this process is successful, it will be downloaded to the download folder? Can you help me? HTML <form action="" method="get"> <button class="btn btn-primary mt-1" type="submit" name="process">PROCESS</button> </form> views ・・・Preprocessing・・・ def downloadtest(readfile): with open(readfile, "r") as f: lines = f.readlines() for line in lines: print(line, end="") response = HttpResponse(f.read(),content_type="text/plain") response["Content-Disposition"] ='attachment; filename=readfile' return response tried lines = f.readlines() for line in lines: print(line, end="") We have also confirmed that the file exists and can be read by this process.