Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Format data to pass to Javascript chart
Sorry in advance for the confusing post. I have some questionnaires that are used to score a project across different areas, like marketing, costs etc. I'm trying to build a chart that shows the score of each project across each area. The format for the chart needs to be name: 'Project Name', data: [2,5,1,4,4,5,6,2] }], with each number being the score of each area. I've managed to get as far as collecting the score for each project for each area, but it duplicates the project name for each questionnaire. [projectName1, Questionnaire1, Score] [projectName1, Questionnaire2, Score] [projectName2, Questionnaire1, Score] ... I'm not sure of the approach I need to take: for project in all_projects: for q in questionnaires: print("getting ", q.title, "responses for", project.name, project.id) if ProjectQuestionnaireResponse.objects.filter(project_name_id=project.id, questionnaire_id = q.id).exists(): q_response = ProjectQuestionnaireResponse.objects.get(project_name_id=project.id, questionnaire_id = q.id) q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).count() if q_answered > 1: q_count = (100 / ProjectQuestionnaireQuestion.objects.filter(questionnaire_id = q.id).count() * q_answered) else: q_count = 0 q_rounded = (5 * round(q_count / 5)) # Scoring Calculator # # Get Questionnaire Range total_questions =ProjectQuestionnaireQuestion.objects.filter(questionnaire_id = q.id).count() score_range = (4 * total_questions) green = 2 red = -2 green_answer_value = (ProjectQuestionnaireAnswer.objects.filter(response = q_response,answer__choice_value="Green").count() * green) red_answer_value = (ProjectQuestionnaireAnswer.objects.filter(response = q_response,answer__choice_value="Red").count() … -
Can you load data from database into Bootstrap modal using Python?
I have a Django project where you can do CRUD operations. I am trying to make it so that when someone tries to edit, a modal will pop up with the data of x or y. I have a strong python background so I'm trying to do this in python. I tried doing it in javascript but I don't know where to start. Any help would be appreciated. -
Get_or_create or form validation then create?
I know this is a somewhat common thing to do but I'm struggling to grasp how to make it work from examples. I want to have a form where the user inputs an object ID (similar to an ISBN for a book). I want to check if that object exists in the db, if not, I want to create the entry based on some info I'll pull from a script using that ID. It seems like I could go two ways. I could use get_or_create, or I could do this with the cleaned data in the form and then I haven't been able to make either work but I think I have some basic misunderstanding of how they work. What is the best way of going forward? -
Django/Daphne/Nginx Websockets not connecting
I am using django with daphne and nginx to run my websockets. Everything was working fine for months in production, however just a couple days ago my websockets wouldn't connect saying "WebSocket connection to 'wss://mydomain:8001/clips/509/' failed: ". I checked the server logs and this is in the output 2022-04-07 16:57:22,970 ERROR [Failure instance: Traceback: <class 'AttributeError'>: 'NoneType' object has no attribute 'replace' Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/autobahn/websocket/protocol.py:2839:processHandshake Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/txaio/tx.py:366:as_future Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/daphne/ws_protocol.py:72:onConnect Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: --- <exception caught here> --- Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/daphne/server.py:200:create_application Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/routing.py:54:__call__ Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:35:__call__ Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:53:valid_origin Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:72:validate_origin Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:73:<genexpr> Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /home/django/Odyssey/venv/lib/python3.8/site-packages/channels/security/websocket.py:97:match_allowed_origin Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /usr/lib/python3.8/urllib/parse.py:376:urlparse Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: /usr/lib/python3.8/urllib/parse.py:430:urlsplit Apr 07 16:57:22 ubuntu-s-1vcpu-1gb-nyc1-01 python[1276]: ] I don't understand why this happened all of the sudden, is it maybe a dependency got updated or depracted? Any ideas are helpful cause I am mad stuck. -
Django 4.0.3 and mssql-django 1.1.2 will not connect to SQL Server Express 2019
I have been going by this tutorial for mssql-django https://docs.microsoft.com/en-us/samples/azure-samples/mssql-django-samples/mssql-django-samples/ My setup is Django 4.0.3 and mssql-django 1.1.2 will not connect to SQL Server Express 2019 on Windows 10, with the SQL Server Express 2019 running locally. I have searched both GitHub and Stack Overflow for examples of mssql-django configurations, but not much is turning up. I am not sure what I am doing wrong. The main things I have been trying is betting on the NAME, USER or HOST parameter being incorrect, as the others seem to be correct. Should NAME be: avxdb or mxlaptop\\avxdb or something else? Should USER be: pyadmin@mxlaptop or just pyadmin? Should HOST be: mxlaptop\SQLEXPRESS, mxlaptop\ss2019, mxlaptop, or 127.0.0.1? DATABASES = { 'default': { "ENGINE": "mssql", "NAME": "avxdb", "USER": "pyadmin@mxlaptop", "PASSWORD": "Python", "HOST": "mxlaptop\SQLEXPRESS", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, } } I have a normal Python script that can connect to the database via pyodbc: connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};' 'SERVER=mxlaptop;' 'DATABASE=avxdb;' 'UID=pyadmin;' 'PWD=Python;') -
Django user updates profile picture and the other users receive this changes too
I created a form so that every user can update its profile. What it's happening is that when a user changes the profile picture of its account, also it changes the profile picture of the other users and of course, I don't want that. This is my code: signals.py def create_user_profile(sender, instance, created, **kwargs): if created: profile = Profile(user=instance) profile.save() post_save.connect(create_user_profile, sender=User, dispatch_uid="profilecreation-signal") forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = [ "first_name", "last_name", "image", "description", "website" ] views.py def profile_page(request, username): form = ProfileForm(data=request.POST, files=request.FILES, instance=request.user.profile) if request.method == "POST": if form.is_valid(): form.save() return redirect(request.META['HTTP_REFERER']) context = { "profile_form": form, } return render(request, "profile.html", context) The profile_page view has username also as attribute because there is more code related to it. Could someone help me? Thanks! -
Django - Comment Xtd - implement title attribute in admin model
I am using the django-comments-xtd app to handle comments and replies. I want to replace the object id in the admin panel with the object title but I am struggling to do that. The code that is in models.py can be found here. I am not pasting it here because it is a long piece of code. Below is my "customized" XtdCommentsAdmin model: class XtdCommentsAdmin(CommentsAdmin): list_display = ('name', 'comment', 'content_type', 'object_pk', 'submit_date', 'is_public', 'is_removed', 'title') ... def title(self, obj): return obj.object_pk.title #what am I doing wrong here? I tried to return obj.title, obj.object_pk.title in my title attribute but I get this output <built-in method title of str object at 0x000001F3BC859120> I also tried to use lookup directly in list_display like object__title but the only thing I get is this: The value of 'list_display[3]' refers to 'object__title', which is not a callable, an attribute of 'XtdCommentsAdmin', or an attribute or method on 'django_comments_xtd.XtdComment'. Could you please tell me how to display the object title instead of the object id? -
AttributeError: 'str' object has no attribute 'text' PyTelegramBotAPI
I was creating a bot that measures the size of a rectangle using the pytelegrambotapi library. I created a database using Python django. Purpose: When a bot is used by more than one user, the bot retrieves the parameters entered by each user from the database and returns a response to them. But the following error is observed in my code: AttributeError: 'str' object has no attribute 'text' I don’t understand where and why this error is happening. BOT.PY ... ... float_pattern = r'^\d{1,7}\.\d{1,2}$' int_pattern = r'^\d{1,7}$' ... ... def perimeter(message): if re.match(int_pattern, message.text) or re.match(float_pattern, message.text): p = float(message.text) chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() print(p, type(p), 'Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Good") msg = bot.send_message(message.chat.id, "Enter height:") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Only number!") bot.register_next_step_handler(msg, perimeter) def height(message): if re.match(int_pattern, message.text) or re.match(float_pattern, message.text): h = float(message.text) chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param2=message.text ).save() print('Parameter (h) from:', chat_id) bot.send_message(message.chat.id, "Good!") msg = bot.send_message(message.chat.id, "The answer is f'{str(result())}'") return h else: msg = bot.send_message(Only number!) bot.register_next_step_handler(msg, height) def result(): p = '' # perimeter h … -
Custom Permissions for admin for get and delete only
In Django rest framework, I want only owner can CREATE, PUT and DELETE but Admin can only have permission for GET and DELETE only not PUT method -
DJANGO int() argument must be a string, a bytes-like object or a number, not 'list'
Hello sir i have in DJANGO a problem tryin to get my algorithm right please help, much appreciated: MYERROR: int() argument must be a string, a bytes-like object or a number, not 'list' MYCODE: def subs(request, pk): sw = Swimmers.objects.filter(id=pk).values('sessions') sw_list = int(list(sw)) res = sw_list +1 print('Data:',sw) return JsonResponse(res, safe=False) -
ProgrammingError at /user_booking not all arguments converted during bytes formatting
The idea is to display user's booking information like booking_name, package etc. I am fetching the data from database in my views.py like this. def user_booking(request): id = request.session['u_id'] booking_data = Booking.objects.raw('select * from booking WHERE id = %s',id) return render(request,'user_booking.html',{'view_data':booking_data}) Now in user_booking.html is displaying data. I have used a proper template to display data in tabular format. Problem is when some data is returned from data base it works perfect. When there is a query for which no data can be found the page breaks and shows "ProgrammingError at /user_booking not all arguments converted during bytes formatting" Instead of all the formatting I resorted to basic code which looks like this <html> {% for b in view_data %} {{b.b_name}} {% endfor %} </html> It gives me the name "ajay" as output and does not break the page, also note that record for ajay's ID is present in my database. Now if ID is changed and then I refresh the lage again it gives me error. What I am trying to do is if there is any data coming from the database then display it otherwise just display "no data here" msg. How do I achieve it? -
How do I get rid of "Inconsistent Migration History" error on Python using Django framework in Docker environment?
The error itself: This is the structure of my app file system: -
can't access database values of django MultiSelectField in an external script
I have a simple scenario where i have a django multiselectfield and the choices are: jobs_multiple_choice = ( (1, 'Social Media Manager'), (2, 'Online Tutor'), (3, 'Bookkeeper'), (4, 'Personal Trainer'), (5, 'Email Marketer'), (6, ' Freelance Writer'), (7, 'Website Designer'), (9, 'Instagram Influencer'), (8, 'SEO Expert '), (10, ' Facebook Ads Specialist '), (11, 'Graphic Designer'), (12, 'Voiceover Artist'), (30, 'Stock Photographer '), (62, 'Data Entry Worker'), ) i want to save number as an id of the jobs, now i want to get the data of the model into an external python script i did the usual import but i have an issue. script.py: import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') django.setup() from practice.models import Jobs a = Jobs.objects.all().first() print(a.name) the output its giving is representative value and not the number like ['1', '2', '42','4', '24'] etc but getting: Social Media Manager, Online Tutor, Bookkeeper, Personal Trainer, Email Marketer, Website Designer, Graphic Designer, Voiceover Artist, Data Entry Worker but! when i do that in manage.py shell, its giving me the desired value like below >>> from practice.models import Jobs >>> a = Jobs.objects.all().first() >>> b = Jobs.objects.all().last() >>> a.name ['1', '2', '3', '4', '5', '7', '11', '12', '62'] >>> b.name … -
Decentralization in blockchain project
I am creating a web application for storing data on the blockchain. There will be about a dozen holders of the system. The following question arose: how to create a decentralized and secure system and which method of data protection do you consider the best? -
Django Validation with and or rule
The condition supposed to be only if this field is filled other field do not need to filled. No with this code i have to fill out all the fields if (self.start==None and self.end==None) or (self.running==None and self.walking==None ) : raise ValidationError( { "start": _("Need to be filled"), "end": _("Need to be filled"), "running": _("Need to be filled"), "walking": _("Need to be filled") } ) -
django NOT NULL constraint failed:
I am getting 2 errors trying to add products to my cart in a website in django. IntegrityError at /apiadd/ NOT NULL constraint failed: cianshop_basketitem.basket_id_id in my console i see this: " productindividual?id=1:136 POST http://127.0.0.1:8000/apiadd/ 500 (Internal Server Error) addToCart.onclick @ productindividual?id=1:136 VM55:1 Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0 " this is my models.py file: from dataclasses import is_dataclass from django.db import models from django.contrib.auth.models import AbstractUser class APIUser(AbstractUser): pass class Product(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() description = models.TextField(null=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=0.0) #9999.99 image = models.FileField(upload_to='products', null=True) class Basket(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey(APIUser, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) class BasketItem(models.Model): id = models.IntegerField(primary_key=True) basket_id = models.ForeignKey(Basket, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def price(self): return self.product_id.price * self.quantity def product_name(self): return self.product_id.name class Order(models.Model): id = models.IntegerField(primary_key=True) basket_id = models.ForeignKey(Basket, on_delete=models.CASCADE) user_id = models.ForeignKey(APIUser, on_delete=models.CASCADE) datetime_ordered = models.DateTimeField(auto_now_add=True) total_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.0) shipping_addr = models.TextField(default="") -
cannot find images in react response
I am trying to return multiple images in django to react. But I am unable to retrieve the images in react. My httpresponse is dictionary in this format: {id1:[image1,image2], id2:[image1,image2} but I am getting only integers as a response in react. django code: images = {} for id in post_ids: img_obj = PostImage.objects.filter(post_id=id) imgs = [img_obj[0].image.file] try: x = img_obj[0].other_image1.file imgs.append(x) except ValueError: pass try: x = img_obj[0].other_image2.file imgs.append(x) except ValueError: pass try: x = img_obj[0].other_image2.file print('type', type(x)) imgs.append(x) except ValueError: pass images[id] = imgs return HttpResponse(images) react code: const submit = () =>{ const token = localStorage.getItem('access'); axios.post(url, { token: token, }).then(res => { if (res.status===200){ console.log(res.data); }else{ alert('error'); } }) } output in cosole 234567 -
Exception in thread django-main-thread unable to run server
[Exception in thread django-main-thread:][1] [Exception in thread django-main-thread:][2] [1]: https://i.stack.imgur.com/b4KFS.png [2]: https://i.stack.imgur.com/w6ko3.png -
Django - How to add "or" condition to queryset.filter in custom filter
i want to make a search filter which searches in multiple fields with multiple conditions, using only one search field. I have this filters.py file: import django_filters from .models import Product class ProductFilter(django_filters.FilterSet): q = django_filters.CharFilter(method='search_filter', label='Cerca') class Meta: model = Product fields = ['q'] def search_filter(self, queryset, name, value): return queryset.filter(name__icontains=value, sku__iexact=value) but return queryset.filter(name__icontains=value, sku__iexact=value) doesn't work, neither return queryset.filter(Product(name__icontains=value) | Product(sku__iexact=value)) How can i do this? -
Django query in list view to group similar category records
I have my website which displays the records on website these records are of different categories how can group the records belongs to similar category and display them together category 1 List item 1 List item 2 List item 3 class Mymixin: def get_queryset(self): return Record.objects.all() class Model: category = models.Charfield() -
Django Exception Type: ProgrammingError Exception Value: no existe la función sum(character varying)
I got an error when i use postgresql total = DetalleFacturas.objects.filter(IdFactura__Fecha__range=[fechainicio, fechafinal], IdFactura__IdBodega__Vendedor__Email=request.user.email).aggregate( Sum('Total')) And i have got this error: ProgrammingError at /reportehelisa/ no existe la función sum(character varying) LINE 1: SELECT SUM("DetalleFacturas"."Total") AS "sum" FROM "Detalle... It's work fine in sqlite but postresql not work -
How to override get_queryset() whilst using UpdateView Django
I have inherited UpdateView and I am trying to override the get_queryset() method, but it keeps throwing an error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: UserProfileManagement is missing a QuerySet. Define UserProfileManagement.model, UserProfileManagement.queryset, or override UserProfileManagement.get_queryset(). models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() return super(User, self).save(*args, **kwargs) def __str__(self): return self.email managers.py class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save() return user views.py class UserProfileManagement(UpdateView): Model = User template_name = 'users/user_profile.html' fields = ['first_name', 'last_name'] def get_queryset(self): queryset = super(UserProfileManagement, self).get_queryset() return queryset.filter(pk=3) However, if I override the get_object() instead it works. def get_object(self, queryset=None): return User.objects.get(pk=3) -
how do I render shipping address_one object associated with a specific order
So the customer has an order page where I want to render their order details, specifically product name, date ordered, status, and their delivery location, right now I got everything to work except the delivery location("address_one"). I would really appreciate it if someone can help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) views.py @login_required def orders(request): orderitems = OrderItem.objects.filter(order__customer__user=request.user) #how do I get the shipping address associated with order shipping = ShippingAddress.objects.filter() context = {"orderitems": orderitems, "shipping": shipping} HTML {% for orderitem in orderitems %} <div class="order-data-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">{{ orderitem.date_added }}</div> <div class="status">dummydata</div> <div class="delivering-to">{{ shipping.address_one }}</div> </div> {% endfor %} -
Is there a way to make a mock timezone for a Selenium test in Django?
In my selenium test below I'm trying to test my Analytics model. I'm using a mock of an Analytics model instance from class AnalyticsFactory. When I run this test everything works fine except I get an error for the timestamp field in the Analytics model. Note: I'm using timezone.now() for this. It seems like the time from when I run the test and when the time is assigned to the Analytics factory is slightly different. For example this is the error I'm getting: AssertionError: datetime.datetime(2022, 4, 8, 13, 3, 28, 153988, tzinfo=<UTC>) != datetime.datetime(2022, 4, 8, 13, 3, 28, 48016, tzinfo=<UTC>) in the error above 153988 and 48016 are different Is there a way I could set a 'fake' timezone object instead of using timezone.now()? Since it seems like 'now' is so precise that I can't get this to work. test_models.py: from django.utils import timezone from django.test import TestCase from myapp.tests.factories import UserFactory, AnalyticsFactory from myapp.models import Analytics class MyTestCase(TestCase): def setUp(self): self.admin = UserFactory( username='first.last@gmail.com', email='first.last@gmail.com', password=12345 ) self.a1 = AnalyticsFactory( user=self.admin, timestamp=timezone.now(), views=10 ) def test_analytics(self): a = Analytics.objects.get(id=6) self.assertEqual(a.views, 10) self.assertEqual(a.user, self.admin) self.assertEqual(a.timestamp, self.a1.timestamp) <--- not working self.assertEqual(response.status_code, 200) factories.py: import factory from myapp.models import Analytics from … -
Creating a root comments and comments with ancestors from the same view
I'm creating comments system like in twitter. Everything works fine with displaying the tweet, its ancestors and descendants. The main problem is I want to create root tweets and tweets with ancestors from the same url (e.g 'compose/tweet/). At the moment my code for this task is working. I have hidden input in my form with parent id value attr if user wants to create an answer on tweet. Attr is empty if root tweet will be created. <form action="{% url 'tweets:make_tweet' %}" method="post" novalidate> {% csrf_token %} {% render_field tweet_form.parent value=id %} <div class="tweet-form-textarea mb-2" id="tweet-form-textarea{{ id }}"> {% render_field tweet_form.text class="form-control fs-5" rows="3" placeholder=placeholder %} </div> <div class="tweet-form-footer d-flex flex-row align-items-center" id="tweet-form-foote{{ id }}"> <span class="chars-counter visually-hidden"></span> <input type="submit" class="make-tweet-btn fw-bold btn rounded-pill" value="Tweet"> <div> </form> Form renders with inclusion template tag: @register.inclusion_tag('tweets/tweet_form_snippet.html', takes_context=True) def render_tweet_form(context, id=''): return { 'tweet_form': context['form'], 'id': id } And finally value attr is populating in template(simplified version): {% if not tweet %} {% render_tweet_form %} {% else %} {% render_tweet_form id=tweet.id %} {% endif %} The form is processed from class: class MakeTweetView(BaseCreateView): form_class = TweetForm def form_valid(self, form): tweet = form.save(commit=False) # Searching for value in hidden input parent = self.request.POST['parent'] …