Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't load static files in Django with right setting
Can't load static files from app called 'gameMuster' even if I'm sure everything is okey with settings.py. Project structure Statics confs Installed apps -
why am i getting this error "expected string or bytes-like object"
I am creating a youtube video downloader with Django and bootstrap but when I try to get the youtube video link and redirect to the download page, I get the error "expected string or bytes-like object" below are my HTML and views.py code views.py from django.shortcuts import render from pytube import YouTube def youtubedownloader(request): return render(request, 'youtube_downloader.html') def download(request): url = request.GET.get('url') yt = YouTube(url) video = yt.streams print(video) return render(request, 'download.html') youtube_downloader.html {% extends 'base.html' %} {% block content %} <div class="mt-5"> <center><h1>Download Youtube Video</h1></center> </div> <div class="container mt-5"> <form method="GET" action="download/"> <div class="form-group align-items-center"> <div class="col-auto"> <label class="sr-only" for="inlineFormInput"></label> <input name="url" type="text" class="form-control mb-2" id="inlineFormInput" placeholder="Paste Youtube link here"> </div> </div> <center> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-2">Go</button> </div> </center> </form> </div> {% endblock content %} -
Error creating a multi-step form using Django session
I'm currently working on building a multi-step registration form in Django. I followed the official documentation which can be seen here. Although the forms do not show any error, the user does not get created. Is there a problem I might be overlooking? def signup_step_one(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('accounts:personal-signup')) else: if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): # collect form data in step 1 email = form.cleaned_data['email'] password = form.cleaned_data['password1'] # create a session and assign form data variables request.session['email'] = email request.session['password'] = password return render(request, 'personal-signup-step-2.html', context={ 'form': form, "title": _('Create your personal account | Step 1 of 2'), }) else: form = CustomUserCreationForm() return render(request, 'personal-signup-step-1.html', { "title": _('Create your personal account | Step 1 of 2'), 'form': form, }) def signup_step_two(request): # create variables to hold session keys email = request.session['email'] password = request.session['password'] if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = email user.set_password(password) user.first_name(form.cleaned_data['first_name']) user.last_name(form.cleaned_data['last_name']) user.save() print('user created') return HttpResponse('New user created') else: form = CustomUserCreationForm() return render(request, 'personal-signup-step-2.html', { "title": _('Create your account | Step 2 of 2'), 'form': form, }) -
Module for pagination in the django framework
I'm writing a web application that uses the google book API to display books that the user searches for. I'm now trying to add pagination to the application, but I'm struggling to find great resources to implement this. I have looked into the Pagination Class, but it seems as it designed to paginate results from a database and not responses from API calls. Do you have any tips or good resources to look into, modules or something that could make it a little bit easier to implement this? Any tips are highly appreciated, Thanks! -
I'm trying to send an email from Django using Gmail SMTP
I've set insecure source ON in my account's setting. Also, this is my settings.py file. Can anybody help me? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com ' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER =' my email' EMAIL_HOST_PASSWORD = 'my password' and I'm getting this error in terminal when I write this code PS D:\start here\silicium7\config-project> python manage.py sendtestemail atabarzega79@gmail.com Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\start here\silicium7\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\start here\silicium7\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\start here\silicium7\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "D:\start here\silicium7\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "D:\start here\silicium7\lib\site-packages\django\core\management\commands\sendtestemail.py", line 33, in handle recipient_list=kwargs['email'], File "D:\start here\silicium7\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "D:\start here\silicium7\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "D:\start here\silicium7\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "D:\start here\silicium7\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 307, in _get_socket self.source_address) for res in getaddrinfo(host, port, 0, … -
permission to add new user in Django
in localhost/admin there is a button for adding new user(figure 1) and this permission is not for all the users figure 1 how can I add this promotion to other user and make it in another template not have to enter to localhost/adminto add a new user and how can I create this new user without email or password (temporary user) (figure2 figure 2 -
Problem with django server (page not loading)
I am currently using Stripe API to develop my own checkout through python/html in Visual Studio Code. I have successfully run a localhost server and I have a django server up and running. When I press checkout, the screen does not go onto the checkout screen, it just stays on the same screen[enter image description here][1]. I am wondering why this is happening? My code for my checkout page (views.py) is: import json import stripe from django.core.mail import send_mail from django.conf import settings from django.views.generic import TemplateView from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from django.views import View from .models import Product stripe.api_key = settings.STRIPE_SECRET_KEY class SuccessView(TemplateView): template_name = "success.html" class CancelView(TemplateView): template_name = "cancel.html" class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': product.price, 'product_data': { 'name': product.name, # 'images': ['https://i.imgur.com/EHyR2nP.png'], }, }, 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return JsonResponse({ 'id': checkout_session.id }) @csrf_exempt … -
Django : Displays "No Value " When trying to fetch checked checkbox without submit using AJAX
i wrote a program using django to retrieve all checked checkbox without submit button by using AJAX , it is not throwing any error , but it displays "NO Value " . Can anyone check and tell me what is the mistake i did . AJAX : <script> $('.form-check-input').change(function(){ // checkbox1 change event var checked_lists = []; $(".form-check-input:checked").each(function() { checked_list.push(this.value); }); var formdata = new FormData(); $.ajax({ formdata.append('checked_list',checked_list) formdata.append('csrfmiddlewaretoken',$('input[type=hidden]').val()); $.ajax({ url:"secondtableonDashboard", //replace with you url method:'POST', data:formdata, enctype: 'application/x-www-form-urlencoded', processData:false, contentType:false, success:function(data){ alert("Display return data"+data) }, error:function(error){ alert(error.error) } }); }); }); </script> Views.py if request.method=='POST': user_list = request.getlist('checked_list') print(user_list) else: print("No Values") html : <td> <div class="form-check form-switch"> <input class="form-check-input" name="Servers[]" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </div> </td> -
How can we get the user to add .csv files using django and mongodb?
I'm very new to both Django & MongoDB and I'm trying to make a project which is about NLP. So, at first, we are going to have a web site. It starts with a user login. User can upload .csv files to the web site and we are going to processes and return to the user as a result. We are going to keep the NLP processing codes in docker. For the database, we are using MongoDB and for the backend side, we are using Django. My question is, How am I going to read and store these .csv file data in MongoDB? I know how to upload .csv files into Django. But, I have no idea what I am going to do if the files coming from the user. -
how can I get an id from request.POST of the form that I'm submitting now
I'm building a clinic Management System and in the section that you add a new doctor, I want the admin to be able to add the days that the doctor is available at, so that means the days' field is a list but Django doesn't have a list field in its models so I created CharField-> days days = models.CharField(max_length=200,null=True) and then I've created a multi-select input field inside the form <select name="days" class="form-select" multiple aria-label="multiple select example"> <option value="mon">Mon</option> <option value="sun">sun</option> <option value="wed">wed</option> <option value="etc">etc</option> </select> so I took the Selected data by using this code for i in request.POST.getlist("days"): d= str(i)+" "+d print(d) # result gonna be the days in string value splited by spaces eg : mon sun wed so I can use it later by using split() but the thing is I'm not able to add this data into the form while submitting it so I thought that I can save the form data and then alter the field days like that def add_doctor(request): form = Add_doctorForm() if request.method == "POST": form = Add_doctorForm(request.POST) if form.is_valid(): form.save() d = "" for i in request.POST.getlist("days"): d= str(i)+' '+d print(d) formdata = Doctors.objects.get(id = request.POST.get("id") formdata.days = d … -
how to link two models in one form in CreateView?
There are two models. Attachment must bind to Post. models.py class Post(models.Model): title = models.CharField(verbose_name='Название', max_length=300) slug = models.SlugField(verbose_name='Ссылка', max_length=300, blank=True, db_index=True) category = models.ForeignKey('Category', verbose_name='Категория', on_delete=models.CASCADE) content = models.TextField(verbose_name='Описание') created_by = models.ForeignKey(User, verbose_name='Материал добавил', on_delete=models.SET_DEFAULT, default=1, related_name='post_created_by') updated_by = models.ForeignKey(User, verbose_name='Материал обновил', on_delete=models.SET_DEFAULT, default=1, null=True, related_name='post_updated_by') is_published = models.BooleanField(verbose_name='Опубликовать', default=True) views = models.PositiveIntegerField(verbose_name='Просмотры', default=0, blank=True) time_create = models.DateTimeField(verbose_name='Дата создания', auto_now_add=True) time_update = models.DateTimeField(verbose_name='Дата обновления', auto_now=True) # META author = models.CharField(max_length=255, verbose_name='Автор', blank=True) source = models.URLField(max_length=255, verbose_name='Ссылка на источник', blank=True) def get_absolute_url(self): return reverse('post', kwargs={'cat_slug': self.category.slug, 'slug': self.slug, 'pk': self.pk}) class Attachment(models.Model): post = models.ForeignKey('Post', verbose_name='Прикрепить файл', on_delete=models.SET_NULL, null=True, related_name='post_attachment') link = models.URLField(verbose_name='Основная ссылка', blank=True) meta_link = models.CharField(verbose_name='Информация', max_length=255, blank=True) load = models.PositiveIntegerField(verbose_name='Загрузки', default=0, blank=True) type = models.ManyToManyField('Type', related_name='type_post') version = models.CharField(verbose_name='Версия материала', max_length=255, blank=True) forms.py class PostForm(ModelForm): class Meta: model = Post fields = '__all__' class AttachmentForm(ModelForm): class Meta: model = Attachment fields = '__all__' exclude = ('post',) How to connect them in CreatView in views.py? I just tried different ways, errors came out. I don't understand a little how to make a formsets. -
I am trying make a custom user signup form and getting following error while making this
I am trying to extend the user model from django.db import models # Create your models here. class RegisterUser(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) phone_number = models.CharField(max_length=20) sector = models.CharField(max_length=50) and tried to create a form for the signup from django.contrib.auth.forms import UserCreationForm from .models import RegisterUser class CreateUserForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = RegisterUser fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'phone_number', 'sector') ** These are the only changes I made I am getting the following error:** raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (username) specified for RegisterUser -
MultipleObjectsReturned: get() returned more than one Post -- it returned 2
This error only happens if multiple users have the same title for their posts. For example, if john has a page with a title 'mypage' this is the error shown if another user has the same title for their page as john. `MultipleObjectsReturned at /john/mypage/update/` get() returned more than one Post -- it returned 2! but if no one else has it, no error is shown when trying to update the post. class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user ##author = current logged in user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False Model class Post(models.Model): title = models.CharField(max_length=100, default=None) slug = AutoSlugField(populate_from='title', null=True) def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug, 'author': self.author}) urls urlpatterns = [ path('landingpage/new/', PostCreateView.as_view(), name='post-create'), path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ] + static(settings.M EDIA_URL, document_root=settings.MEDIA_ROOT) -
Can't display SVG images
I can't manage to display and SVG image in an HTML template. I'm working with Django, and this is how my HTML looks like: <svg><use xlink:href="{% static 'user_template_2/assets/test.svg' %}"></use></svg> The path and the filename are correct, I'm loading other static assets using that same directory. I've already added this to my settings file: import mimetypes mimetypes.add_type("image/svg+xml", ".svg", True) mimetypes.add_type("image/svg+xml", ".svgz", True) Any idea what I might be missing? -
Embed Linux screen Terminal in webpage
I am want to embed Linux screen session to embed in django website. Is there is any way to do embed only specific screen in webpage. -
Django tests fails with <model> has not attribute 'object' error
I have the following two models: class Resource(models.Model): identifier = models.UUIDField(default=uuid.uuid4, unique=True) date_added = models.DateTimeField(default=now) def __repr__(self): return f'Resource: {self.identifier}, Time added: {self.date_added}' class URLResource(Resource): url = models.URLField() def __repr__(self): return f'{self.identifier} URL: {self.url}' When I run the following commands in the django shell, everything works fine: > from user_page.models import URLResource > URLResource.objects.create(url='abc') # outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc` > URLResource.objects.get(url='abc') # outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc` However, my seemingly trivial test case fails, even though the similar execution succeeds in the django shell: from django.test import TestCase from users.models import CustomUser from .models import Resource, URLResource, Record class URLResource(TestCase): def setUp(self): url_resource = URLResource.objects.create(url='abc') print(repr(url_resource)) def test_url(self): print(repr(URLResource.objects.get(url='abc'))) I get the following error: ====================================================================== ERROR: test_url (user_page.tests.URLResource) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/admin/Desktop/readrrr/user_page/tests.py", line 26, in setUp url_resource = URLResource.objects.create(url='abc') AttributeError: type object 'URLResource' has no attribute 'objects' ---------------------------------------------------------------------- -
configuration has an unknown property 'devDependencies'
When I run my django server and try 'npm run dev', it gives me an error stating that there is no property called devDependencies. Is there something wrong with my JSON file? This is my package.json file: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.13.13", "@babel/preset-env": "^7.13.12", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.28.0", "webpack-cli": "^4.6.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } -
Get index info in postgres usin Django ORM
I'm using Postgres with Django and I want to get the info of an index I made on a table, specifically I want to see the size of the index. -
RelatedManager' object has no attribute 'description
I perform request http://167.71.57.114/api2/workout-exercises/3 I want to receive data about WorkoutExercise object number 3 (detail view) Got AttributeError when attempting to get a value for field description on serializer ExerciseSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py class WorkoutExerciseSerializer(serializers.ModelSerializer): exercises = ExerciseSerializer() class Meta: model = WorkoutExercise fields = ('week', 'exercises') views.py class WorkoutExerciseViewSet(viewsets.ModelViewSet): queryset = WorkoutExercise.objects.all() serializer_class = WorkoutExerciseSerializer http_method_names = ['get', 'post'] models.py class WorkoutExercise(models.Model): workout_program = models.ForeignKey(WorkoutProgram, on_delete=models.CASCADE, related_name='workout_exercises') week = models.PositiveIntegerField(default=1) day = models.PositiveIntegerField(default=1) order = models.PositiveIntegerField(default=1) def save(self, *args, **kwargs): if not self.pk: last_order = WorkoutExercise.objects.all().aggregate(largest=models.Max('order'))['largest'] if last_order is not None: self.order = last_order + 1 return super(WorkoutExercise, self).save(*args, **kwargs) def get_workout_programs(self): return self.workout_program.name def get_exercises(self): pass def __str__(self): return self.workout_program.name class Meta: ordering = ('week', 'day') -
'django.db.models' has no attribute 'StdImageField'
I'm trying to use django-stdimage to resize my picture but i'm getting this error AttributeError: module 'django.db.models' has no attribute 'StdImageField' Model from django.db import models from django.contrib.auth.models import AbstractUser from django.views.generic import TemplateView from django.db.models import Q from cloudinary.models import CloudinaryField from .validators import validate_file_size from stdimage.models import StdImageField class CustomUser(AbstractUser): picture = models.StdImageField(null=True, blank=True, upload_to="images", validators=[validate_file_size], size=(256, 256)) -
How to fetch data from database and show it in bootstrap's modal box ( pop up ) in django respectively?
Technologies I'm using --> Back-end --> Python, Web Framework --> Django, Front-end --> HTML5, CSS3, Bootstrap 4, Database --> SQLite3. What I want --> To display the data of each object in each bootstrap's modal box( popup ). The problem --> Data of the first object is only being shown in all the modal boxes( popups ). Files are as follows: HTML template --> manage_requisition.html 👇 {% extends 'hod_template/base_template.html' %} {% block page_title %} Manage Requisitions {% endblock page_title %} {% block main_content %} <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Manage Requisitions</h3> </div> <!-- /.card-header --> <!-- form start --> <div class="table"> <table class="table"> <tr> <th style="text-align: center;">Action</th> <th>View Requisition</th> </tr> {% for requisition in requisitions %} <tr> <td style="text-align: center; vertical-align: middle;"> {% if requisition.requisition_status == 0 %} <a style="width: 85px;" href="{% url 'supervisor_approve_requisition' requisition_id=requisition.id %}" class="btn btn-success inline" >Approve</a> <a style="width: 85px;" class="btn btn-danger inline" href="{% url 'supervisor_rejected_requisition' requisition_id=requisition.id %}" >Reject</a> {% elif requisition.requisition_status == 1 %} <button class="btn btn-warning" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Approved</button> {% else %} <button class="btn btn-danger" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Rejected</button> {% endif %} </td> <td> <button type="button" class="btn btn-warning" … -
How do I Autocomplete using JSON response
I am making a mock trading website and I need to populate an autocomplete dropbox with options, gotten from a JSON response. Here is some background, I am using Django for the backend and Materialize framework for the front end. And I am getting the JSON response from the IEX cloud API. I am using their search functionality. The problem: When a user enters the name of the company they don't always necessarily know the right symbol as well, so if I can make a drop-down box that makes it easier for them that would be awesome. The solution I envision: As the user types the name of the company it starts to give us autocomplete suggestions just like this: What I need: If you could give me a direction, a starting point, a resource I would be very happy. I have been roaming around the interwebs but I seem to find a solution, so if you can point me in the right direction that would be very much appriciated. -
Insert lat and lon in model fields after user fills in address
Is it possible to call an API (eg. Google Maps API) on submit (or even before submit?) and insert lat and lon values in the model's fields so they are saved to the DB my app is connected to? I want to re-use those values later in a view on the front-end outside the admin to plot them an a map. models.py: from django.db import models from django.db.models import Q class Address(models.Model): street = models.CharField(max_length=100) number = models.IntegerField(null=True) postal = models.IntegerField(null=True) city = models.CharField(max_length=100) country = models.CharField(max_length=100) is_primary = models.BooleanField(null=False) geo_lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) geo_lon = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) customer = models.ForeignKey("Customer", on_delete=models.CASCADE, related_name="addresses") class Meta: verbose_name_plural = 'Addresses' constraints = [ models.UniqueConstraint( fields=['customer'], condition=Q(is_primary=True), name='unique_primary_per_customer' ) ] def save(self, *args, **kwargs): if self.is_primary: self.__class__._default_manager.filter(customer=self.customer, is_primary=True).update(is_primary=False) super().save(*args, **kwargs) def __str__(self): return f"{self.street} {self.number}, {self.postal} {self.city}, {self.country}" class Customer(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) vat = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}" -
I don't know why instance is not working in form django
views.py @login_required def put(request, id): question = get_object_or_404(Question, id=id) poll_form = PollForm(request.POST, instance=question) print(poll_form) choice_forms = [ChoiceForm(request.POST, prefix=str( choice.id), instance=choice) for choice in question.choice_set.all()] if poll_form.is_valid() and all([cf.is_valid() for cf in choice_forms]): new_poll = poll_form.save(commit=False) new_poll.created_by = request.user new_poll.save() for cf in choice_forms: new_choice = cf.save(commit=False) new_choice.question = new_poll new_choice.save() return redirect('poll:index') context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'polls/edit_poll.html', context) html template {{poll_form.as_table}} {% for form in choice_forms %} {{form.as_table}} {% endfor %} models.py class Question(models.Model): title = models.TextField(null=True, blank=True) created_by = models.ForeignKey(User, null=True, blank=True, related_name="created", on_delete=models.CASCADE) forms.py class PollForm(forms.ModelForm): title = forms.CharField(max_length=333, label='Question') class Meta: model = Question fields = ['title'] class ChoiceForm(forms.ModelForm): text = forms.CharField(max_length=255, label='Choice') class Meta: model = Choice exclude = ('question',) when i inspect the element <td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="title" maxlength="333" required="" id="id_title"></td> fields are empty (but instead it should be filled by existing id questions and choice ) but i see errorlist class i dont know please help me but when i fill edit form and try to update things it worked -
For loop in django templates using Integerfield in model object
I have a model like this: class Testimonial(models.Model): rating = models.IntegerField(_("Rating")) I'm looping over all testimonials in Django templates using one for loop, now how do I display the ratings for each testimonial object. My stars class in HTML looks like this: <ul class="list-unstyled"> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star-half-alt"></i></li> </ul> How do I solve this issue?