Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'playgrounddebug_toolbar' , i followed documentation but still i getting this error
Django debug tool Error I followed the step by step written in the documentation https://django-debug-toolbar.readthedocs.io/en/latest/installation.html but still i getting this weird error, unable to understand it, can someone please help me out :) enter image description here -
Selected Options are deleted after renumbering a Adding/Removing Dynamic Formset with Selection Options using Javascript
I have created a dynamic formset for my django project to add and remove forms dynamically. To preserve the value of the fields after renumbering, I am saving the value of the field before renumbering and I am assigning the same value after renumbering the forms. It is working wonderfully in the text inputs but due to my limited experience and knowledge in javascript, I am not able to preserve the value of the selcted options. Any help and suggestions are highly welcomed. Thank You. <style type="text/css"> fieldset { border: none; } </style> <form id="demo" action="{% url 'my_formset' %}" method="POST"> {% csrf_token %} {{p_form}} <br> <hr> <!-- Keep Track of the Total Form Here --> <input id="total_forms" name="TOTAL_FORM_COUNT" value="0" type="hidden"> <!-- This is the Form that will be duplicated. We will hide this form. --> <fieldset disabled class="empty-form" style="display: none"> <fieldset class="fieldset" id="fs_0"> <label>Name</label> <input type="text" id="id-f-0-name" name="id-f-0-name" value=""> <label>Select:</label> <select id="id-f-0-item" name="id-f-0-item" placeholder=""> <option disabled selected value={{None}}> Select Item </option> <option value='1'>Butter</option> <option value='2'>Milk</option> <option value='3'>Tofu</option> <option value='4'>Soyabeans</option> </select> <button type="button" id="d-0" class="delete_form" onclick="del_form(this.id);"> DELETE </button> </fieldset> </fieldset> <!-- This is where we will insert the form --> <fieldset class="forms"> </fieldset> <!-- This is the ADD Button to add … -
Getting untraceable error 'tuple' object has no attribute 'get'
I am trying to save the form with some validation. Here is my forms.py class AddPatientForm(ModelForm): class Meta: model = Patient fields = [ 'category', 'case_paper_number', 'full_name', 'age', 'birth_date', 'gender', 'mobile_number', 'email', 'address_line_1', 'address_line_2', 'city', 'pin_code', 'referred_by', ] widgets = { 'birth_date': widgets.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'type':'date'}), } def clean_full_name(self): data = self.cleaned_data full_name = data['full_name'] if not len(full_name)>=10: raise ValidationError('Enter valid full name') Here is my views.py if request.method == 'GET': return render(request, 'main/addpatient.html', {'casepapernumber': casepapernumber, 'form':form}) elif request.method=='POST': form = AddPatientForm(request.POST) try: # if form.is_valid(): newpatient = form.save(commit=False) if form.cleaned_data['category'] == 'ANC': newpatient.is_anc = True if form.cleaned_data['category'] == 'INF': newpatient.is_inf = True if form.cleaned_data['category'] == 'GYNAC': newpatient.is_gynac = True newpatient.save() return redirect('allpatients') else: messages.add_message(request, messages.ERROR, 'Something went wrong!') return (request, 'main/addpatient.html', {'casepapernumber': casepapernumber, 'form':form}) except ValueError: messages.add_message(request, messages.ERROR, 'Please submit valid data') return (request, 'main/addpatient.html', {'casepapernumber': casepapernumber, 'form':form}) When there is valid data, new object is being created but I am getting attribute error. When form is not valid still getting error. I am struggling too much to validate form data. Traceback "POST /addpatient/? HTTP/1.1" 500 67207 Internal Server Error: /addpatient/ Traceback (most recent call last): File "C:\Users\Prashant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Prashant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\deprecation.py", line 96, in … -
django from does not save form and create pdf file
Can you explain please why my form do not show pdf file in DJANGO. There is my code: views.py class CountryCreateView(CountryViewMixin, core.FormModalView): form_class = CountryForm template_name = 'home/country.html' template_name_success = 'home/application_success.html' template_name_pdf = 'home/application_pdf.html' def get_file(self): template = render_to_string( template_name=self.template_name_pdf, context={ 'name': self.name, 'address': self.address, 'registration_number': self.registration_number, 'note': self.note, 'status': self.status, } ) # self.object = form.save() html = HTML(string=template) pdf_file = html.write_pdf() # object.file.save('1.pdf', self.get_file()) return File(BytesIO(pdf_file)) def form_valid(self, form): self.object = form.save() self.object.file.save('1.pdf', self.get_file()) return HttpResponseRedirect(self.get_success_url()) forms.py class CountryForm(core.ModelForm): class Meta: model = Country fields = ( 'name', 'address', 'registration_number', 'note', 'status',) I need to save from django field form fields to PDF.This code must to work. But I do not understand Why it doesn't working(((Please help -
Nested JSON output for Primary and Foreign key Django Rest Framework
Iam using Django 3.2 with Restframework. I have a Model as a for a Primary key named Tag and a Model connected as a foreign key named TagItem. I tried to get a nested JSON output for it but its not working as expected. Models.py class Tags(models.Model): tagId = models.CharField(primary_key=True, max_length=100,default=1) section = models.CharField(max_length=100) class TagItem(models.Model): tagId= models.ForeignKey(Tags, on_delete=models.CASCADE,default=1) select = models.BooleanField(default=False) name = models.CharField(max_length=50) views.py def get_tag_details(request): if request.method == 'GET': tag = Tags.objects.all() tagitem = TagItem.objects.all() TagSerializeobj = TagsSerializer(tag,many=True) TagItemSerializeobj = TagItemSerializer(tagitem, many=True) result = {} result['tag'] = TagSerializeobj.data for item in TagItemSerializeobj: if item.tagId == result['tag'].tagId: result['tagItem'] = item return Response(result) Error: 'ListSerializer' object is not iterable How to iterate of get items nested under related Tags only. Required output { "id": 1, "section": "crafts", "items": [ { "id": "10", "select": false, "name": "Wood" }, { "id": "11", "select": false, "name": "Clay" } ] }, { "id": 2, "section": "states", "items": [ { "id": "20", "select": false, "name": "Andhra Pradesh" }, { "id": "21", "select": false, "name": "Arunachal Pradesh" }, ] } -
TypeError : Object of type function is not JSON serializable
I have defined the following code in the views.py I am getting TypeError : Object of type function is not JSON serializable Libaries: from django.db.models.query import QuerySet from django.shortcuts import render from django.http import HttpResponse , Http404 , JsonResponse import json from json import JSONEncoder from FeedPost.models import trill def home(request, *args, **kwargs): return render(request, "feed.html", context={}, status=200) Where the error occured def trills_list_view(request, *args , **kwargs): qs = trill.objects.all() trills_list = [{"id": x.id, "name": x.name} for x in qs] data = { "response": trill_list } return JsonResponse(data) def trill_list(request, trill_id, *args, **kwargs): data = { "id" : trill_id, } status = 200 try: obj = trill.objects.get(id=trill_id) data['name'] =obj.name except: data['message'] = "Not found" status = 404 return JsonResponse(data, status=status) -
Checkbox button on a bootstrap modal inside django form
I currently have a form in my django app. Inside my form, there's a button to open a bootstrap modal for our 'terms & conditions'. and inside the modal, I have a checkbox that a user can click to unsubscribe from our service. And the submit button is located on the form itself, not on the modal (modal only has a single checkbox). Everything works perfectly fine except that Django doesn't seem to save the value of checkbox to our database. I wonder if I need to use AJAX or Jquery to make this happen? Any guidance will be greatly appreciated. HTML - Template <div class="modal fade" id="terms_conditions" tabindex="-1" role="dialog" aria-labelledby="termsLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="termsLabel">Terms and conditions</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="checkbox_subscription"> {% csrf_token %} {% for field in form.subsc %} {{ field.tag}} {% endfor %} <label>Please check this button to unsubscribe</label> </div> </div> </div> </div> </div> <div class="terms_and_conditions"> {% for field in form.t_c %} {{ field.tag}} {% endfor %} <label>Please accept <a href="#" data-toggle="modal" data-target="#terms_conditions">terms and conditions</a>.</label> </div> forms.py class ApplicationForm(forms.ModelForm): class Meta: model = Enquiry fields = ['name','other','t_c','subsc' ] t_c = forms.BooleanField() subsc … -
Django- how to display multiple images uploaded from admin in template?
I would like to upload multiple photos to the Django admin and display them in views.py. Here's what I have so far: models.py class Show(models.Model): title = models.CharField(max_length=1024) slug = models.SlugField(max_length=1024) class ShowPhoto(models.Model): show = models.ForeignKey( Show, on_delete=models.CASCADE, related_name="photos" ) photo = models.ImageField() forms.py from django import forms from django.core.validators import validate_image_file_extension from django.utils.translation import gettext as _ from .models import Show, ShowPhoto class ShowAdminForm(forms.ModelForm): class Meta: model = Show fields = ( "title", "slug", ) photos = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), label=_("Add photos"), required=False, ) def clean_photos(self): """Make sure only images can be uploaded.""" for upload in self.files.getlist("photos"): validate_image_file_extension(upload) def save_photos(self, show): """Process each uploaded image.""" for upload in self.files.getlist("photos"): photo = ShowPhoto(show=show, photo=upload) photo.save() admin.py from django.contrib import admin from django.template.loader import get_template from django.utils.translation import gettext as _ from .models import Show, ShowPhoto from .forms import ShowAdminForm class ShowPhotoInline(admin.TabularInline): model = ShowPhoto fields = ("showphoto_thumbnail",) readonly_fields = ("showphoto_thumbnail",) max_num = 0 def showphoto_thumbnail(self, instance): """A (pseudo)field that returns an image thumbnail for a show photo.""" tpl = get_template("shows/admin/show_thumbnail.html") return tpl.render({"photo": instance.photo}) showphoto_thumbnail.short_description = _("Thumbnail") How would I write a views.py method so that the multiple photos upload from the ShowPhoto model can be rendered in the template? -
Create two related objects with Django-Admin
With the project I am currently working on we have use the Django Group model along with a custom model (OtO relationship to Group) to extend the functionality of groups and we use the django-admin interface. # models.py class GroupExt(models.Model): group = models.OneToOneField(Group, primary_key=True) # admin.py class GroupExtInlineAdmin(admin.StackedInline): model = GroupExt fields = (...) class GroupAdmin(admin.ModelAdmin): inlines = (GroupExtInlineAdmin,) admin.register(Group, GroupAdmin) So, when a user logs in to the admin interface and goes to create a new group they are taken to a page that has the form for the normal group fields such as name and permissions, but also has the form for the GroupExt model that should go along with the group. Currently, when a new group is created only the Group model is being created. If you go and edit the group you just created and fill out the GroupExt inline form, it will then create the GroupExt model. How would we make it save the GroupExt model when first creating the group? -
Django Forms vs HTML - name value for buttons / working with dynamic data
Trying to wrap my head around Django forms. Appreciate they offer built-in cleaning and checking of data. My issue is: I am pulling multiple rows from a database I want the User to be able to update the value of a particular row I can assign a row-related, unique value to the radio buttons in html 3a) For example {{ % for key, value in tempDict.items %}} {{ i.id }} {{ i.status }} ... and so on 3b) Then I can quite easily assign a unique value for any radio buttons I may have in the html type="radio" name={{ i.id }} How do I achieve the same as (3b) with Django forms? Here is the context I am supplying the html form for reference. In a nutshell I have two tables, one for students (first name, last name, active status) and one for their attendance, which references the pk/id of the student table as a ForeignKey. What I am trying to achieve below is activeStudents = filtering the student table to only give me active students. This will form the basis of my "attendance" report. todayAttendance = filtering attendance table to that day's attendance only. Then I check to see … -
Making of a customer report based on sales
I am trying to make a customer wise sales report, in it there will customers listed with their total number of sales, total amount, total paid and balance of sales occurred in the selected time period. models: class Customer(models.Model): name = models.CharField(max_length=128) phone = models.CharField(max_length=128) email = models.EmailField(blank=True, null=True) address = models.TextField() is_deleted = models.BooleanField(default=False) ... class Sale(models.Model): auto_id = models.PositiveIntegerField() sale_id = models.CharField(max_length=128, blank=True, null=True) sale_date = models.DateTimeField() customer = models.ForeignKey('customers.Customer', limit_choices_to={'is_deleted': False}, on_delete=models.CASCADE) customer_address = models.TextField(blank=True, null=True) sale_category = models.CharField(max_length=128, choices=SALE_CATEGORY, default="intra_state") subtotal = models.DecimalField(default=0.0, decimal_places=2, max_digits=15, validators=[MinValueValidator(Decimal('0.00'))]) round_off = models.DecimalField(decimal_places=3, default=0.00, max_digits=30) total = models.DecimalField(default=0.0, decimal_places=2, max_digits=15, validators=[MinValueValidator(Decimal('0.00'))]) paid = models.DecimalField(default=0.0, decimal_places=2, max_digits=15, validators=[MinValueValidator(Decimal('0.00'))]) balance = models.DecimalField(decimal_places=2, default=0.00, max_digits=15) is_deleted = models.BooleanField(default=False) ... What I tried is passing customers with sales occurred in the time period and using a template tag getting the sale values of each customer in template views: def customer_sales_report(request): from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') filter_form = { 'from_date': from_date, 'to_date': to_date, } from_date = datetime.datetime.strptime(from_date, '%d/%m/%Y') to_date = datetime.datetime.strptime(to_date, '%d/%m/%Y') sales = Sale.objects.filter(sale_date__date__range=[from_date, to_date], is_deleted=False) customer_pks = list(sales.values_list('customer_id', flat=True)) customers = Customer.objects.filter(pk__in=customer_pks, is_deleted=False) filter_string = f"{filter_form['from_date']},{filter_form['to_date']}" context = { 'customers': customers, 'filter_form': filter_form, 'filter_string': filter_string, "title": 'Customer sales report', } return render(request, … -
Is it necessary to use serializes in Django rest framework?
Is it necessary to use serializers in Django rest? I'm building a project where I came across a scenario where fields in forms add dynamically and then I need to validated and save data into DB. Since fields in forms dynamic, How can we handle this in serializer? Can we do validations and saving without using serializes? -
Hi, I am using django rest framework I have a json data and i want to post this data using ajax and display this data using ajax
Please help me how i submit my html form using ajax and dispaly my blogs in my html form.I am using django rest framework please help me how i submit my request using ajax and dispaly my blog data using ajax Please help me how i submit my html form using ajax and dispaly my blogs in my html form.I am using django rest framework please help me how i submit my request using ajax and dispaly my blog data using ajax Please help me how i submit my html form using ajax and dispaly my blogs in my html form.I am using django rest framework please help me how i submit my request using ajax and dispaly my blog data using ajax MY views.py file: @api_view(['GET', 'POST']) # @parser_classes([MultiPartParser, FormParser]) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def add_blog(request, format=None): if request.method == 'POST': serializer = AddBlogSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): blog = serializer.save() blogdata = {'title':blog.title, 'author':blog.author, 'description':blog.description, 'image':blog.image.url, 'time':blog.time, 'date':blog.date} data = {'result': 'success', 'message':'Blog post added successfully', 'blogdata': blogdata} return Response(data=data, status=201) elif not serializer.is_valid(): serializererrors = serializer.errors data = { 'result': 'error', 'message':serializererrors} return Response(data=data) if request.user.id and request.method == 'GET': return render(request, 'blog.html') @api_view(['GET', 'POST']) # … -
django-bootstrap5 TemplatesSyntaxError
I am trying to utilize django-bootstrap 5 for my form, after creating the form and everything i rendered my template and here is it. {% extends "base.html" %} {% load bootstrap5 %} {% block content %} <div class="container"> <h1>Log In</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">login</button> {% endbuttons %} {% endblock bootsrap_form %} </form> </div> {% endblock content %} urls.py path('login/',auth_views.LoginView.as_view(template_name='account/login.html'),name='login') But when I run the server I got a template syntax error telling me that its expecting an end block meanwhile I have an endblock already, here is the error: TemplateSyntaxError at /account/login/ Invalid block tag on line 8: 'bootsrap_form', expected 'endblock'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 3.2.4 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 8: 'bootsrap_form', expected 'endblock'. Did you forget to register or load this tag? and the code returned in the error interface looks like this: 1 {% extends "base.html" %} 2 {% load bootstrap5 %} 3 {% block content %} 4 <div class="container"> 5 <h1>Log In</h1> 6 <form method="POST"> 7 {% csrf_token %} 8 {% bootsrap_form form%} 9 <input … -
Not able to retrieve data values from Ajax GET call into Django view
I am trying to query the employee list based on parameter I send through ajax call inside data, but it giving me an error (i want it through GET req only ) Js ajax func $(document).ready(function () { $(".call_ajax").click(function () { $.ajax({ url: "/employee_list", type: "GET", contentType: "application/json", dataType: "json", data: { designation: "soft eng", }, headers: { "X-CSRFToken": csrftoken, Authorization: my_token, }, success: function (data) { console.log(data); }, error: function (xhr) { //Do Something to handle error console.log(xhr.error); }, }); }); my view @csrf_exempt @api_view(['GET', 'POST', 'PUT', 'DELETE']) @permission_classes([IsAuthenticated]) @authentication_classes([TokenAuthentication]) def employee_list(request): if request.method == 'GET': data_ = request.data['designation'] print(data_) employees = Employee.objects.all() students = Student.objects.all() user = MyUser.objects.all() serializer = EmployeeSerializer(employees, many=True) serialized_sudents = StudentSerializer(students, many=True) multi = { 'employees': serializer.data, 'students': serialized_sudents.data } # serializer2 = UserSerializer(user, many=True) return JsonResponse(multi, safe=False) error i am getting in browser GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error) error in Django log File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list data_ = request.data['designation'] KeyError: 'designation' -
How to create superuser for my django project on first migration?
I am creating super user with command python manage.py createsuperuser I would like to set an email, password and create a superuser while running my first migrations. What is the best way to achieve that? -
creating a new instance of todolist in every URL
I want to upgrade my todolist app so that users can create a link to their own todolist. for example, they can do 127.0.0.1/room/testroom and it'll take them to a todo list. Another use can do 127.0.0.1/room/testroom2 will take them to a new room with another instance of the todo list. I'm not sure how to implement this feature. I already have one app set up for the main todo app functionality. I'm in the progress of writing the ROOMS app which will let users create rooms. I don't know how to mix both models from different apps, or should I put them all in the same app? -
Getting self.pk from DetailView for lte/gte comparison (Django)
Goal: Implement next article / previous article feature on article page which is being served via DetailView. Compare current article pk against queryset in order to grab the next and previous articles. I've tried a lot of different methods so far, but I'm getting errors on all of them. ''' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) pk = Post.objects.filter(pk=self.kwargs.get('pk') ''' I've also tried: pk = self.kwargs.get('pk') and pk = self.kwargs['pk'] I get KeyError on the dictionary attempt and None on the get attempts. I can't figure out why I'm not able to return the pk for the article in order to finish the code. Also, I've tried to get other data from the Post model, with the same errors. -
How to host 2 Django Application using gunicorn & nginx in Production
Hello I want to host 2 djagno websites using Gunicorn and Nginx and I don't know how to do this this is my first time to host 2 django websites in one server and 2 domain so please tell me how to host 2 django website. Here is my 1 file located /var/www/site1 and here is my 2 file /var/www/site2 -
Django Social Auth Update First And Last Name in Django App Permanently
I am using django-social-auth to simplify the coded needed to use Auth0 to authenticate for the django application. I want to give my users the functionality to update their first and last names within the django application and have set up an edit profile form to do so. However, after changing their first and last name, once a user logs out and logs back in, their name is re-written so that their first name is their email and they have no last name. I have already tested to make sure the form is working properly (both from the app front end and the database). Is there something I need to configure to prevent social-auth from re-setting the user's name each time they log in? -
Configuring Scrapyd + Django on Docker to use django models
I have this project with scrapy, scrapyd and django. My crawler uses the django models to add the items to the database through the pipelines. What i did was use a single container to start the scrapyd and the django server, but this give the problem that the scrapyd can't find the spiders even if they exist docker-compose.yaml version: "3" services: api: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "cd pokemon_crawler && scrapyd & python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=pokedex - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: "postgres:10-alpine" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword - POSTGRES_DB=pokedex My crawler view to run the crawler from rest_framework.views import APIView from rest_framework import authentication, permissions from rest_framework.response import Response from scrapyd_api import ScrapydAPI class CrawlerView(APIView): scrapyd = ScrapydAPI("http://localhost:6800") authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAdminUser] def post(self, request, format=None): pokemons = request.POST.getlist("pokemons", None) if not pokemons or not isinstance(pokemons, list): return Response({"error": "Missing args"}) pokemons = ["+"] if "all" in pokemons else pokemons settings = { "USER_AGENT": "Mozilla/5.0 (compatible; Googlebot/2.1; " "+http://www.google.com/bot.html)", } # Here we schedule a new crawling task from scrapyd. # This returns … -
Button must have a tooltip in one of template, but not in the others
I include the button for different templates (and different divs). There should be a tooltip in one of these divs, but not in the others. How can I do this? I think I can check the div class in the button (something like {% if div_class=="..."%}), but I do not know how to do this. Is it possible? Maybe I need to check the template name or something else? first.html <div class="single-card__favorite"> {% include 'button.html' %} </div> second.html <div class="card__footer"> {% include 'button.html' %} </div> button.html {% load user_filters %} {% if author|isfavorite:user %}> <button class="button button_style_none" name="favorites"> <span class="icon-favorite icon-favorite_active"></span> </button> <div class="single-card__favorite-tooltip tooltip">Delete from favorites</div> {% else %} <button class="button button_style_none" name="favorites" data-out> <span class="icon-favorite"></span> </button> <div class="single-card__favorite-tooltip tooltip">Add to favorites</div> {% endif %} -
Django fails at properly redirecting from one view to another
I have a search bar on the side of the webpages of the app i'm working on, what i'm trying to do is have my search view take in the user's query, compare it with a list of entries and if what the user typed in matches the title of any of the entries available, search should redirect to another view called title which handles rendering the html file of the entry the user searched for along with matching it with the approparitate URL (i.e if the user searches for the Django entry, title renders HTML file of said entry and assigns it the URL "example.com/Django") The problem lies in the fact that every time i redirect from search to title, title renders the html file reserved for the case in which no entry matches what the user searched for, no matter whether the entry is available or not. It should also be noted that the path for the search view is a mess. if i write the path like that path("<str:search>", views.search, name="search" i get a NoReverseMatch error saying that django was expecting an argument but recieved none, but path("search", views.search, name=search causes the rendered error page to have … -
Do I need to create react app for every Django app?
I am following this tutorial. https://www.youtube.com/watch?v=6c2NqDyxppU I'm just confused if I have couple of django apps, do I need to create a react app for each or just one react app (in the video's case named frontend)? -
Rendering part of a form conditionally
I have a form where I need to only take address input if "new-address" is selected. I've been trying to only include this form if the correct radio button is checked, but I'm having trouble getting it to work. If I don't escape the braces, the js breaks, but if I do, it renders the addressform as {% include 'partials/form_fields.html' %} and not as the actual form template. I'm open to django based solutions, but this logic needs to be done without refresh. js var addresslist = document.getElementById("address-list"); var addressform = "\{% include 'partials/form_fields.html' %\}" addresslist.addEventListener("change", function () { var address = document.querySelector('input[name="addresses"]:checked').value if (address == "new-address") { console.log(address) document.getElementById('address-form').innerHTML = addressform; } else { console.log(address) document.getElementById('address-form').innerHTML = ""; } }); form <form method="POST" id="subscription-form" data-secret="{{client_secret}}"> {% csrf_token %} <label class="block uppercase text-gray-600 text-xs font-bold mb-2">Payment Details</label> <div class="form-check my-3 bg-gray-200 p-2 rounded-md"> <input class="form-check-input" type="radio" name="payment-methods" id="add-new-card" value="add-new-card" onclick="addCard()"> <label class="form-check-label" for="add-new-card"> Add new payment method </label> <div id="new-card" style="display: none;"> <label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name"> Name on Card </label> <input id="cardholder-name" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150" value="{{customer.name}}" detype="text"> <!-- placeholder for Elements --> <label class="block …