Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load data without using a form
I am a student learning Django. I've been loading data using form so far, but I'd like to know how to load data when I press the button without using form. Is there something wrong with my code? model.py class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.join_code) class Meta: ordering = ['join_code'] Join/views from datetime import timezone from django.shortcuts import render Create your views here. from zeronine.models import * def join_detail(request): product = Product.objects.all() if request.method == "POST": join = Join() join.product_code = product join.username = request.user join.part_date = timezone.now() join.save() return render(request, 'zeronine/detail.html', {'product': product}) detail.html {% extends 'base.html' %} {% block title %} 상품 상세보기 {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-4"> <img src="{{product.image.url}}" width="190%" style="margin-top: 35px;"> </div> <div class="text-center col" style="margin-top:150px; margin-left:200px;"> <b><h4 class="content" style="margin-bottom: -5px;"><b>{{product.name}}</b></h4></b> <br> <div> <!-- <span>주최자 : <b>{{ product.username }}</b></span><br>--> <span style="color: #111111">모집기간 : <b>{{ product.start_date }} ~ {{ product.due_date }}</b></span> </div> <hr style="margin-top: 30px; margin-bottom: 30px;"> <p><span class="badge badge-dark">가격</span> {% load humanize %} {% for designated in designated_object %} {% if designated.product_code.product_code == product.product_code %} {{designated.price | floatformat:'0' | intcomma }}원 {% … -
Page or Form Not showing validation Error Django
Hello Guys I'm trying to show validation errors on Django forms. I do not know what's going on. I want to make a validation error if the username already exists in the database, but it ain't throwing me an error. Here is My code. In terminal its show the error but not in the page. Forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.forms import fields from django.forms.widgets import PasswordInput User = get_user_model() unallowed_username = ['hello'] class LoginForm(forms.ModelForm): username= forms.CharField() password = forms.CharField( widget=PasswordInput( attrs={ "class": "login-password form-control", "id": "login-password" } ) ) class RegisterForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField() username = forms.CharField() password1 = forms.CharField( label="Password", widget=forms.PasswordInput( attrs = { "class": "form-control user-password1", "id": "user-password" } ) ) password2 = forms.CharField( label="Confirm Password", widget=forms.PasswordInput( attrs = { "class": "form-control user-password2", "id": "user-confirm-password" } ) ) class Meta: model = User fields = ["first_name", "last_name","username", "email", "password1","password2"] def clean_username(self): username = self.cleaned_data["username"] qs = User.objects.filter(username__iexact = username) if username in unallowed_username: raise forms.ValidationError("This username is unproper Username Please pick another") if qs.exists(): print("invalid username") raise forms.ValidationError(("This is an Invalid Username Please pick another")) return username def clean_email(self): email = self.cleaned_data["email"] … -
How do I run some code when a user signs up with python-social-auth in Django?
I'm using Django and python-social-auth and when a user signs up I want to call the API of another service to add the user to it (think something like Mailchimp). What's the correct way of doing it? My app has a backend which is API only written in Python and Django, and a frontend written in JavaScript. For the purpose of signing up/in though, there's a link to the backend (api.example.com/social-auth/...) so it ends up being a bit of a hybrid. After logging in or out, the backend redirects the user back to the frontend, by having this in settings.py: LOGIN_REDIRECT_URL = env("FRONTEND_URL") LOGOUT_REDIRECT_URL = env("FRONTEND_URL") If there's any of my code that's relevant to this question, please let me know and I'll add it. I'm not sure what parts are and I didn't want to do a big dump of all my code. Also, I don't think my code around this issue is particularly good, so I'm happy to change it. -
I trial make Permission in CreateView
I want to check if user in true editUser before open url and create post, urls.py", line 13, in path('new/', PostCreateView.as_view(), name='new_post'), AttributeError: 'NoneType' object has no attribute 'as_view' def notLoggedUsers(view_func): def wrapper_func(request,*args,**kwargs): if not request.user.profile.editUser: return redirect('index') else: return view_func(request,*args,**kwargs) return wrapper_func @notLoggedUsers class PostCreateView(LoginRequiredMixin, CreateView): model = Post template_name = 'crud/new_post.html' form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Send emails with django send_mass_mail
I am trying to send two different emails using the django send_mass_mail function. I'm very new to django, and I'm struggling to get it to work. The send-Mail function works fine when I use it, but I want to send different emails to the customer and the site owner when a purchase is made. Any help with this would be amazing! Thanks so much! def _send_confirmation_email(self, order): """ Send the user a confirmation email """ cust_email = order.email subject = render_to_string( 'checkout/confirmation_emails/confirmation_email_subject.txt', {'order': order}) body = render_to_string( 'checkout/confirmation_emails/confirmation_email_body.txt', {'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL}) subject2 = render_to_string('Order Placed', {'order':order}) body2 = render_to_string( 'An order has been placed', {'order': order} ) message1 = ( subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email] ) message2 = ( subject2, body2, settings.DEFAULT_FROM_EMAIL, ['test@hotmail.com'] ) send_mass_mail((message1, message2), fail_silently=False) -
how to change my flask app to django app?
I want to change my flask web to django app. from flask import Flask app = Flask(__name__) @app.route('/login', methods = ['POST']) def login(): try: data = request.json usernameval = data['userName'] passwordval = data['password'] response = {'username': usernameVal, 'password':passwordval} except Exception as error: response = {'error': 'Try again'} finally: return response if __name__ == '__main__': app.run(host="0.0.0.0",port=8080) I am using postman to sending request to this route abd want to do the same with django app. What is the django version of this code ? -
Assign username to field in models.py table
Let’s say I have a Table1 that contains 5 data, > class Table1(models.Model): > code = models.CharField(max_length=16,unique=True) > > author_Up = models.CharField(max_length=16,default=User) > date_Up = models.DateTimeField(auto_now=True) > post_date = models.DateTimeField(default=timezone.now) > author = models.ForeignKey(User,on_delete=models.CASCADE) > def __str__(self): > return self.code I am using formes.py as: class Table1_F(forms.ModelForm): code = forms.CharField(label='Code',max_length=16) class Meta: model= Table1 fields=['code'] The Problem is I need to assign a new values of (author_Up) and (date_Up) every time that another user make an update and keep the initial author. How do I solve this Please? -
updating the master records with detail records as per posting
I lost and do not know where to start and end. please light on this tunnel. I am having transaction model with data as follows: Acctcode acctname debit credit 1101 stationary exp 100.00 1101 stationary exp 245.00 I am having Account master model: code detail reportingacct Acct Level 1000 expenses 0 1 1100 office expenses 1000 2 1101 stationary exp 1100 3 I need data for context as: code name balance AcctLevel 1000 expenses 345.00 1 (posting from level 2) 1100 office exp 345.00 2 (posting from level 3 sum) 1101 stationary exp 345.00 3 (sum of two transaction) I tried with view as follows: acctbalance = FinTransDetail.objects.values("fd_acct__AcctCode", 'fd_acct__AcctName','fd_acct__AcctLevel','fd_acct__AcctReport1').order_by( 'fd_acct__AcctCode').annotate(balance=Sum('fd_debit')-Sum('fd_credit')) print (acctbalance) sample data with real value: ***<QuerySet [{'fd_acct__AcctCode': Decimal('1101'), 'fd_acct__AcctName': 'OFFICE BUILDINGS', 'fd_acct__AcctLevel': Decimal('3'), 'fd_acct__AcctReport1': '1100', 'balance': Decimal( '112')}, {'fd_acct__AcctCode':....."**** for data in acctbalance: print(data['balance']) sample data with real value: ***112 -2786 302 -500 100 230 2254 400 **** my models: class AccountMaster(models.Model): """Model representing a book (but not a specific copy of a book).""" AcctLevel = models.DecimalField(max_digits=1, decimal_places=0, default=1) AcctCode =models.DecimalField( decimal_places=0, max_digits=6,unique = True) AcctName = models.CharField(max_length=50) AcctDesc = models.CharField(max_length=100) AcctType = models.CharField(max_length=20,choices=ACCTTYPE_CHOICES,null=True, blank=True) AcctReport1 = models.CharField(max_length=20, null=True, blank=True, default=0) AcctReport2 = models.DecimalField(max_digits=6, decimal_places=0, default=0, blank=True) AcctPosting … -
Book object is not iterable: Trying to display similar objects of an instance based on a field
I am working on a library project that displays books and each both is in a category(history, math, adventure, etc). On the detailed view of a book, I want a link (with "See similar books in this category") that will redirect the user to other books of the same category of the current book. So if the detail page of a book has a category of "history", the link will direct to other books in the "history" category. The redirection is to another template (Addon: In helping me out, I would love to display the "similar books" in the same page, not a different page) error details TypeError at /search/similar/bootsrtap/ 'Book' object is not iterable models.py class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') choices = Category.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255) category = models.CharField(max_length=255, choices=choice_list) slug = models.SlugField(max_length=100, unique=True) def __str__(self): return self.author + ": " + self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def similar_book(self): return Book.objects.filter(category=self.category) urls.py urlpatterns = [ path('detail/<slug:slug>/', BookDetail.as_view(), name='detail'), path('search/similar/<slug:slug>/', views.search_similar_results, name='search_similar_results'), views.py … -
How to put this button next to my form field and not two lines below?
Im trying to learn django so Im making a website, but I dont know much of Html, css, or js. so I used a wesite builder to make a template, and Im just editing the codes it gave me. This is the scenario Im trying to fix: Link to Problematic part's picture I want the yellow button to be next to the form field but I cant figure out how to get it there this is the corresponding part from my html file: <div class="u-align-left u-container-style u-layout-cell u-right-cell u-shape-rectangle u-size-30 u-size-xs-60 u-layout-cell-2" src=""> <div class="u-container-layout u-container-layout-5" src=""> <h2 class="u-align-center u-custom-font u-text u-text-default u-text-6">Add</h2> <p class="u-align-left u-custom-font u-heading-font u-text u-text-2"> <form method='POST' class='post-form'> {% csrf_token %} {{ forms.newcat.non_field_errors }} <div class="fieldWrapper"> {{ forms.newcat.name.errors }} <label for="{{ forms.newcat.name.id_for_label }}">New Category Name </label> {{ forms.newcat.name }} </div> <button type='submit' name='addcategory' class="u-btn u-btn-round u-button-style u-hover-palette-3-light-2 u-palette-3-light-1 u-radius-50 u-btn-1">Add</button> </form> </p> ps. I figured the issue is in the html parts, but if needed I can provide the css file too. Thanks in advance for the help! -
Build a proxy in Django that can handle concurrent requests
I'm looking to build a small proxy for myself in Django. The issue I have is that if I query one endpoint two times in parallel, it waits for one request to finish before serving the other one. I feel like this is not optimised because most of the time is spent waiting for the network to download the page. For my two requests this should be done in parralel, just like a lib like Scrapy would do. Do you have any insights on how to do this or am I missing something? Thanks! -
Display a chart of last 30 days-django
I am working on customer requests project where I want to visualize the requests submitted in the last 30 days on chart. This will sum up daily requests for the last 30 days. below is the code I have but the result is an empty chart: def daterange(date1, date2): for n in range(int ((date2 - date1).days)+1): yield date1 + timedelta(n) def summarychat(request): current_date = date.today() days_before = date.today()-timedelta(days=30) for dt in daterange(days_before,current_date): print(dt.strftime("%Y-%m-%d")) dates = Customer_Requests.objects.filter(arrival_date=dt) date_data = list() category = list() for i in dates: i =Customer_Requests.objects.values('arrival_date').annotate(re_number=Count('request_name')).order_by('arrival_date') date_data.append(int(i['re_number'])) category.append(i['arrival_date']) resolved_series = { 'name': 'Daily', 'data': date_data, 'color': 'green' } chart3 = { 'chart': {'type': 'column'}, 'title': {'text': 'Statistics'}, 'xAxis': {'date_data': date_data}, 'series': [resolved_series] } dump3 = json.dumps(chart3) return render(request,'summarized.html',{'chart3': dump3}) I want to transform this SQL query in python: SELECT count(request_name) from Customer_Requests where date between date1 and date2; here date1 is today's date and date2 is today'date-30 days Please assist on this. -
Django TestCase works with Sqlite3 - doesn't work with Postgres
I'm trying to figure out why my tests are working with Sqlite3 but don't work with Postgres. import os from django.conf import settings from django.test import TestCase from products.factory import ProductFactory from products.models import Product, Organisation from products.services.imports import ImportService from users.factory import UserFactory, OrganisationFactory from users.models import User class ProductTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: cls.org = OrganisationFactory.create(name='My organisation') cls.user = User.objects.create_user('peter','xxxxxxxx') cls.user.organisation = cls.org cls.product = ProductFactory.create(title='Title', created_by=cls.user, organisation=cls.org) def test_product_has_organisation(self) -> None: self.assertTrue(self.product.organisation, 'Product has no organisation') When running it with Postgres it raises: ERROR: test_product_has_organisation (products.tests.test_product.ProductTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/milano/PycharmProjects/.virtualenvs/markethelper_api/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.ForeignKeyViolation: insert or update on table "products_product" violates foreign key constraint "products_product_updated_by_id_33940c75_fk_users_user_id" DETAIL: Key (updated_by_id)=(19) is not present in table "users_user". The Product.updated_by: updated_by = CurrentUserField('users.User', on_delete=models.CASCADE, related_name='updated_products', null=True, blank=True, verbose_name='Updated by', on_update=True) Do you know where is the problem? -
Django-celery , "celery_file -A django_email_celery worker --loglevel=info" not working
I want use celery with RabbitMQ for email function for my Django - project , I Have installed celery and RabbitMQ. I hvae tried to Run this command but not working any of these. I am using Windows 10. enter image description here enter image description here enter image description here -
Django - Shared user database
I am having a project using a mother server gathering the data of a lot of small devices. The mother database is running Django,as well as the clients. The clients are mainly offline but go online to synchronize with the mother database from time to time. I would like to have a user management for my project. The idea is that all the changes of the users is happening on the mother database to avoid conflicts in the event both database are getting updated. I am not too sure about the approach to take. What are my different options and what would you recommend? -
Issue updating Django database
Hi everyone please I'm having difficulty updating data from the database base list. The editing page rendered but it doesn't show any input form. Hi everyone please I'm having difficulty updating data from the database base list. The editing page rendered but it doesn't show any input form. Views.py def edit_result(request, id): models = StudentResult result = Student.objects.get(id = id) return render (request,'studentportal/edit_result.html', {'result':result }) Models.py class Student(models.Model): userprofile = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE, related_name='myuser') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) profile_pic = models.ImageField(upload_to=student_image, verbose_name="ProfilePicture", blank=True) level = models.IntegerField() guardian_email = models.EmailField() guardian_phone = models.IntegerField() def __str__(self): return self.first_name def get_absolute_url(self): return reverse("studentportal:student_detail", kwargs={"pk": self.id}) class StudentResult(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='myresult') english = 'english' mathematic = 'mathematic' physic = 'physic' chemistry = 'chemistry' computer = 'computer' agric = 'agric' subject = [ (english, 'english'), (mathematic, 'mathematic'), (physic, 'physic'), (chemistry, 'chemistry'), (computer, 'computer'), (agric, 'agric'), ] subject = models.CharField(max_length=50, choices=subject) # subject = models.CharField(max_length=50) exam = models.IntegerField() test = models.IntegerField() total = models.IntegerField() def __str__(self): return self.subject Forms.py class StudentModelForm(forms.ModelForm): class Meta: model = Student fields = ('userprofile','first_name','last_name','profile_pic','level','guardian_email','guardian_phone') class ResultModelForm(forms.ModelForm): class Meta: model = StudentResult fields = ('student','subject','test','exam','total') -
how to get correct attribute for class Meta?
after running command python manage.py inspectdb, i am having following error TypeError: 'class Meta' got invalid attribute(s): ifsc,bank,branch,address,city,district,state my model is as following from django.db import models class Banks(models.Model): class Meta: db_table = 'banks' name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'branches' ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey('Banks', models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=250, blank=True, null=True) address= models.CharField(max_length=250, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) -
How to store picture password in database using Django framework?
when I click one of the picture of the image, how will it be stored in the database -
How to fetch data from another app Django
I'm creating a quiz project using Django with MongoEngine. Multiple Choice Questions and quiz are two separated apps. I want to fetch multiple choice in quiz based on m_id (unique number for each multiple choice). I'm a beginner and need a little help. How can i achieve thisMCQS Model from django_mongoengine import Document, EmbeddedDocument, fields class multichoice(Document): m_id = fields.IntField(min_value=1, verbose_name='MCQ Id') m_title = fields.StringField(primary_key=True, max_length=255, verbose_name='Title') m_question = fields.StringField(verbose_name='Question') m_alternatives = fields.ListField(fields.StringField(),verbose_name='Alternatives') def __str__(self): return self.m_title Quiz Model from django_mongoengine import Document, EmbeddedDocument, fields from mcqs.models import * class quiz(Document): q_id = fields.IntField(min_value=1, verbose_name='Quiz ID') q_title = fields.StringField(primary_key=True, max_length=255, verbose_name='Title') q_s_description = fields.StringField(max_length=255, verbose_name='Description') q_questions = fields.ListField(fields.IntField(), verbose_name='Question Numbers', blank=True) def __str__(self): return self.q_title MCQ Views def view_multichoice(request, m_id): get_md = multichoice.objects(m_question_number = m_id) return render(request, 'mcqs/mcq.html', {'get_md':get_md}) Quiz Views def view_quiz(request, q_id): get_q = quiz.objects(q_id = q_id) return render(request, 'quiz/quiz.html', {'get_q':get_q}) Current Result Expected Result -
django.db.utils.OperationalError: (1045, 'Plugin caching_sha2_password could not be loaded
I have a django app connecting to mysql. I also use nginx for srving static files. My django app can't connect to mysql that's inside docker. I use docker compose to connect these 3 containers. But when i run docker compose up command i get this error. I use python:3.9-slim-buster image for django app. I already tried chaning it to python:3.9 but nothing has changed. Docker compose file version: '3.8' services: django: build: . volumes: - static:/static - media:/media ports: - 8000:8000 networks: - database environment: DB_HOST: db depends_on: - db nginx: build: ./nginx ports: - 80:80 volumes: - static:/static depends_on: - django db: image: mysql:8.0.25 command: '--default-authentication-plugin=mysql_native_password' restart: always ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: ecommerce networks: - database volumes: - db:/var/lib/mysql volumes: static: media: db: networks: database: Error: Traceback (most recent call last): django_1 | File "/app/manage.py", line 22, in <module> django_1 | main() django_1 | File "/app/manage.py", line 18, in main django_1 | execute_from_command_line(sys.argv) django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line django_1 | utility.execute() django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute django_1 | self.fetch_command(subcommand).run_from_argv(self.argv) django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv django_1 | self.execute(*args, **cmd_options) django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute … -
Possible reasons for Django Channels intermittently functioning
I am attempting to use Django Channels on my digital ocean ubuntu 18 droplet to serve a 'video' feed from a webcam attached to a raspberry pi. The raspberry pi is using python websockets-client and openCV to send jpeg images quickly (every 0.05 seconds). The issue is that this will work great, streaming for 10+ minutes perfectly, and I will think I have got it working. Then the next day, it will stream for about 10 seconds before the raspberry pi disconnects from the websocket from what appears to be my server disconnecting it, and then I cannot get it to stream longer than a few seconds. Why would it work perfectly one day, and not the next? Nothing obvious has changed. The reason I think it is my server/channels/redis causing the problem: Before the raspberry pi even seems to be having any trouble, the video feed being shown on the browser will become very laggy then will stop getting new images entirely. Then a few seconds later my raspberry pi socket will disconnect from the websocket. What I have Tried: I have done a speed test on my internet connection and it is 50mb down/15mb up. I have tried … -
Field 'id' expected a number but got 'hellooo' - Django Blog Comments
I'm trying to make it possible to add comments on my blog, but I'm getting the following error when I try to submit the comment: "Field 'id' expected a number but got 'hellooo'." Views.py: class AddComment(generic.CreateView): model = Comment form_class = AddComment template_name = 'add_comment.html' def form_valid(self, form): form.instance.post_id = self.kwargs['slug'] return super().form_valid(form) success_url = reverse_lazy('blog') forms.py: class AddComment(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') widgets = { 'Name': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } models.py: class Comment(models.Model): post = models.ForeignKey(Post, on_delete= models.CASCADE, related_name='comments') name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) urls.py: from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='blog'), path('add_post/', views.AddPost.as_view(), name='add_post'), path('edit_post/<slug:slug>/', views.EditPost.as_view(), name='edit_post'), path('delete_post/<slug:slug>/', views.DeletePost.as_view(), name='delete_post'), path('<slug:slug>/comment/', views.AddComment.as_view(), name='add_comment'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] -
Django: Get first row from related table and show with main table query
The image table contains multiple images of a product. I want to bring an image column to match the product ID in the query set of the product table, which is the first image of the related product ID in the image table. Model: class Product(models.Model): product_code = models.CharField(max_length=50, unique=True) product = models.CharField(max_length=100, unique=True) class Image(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='images') Raw SQL: select p.*, i.image from accpack_product p join (select product_id, image from accpack_image group by product_id order by id) i on p.id=i.product_id order by p.id -
Django app import models form another file not working
Hi I am having a problem with importing a model form another app file that I have in the same project. -DND_website -data -__init__.py -models.py -main -views.py the code: from DND_website.data.models import PagesData error: ModuleNotFoundError: No module named 'DND_website.data' -
Jquery append method returning html tags instead of the proper formats
The feature is for a quiz and im retrieving the data for the quiz that is the questions and answers and appending it to my div having id test_box. The data has been successfully retrieved but instead of proper formatting the data, it is returning me in form of html tags. Here is my code snippet: const url = window.location.href const testBox = document.getElementById('test_box') $.ajax({ type: 'GET', url: `${url}/data`, success: function(response){ const data = response.data data.forEach(element => { for (const [question, answers] of Object.entries(element)){ testBox.append(` <div class="question_box"> <div> <b>${question}</b> </div> `); answers.forEach(answer => { testBox.append(` <div> <input type="radio" class="ans" id=${question}-${answer}" name="${question}" value="${answer}"> <label for="${question}">${answer}</label> </div> `) }) testBox.append(`</div>`); } }); }, error: function(error){ console.log(error) } });