Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django send_mail not working while smtplib works
I have a setup where I am using "send_mail" to send emails to the users using a gmail account. For some reason this function returns "smtplib.SMTPServerDisconnected: Connection unexpectedly closed". I am using a gmail account with 2 factor security enabled and an app password. If I just build a script using smtplib, it works. I am not sure how exactly to debug this issue. Code snippets below: settings.py ... EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = "myemail@costumgmail.com" EMAIL_HOST_PASSWORD = "mypass" EMAIL_PORT = 587 EMAIL_USE_TLS = True ... djangotest.py from django.core.mail import send_mail send_mail('Django mail', 'This e-mail was sent with Django.', "myemail@costumgmail.com" , ['some.other@mail.com'], fail_silently=False) # smtplib.SMTPServerDisconnected: Connection unexpectedly closed smtplibtest.py from email.message import EmailMessage import smtplib email_sender = "myemail@costumgmail.com" email_password="mypass" email_reciever ='some.other@mail.com' subject = "test" body = "test" em = EmailMessage() em['sender'] = email_sender em['to'] = email_reciever em['subject'] = subject em.set_content(body) smtpObj = smtplib.SMTP('smtp-relay.gmail.com', 587) smtpObj.ehlo() # (250, b'smtp-relay.gmail.com at your service, [188.26.233.149]\nSIZE 157286400\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') smtpObj.starttls() # (220, b'2.0.0 Ready to start TLS') smtpObj.login(email_sender, email_password) # (235, b'2.7.0 Accepted') smtpObj.sendmail(email_sender, email_reciever, em.as_string()) # OK traceback from django: Traceback (most recent call last): File "<console>", line 1, in <module> File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return … -
how to show same value of foreign field in admin panel- field name is that prize
when i generate a voucher code in class name unique code i need to know how can i show same value of prize field in draw as per unique code value Here we can see the[ this is the voucher code admin panel this is the draw adminpanel Now I need the same value of prize as the draw as per the unique code, Here we can see in the image there should be justdo or 10% instead of nothing or sorry models.py import logging import secrets from django.db import models from django.db.models.signals import post_save Get an instance of a logger logger = logging.getLogger(__name__) class Draw(models.Model): """ Class to represent each valid draw that happened in the system. """ email = models.EmailField() code = models.CharField(max_length=8) sent = models.BooleanField(default=False) rotation = models.IntegerField(default=0) date = models.DateTimeField(blank=True, null=True) prize = models.ForeignKey('Prize', on_delete=models.CASCADE, null=False, blank=False) retry_used = models.BooleanField(default=False) @classmethod def post_create(cls, sender, instance, created, *args, **kwargs): """ Connected to the post_save signal of the UniqueCodes model. This is used to set the code once we have created the db instance and have access to the primary key (ID Field). """ # If new database record if created: # We have the primary key (ID … -
Newbie Question: How can I automaticaly create a model instance in Django?
Hi Im pretty new to all this so sorry if I don't explain this very well. I want to create a model where I can make some football projections so far I have: class Team(models.Model): name = models.CharField(max_length=20) name_short= models.CharField(max_length=3) def __str__(self): return self.name_short class Projection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="projection", null=True) title= models.CharField(max_length=20, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('projection-detail', kwargs={'pk': self.pk}) class TeamProjection(models.Model): title = models.ForeignKey(Projection, on_delete=models.CASCADE) team = models.OneToOneField(Team, on_delete=models.CASCADE) total_plays = models.IntegerField(null=True, blank=True) What Im trying to do is when you create a new Projection it will auto create an instance of Team Projection for each team in Team Model. So it would be something like: Projection 1 Arizona 1050 Projection 1 Atlanta 1020 and so on? -
How can I fill the Django forms field in view?
In my Django forms I have 5 fields but I will take 4 of them from the html template. The 5. one will be filled in the views. When I try to do like this it says form is not valid. How can I fill the data in views? forms.py class ProductForm(forms.ModelForm): class Meta: model = ProductModel fields = ('category','brand','series','model','asin') productform.html <form id="firstform" action="{% url 'productpage' %}" method="POST"> {% csrf_token %} <input type="text" id="category" name="category" placeholder="Category"> <input type="text" id="brand" name="brand" placeholder="Brand"> <input type="text" id="series" name="series" placeholder="Series"> <input type="text" id="model" name="model" placeholder="Model"> <input type="submit" id="save-button" name="save-button" value="Save" > </form> views.py def productpage(request): if request.POST.get('save-button'): form = ProductForm() if request.method == 'POST': form = ProductForm(data=request.POST) print("a") if form.is_valid(): print("i") form.cleaned_data["asin"] = "B324235252" form.save() HttpResponse("KAYDEDİLDİ") else: print("iiii") HttpResponse("Form is not valid") else: form = ProductForm() return render(request,"first_app/productform.html") -
django db not show to the html views
I normally configure as I think, the view, the url and the models but I still don't understand why nothing is displayed on the template, this is my problem currently help me solve this problem from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView from .models import Poster, CategoriePost class Posterlist (ListView): queryset = Poster.objects.all() template_name = 'blog.html' from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from django.utils.text import slugify from ckeditor.fields import RichTextField class CategoriePost(models.Model): Nom_de_la_categorie = models.CharField(max_length=250) def __str__(self): return self.Nom_de_la_categorie class Meta: verbose_name = ("CategoriePost") verbose_name_plural =("CategoriePosts") STATUS = ( (0,"Brouillon"), (1,"Publier") ) class Poster(models.Model): categorie = models.ForeignKey(CategoriePost, on_delete=models.CASCADE, related_name='blog_categorie') titre = models.CharField(max_length=300, unique=True) slug = models.SlugField(max_length=300, unique=True) auteur = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') contenue = RichTextField(blank=True, null=True, config_name='default') status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='media/', height_field=None, width_field=None, max_length=100,) date_publication = models.DateTimeField(default=timezone.now) date_creation = models.DateTimeField(default=timezone.now) date_mise_a_jour = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Poster, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("blog:Post_detail", args=[self.slug]) class Meta: ordering = ('-date_publication',) verbose_name = ("Poster") verbose_name_plural =("Posters") def __str__(self): return self.titre {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class=" col-md-8 col-md-10 mx-auto"> <div class="site-heading"> <h3 class=" site-heading my-4 … -
Django - How to make admin not have own profile model
How to make the admin not have a profile created. I have a Profile, Relationships one to one model and want to exclude admin. -
My form field doesn't appears on my web app
I'm trying to make my first personal account web app and I have a trouble with it. I've created a bio model field in models and tryied get it in forms, but there is something is going wrong - this field doesn't want to display on web-site. The rest of the fields are working. Everything is fine at admin panel. Models: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField("email address", unique=True) bio = models.TextField("bio", max_length = 300, blank=True) Forms: class ChangeUserForm(UserChangeForm): password1 = forms.CharField( label=("Password"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) password2 = forms.CharField( label=("Password confirmation"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class':'input100','placeholder':'Username','name':'username'}) self.fields['email'].widget.attrs.update({'class':'input100','placeholder':'Email','name':'email'}) self.fields['password1'].widget.attrs.update({'class':'input100','placeholder':'Password','name':'password'}) self.fields['password2'].widget.attrs.update({'class':'input100','placeholder':'Repeat password','name':'password'}) class Meta: model = User fields = ['username', 'email', 'bio', 'password', 'password2'] widgets = { 'bio': TextInput(attrs={ 'class':'input100', 'placeholder':'Your bio', 'name':'bio' }), } Views: def edit_profile(request): form = CreateUserForm(initial={ 'username':request.user.username, 'email':request.user.email, 'bio':request.user.bio, }) if request.method == 'POST': form = ChangeUserForm(request.POST) if form.is_valid(): form.save() return redirect(home) else: return render(request, 'users/edit.html', {'form':form}) else: return render(request, 'users/edit.html', {'form':form,}) HTML: <div class="wrap-input100 m-b-16"> <div class="input100">{{ form.email }}</div> <span class="focus-input100"></span> </div> <div class="wrap-input100 m-b-16"> <div class="input100">{{ form.bio }}</div> <span class="focus-input100"></span> </div> There we can see that email field appears, whereas the … -
Django form invalid before rendering with a context processor
I have a slight issue with my form using Django. On my website I have a 'settings' box on every page (rendered with an 'include') in base.html - each settings box has a form which I am rendering with a 'context processor' however when rendering the form in the template nothing shows. Rendering with {{global_rebase_form.get_context}} I get the following message: {'form': <global_rebase_form bound=False, valid=False, fields=()>, 'fields': [], 'hidden_fields': [], 'errors': []} Suggesting it is invalid? My code is as follows Settings.py 'OPTIONS': { 'context_processors': [ 'apps.home.views.global_rebase_context', ... ], context processor: def global_rebase_context(request): form = global_rebase_form() return { 'global_rebase_form': form } template <form method="POST" name="time" id="rebase-form"> {% csrf_token %} {{global_rebase_form.as_p}} </form> form.py class global_rebase_form(forms.Form): class Meta: model = profile fields = ['location_rebase', 'time_rebase'] Any help would be greatly appreciated! -
Reverse and HttpResponseRedirect don't work with DefaultRouter
I need to send back response with product details, so I use HttpResponseRedirect and reverse. It requires the app_name:name, so I tried something like below, but I get error: django.urls.exceptions.NoReverseMatch: Reverse for 'product' not found. 'ProductViewSet' is not a valid view function or pattern name. This is my view: @api_view(['POST']) @permission_classes([IsAuthenticated]) def bump(request, pk): product = get_object_or_404(Product, id=pk) product.bumps.add(request.user) return HttpResponseRedirect(reverse('products:product', args=[pk])) This is my urls: app_name = 'products' router = DefaultRouter() router.register(r'', ProductViewSet) urlpatterns = [ path('', include(router.urls), name='product'), ] What is wrong in this code? I use the correct app_name and name. -
PostgreSQL local data not showing in Docker Container
I just want some help here, I'm kinda stuck here in Docker and can't find a way out. First, I'm using Windows for a Django APP and Docker I'm using PgAdmin4 with PostgreSQL 14 and created a new server for docker The log for the Postgres Image: 2022-07-16 19:39:23.655 UTC [1] LOG: starting PostgreSQL 14.4 (Debian 14.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2022-07-16 19:39:23.673 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2022-07-16 19:39:23.673 UTC [1] LOG: listening on IPv6 address "::", port 5432 2022-07-16 19:39:23.716 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2022-07-16 19:39:23.854 UTC [26] LOG: database system was shut down at 2022-07-16 16:50:47 UTC 2022-07-16 19:39:23.952 UTC [1] LOG: database system is ready to accept connections PostgreSQL Database directory appears to contain a database; Skipping initialization Log from my image: (you can see that doesn't have migrations) 0 static files copied to '/app/static', 9704 unmodified. Operations to perform: Apply all migrations: admin, auth, contenttypes, controle, sessions Running migrations: No migrations to apply. Performing system checks... System check identified no issues (0 silenced). July 16, 2022 - 16:40:38 Django version 4.0.6, using settings 'setup.settings' Starting development server at http://0.0.0.0:8000/ Quit … -
Django Error with Update view associted with model with foreign keys
I have a model, ProjectNoteComments, that is for adding comments on ProjectNotes. Comments are related to notes and notes are related to projects via foreign keys. The ProjectNoteComments are displayed via the ProjectNotesDetailView view. When I add a ProjectNoteCommentUpdateview and corresponding link to the note detail view page I get the following error: Reverse for 'project_note_comment_update' with arguments '(6, 9, 20)' not found. 1 pattern(s) tried: ['projects/note/(?P[0-9]+)/comment/comment:pk/update\Z'] I have not been able to figure out how to solve this issue. The views: class ProjectNotesDetailView(FormMixin, DetailView): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments form_class = NoteCommentForm crumbs = [...] def form_valid(self, form): projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk')) comment = form.save(commit=False) comment.projectnote = projectnote comment.created_by = self.request.user comment.save() return super().form_valid(form) def get_success_url(self): return reverse('company_project:project_note_detail', args=[self.kwargs.get('pk'), (self.object.id)]) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) class ProjectNoteCommentUpdateView(UpdateView): model = ProjectNoteComments template_name = 'company_accounts/update_project_note_comment.html' fields = ['body'] def get_success_url(self): return reverse('company_project:project_note_detail', args=[self.kwargs.get('pk'), (self.object.id)]) The URLs path('project/<int:project_pk>/note/<int:pk>/', ProjectNotesDetailView.as_view(), name='project_note_detail'), path('note/<int:pk>/comment/comment:pk/update', ProjectNoteCommentUpdateView.as_view(), name='project_note_comment_update'), The relevant template code link on Projectnotedetail page: <div class="header-edit-link col-sm"> {% if perms.company_project.can_change %} <div><a href="{% url 'company_project:project_note_comment_update' object.project.pk object.pk comment.pk %}"><i class="fa … -
Django/Postgres fulltext search - exclude if value contains <STRING>
Trying to use Postgres search in Django using SearchVector and I want to exclude results if contain a given string. Is it possible? Example from docs: Entry.objects.annotate(search=SearchVector('body_text', 'blog__tagline')).filter(search='Cheese') What if I want to exclude objects whose blog__tagline contains "queso"? I can't exclude objects with "queso" before annotation because I want to include them when a search is not performed. -
django webpack loader render_bundle error
We have a legacy Django-webpack app using Django webpack loader. The app code moved into a /app directory and the render_bundle stopped working. The error message is File "/usr/local/lib/python3.9/site-packages/webpack_loader/templatetags/webpack_loader.py", line 22, in render_bundle tags = utils.get_as_tags( File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 71, in get_as_tags bundle = _get_bundle(loader, bundle_name, extension) File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 47, in _get_bundle bundle = loader.get_bundle(bundle_name) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 116, in get_bundle filtered_chunks = self.filter_chunks(chunks) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in filter_chunks ignore = any(regex.match(chunk) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in <genexpr> ignore = any(regex.match(chunk) TypeError: expected string or bytes-like object webpack-stats.json {"status":"done","publicPath":"http://localhost:8001/","chunks":{"app":[{"name":"app.js","publicPath":"http://localhost:8001/app.js","path":"/app/static/dist/app.js"}]}} I hard-coded our STATICS_URL to try to match the documentation on django-webpack-loader DJANGO STATICS_URL: /app/static/dist/ WEBPACK PATH(output.path): /app/static/dist WEBPACK_LOADER: WEBPACK_LOADER = {"DEFAULT": {"CACHE": not DEBUG}} Code that triggers the error: {% render_bundle 'app' %} inside a index.html -
How to restrict website access? for whole domain site?
I have website django based, i need access control domain based like. I already established django own auth system and 2-auth system. I need for whole domain access control even for the static files. If that possible only access code not username and password, and this need to be hard coded env or something like this. Django version v4.0, Hosting Heroku -
JSON POST and GET 404 (Not Found)
I am trying to create an API in Django but am receiving the following errors message in the JavaScript console. GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Does anyone know how to fix this problem? API url: path("edit/<int:post_id>", views.edit, name="edit") views.py def edit(request, post_id): try: post = Post.objects.get(user=request.user, pk=post_id) except Post.DoesNotExist: return JsonResponse({"error": "Post does not exist."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) else: return JsonResponse({"error": "Need a GET request."}, status=404) JavaScript Function function edit_email(id){ console.log("edit button is clicked") document.querySelector('#post_itself').style.display = 'none'; document.querySelector('#date_and_time').style.display = 'none'; document.querySelector('#likes').style.display = 'none'; const textarea = document.createElement('textarea'); //get post fetch(`/edit/${id}`) .then(response => response.json()) .then(post => { textarea.innerHTML = `${post.post}` document.querySelector('#p_user').append(textarea); }) //save the post fetch(`/edit/${id}`,{ method: 'POST', post: JSON.stringify({ post: textarea.value }) }) } HTML {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself">{{ post.post }}</h6> <h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6> <h6 id="likes" class = "post_elements">{{ post.likes }}&#x1F44D;</h6> {% if post.user == request.user %} <button id="editButton" class="edit_button">Edit</button> {% endif %} </div> {% endfor %} I think something might be wrong in the way I am passing in the id to the API, … -
set calculated property on model only once
im using python3 + django, and i have a model of User with few fields an admin page where all the users are presented a form page where a single user is presented and can be updated an external API with 2 endpoints: GET /api/users/name (get all names for all the users) GET /api/users/:id/name (get name for user by id) i want to add a name property to be presented on admin page (as a column) and on a form page (read-only, not changeable) how can i add this "calculated" property without calling an api more than needed? -
how can i show a manytomany foeld values in a form?
i wrote a code about music and used ManyToManyField() as genre but when i try to show genres it just show : Genre['a number'] template: {% extends 'pages/base.html' %} {% block content %} <form> {% if mdata.image %} <img src="mdata.image.url" height="500" width="500"> {% endif %} {% for field in form %} <p>{{ field.label }} : {{ field.value}}</p> } {% endfor %} </form> <a href="{% url 'pages:edit_music' mdata.id %}">edit</a> {% endblock %} -
Model register save user created django admin
I'm using django admin, and I have a model in wich I have a created_user property. The problem is that I dont know how to register the user from the django admin. Someone know how to do this? -
dj allauth get password when its resetted
I need to provide the raw password of an allauth user to a third party provider when he resets his password. So everytime when the password gets resetted I call the @receiver(password_reset). However, then the password was already salted. I need to get the raw password data to realise the password change also at an external service. How would get the new "raw" password, which wasn't already salted or how could I desalt it? @receiver(password_reset) def password_change_callback(sender, request, user, **kwargs): #run third party api call containing the new password -
Read Only for specific rows Django not the empty filelds
I am trying to create read only field for specific row where is values , and i wrote this script , with this script after saving the page i can not edit the empty rows ,in the page. class Calender(admin.TabularInline): model = models.Calendar def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ("registrations", "calendar") return self.readonly_fields -
Best practices for managing Django auth using sessions and token based methods in same project
I'm trying to add API support via django-rest-framework for all the views in my project. Assume that all the views return a JSON response and are function based. How can I best handle this situation without re-writing a lot of code? Here is what I have at the moment: views.py @login_required @require_POST def get_data(request): #.... core logic .... return JsonResponse({'msg': '<...>'},status=200) @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def api_get_data(request): return get_data(request) urls.py url(r'^get_data/$', views.get_data, name='get_data'), url(r'^api/v1/get_data/$', views.api_get_data, name='api_get_data'), I'm using CSRFmiddleware, so I get CSRF blanket protection for all views. Is there a better approach than the above to achieve/ensure: REST API calls work without CORS/CSRF token Browser-based calls work only with CORS/CSTF token I'd appreciate any help or suggestions on how to design/organize the project for this use case. -
Django signup form doesn't submit data or save in database or valid and invalid errors working
$ I was trying to submit this following codes , it never submit or saved in database or give any reaction , even the warnings or (valid and invalid of bootsrap5.2 in not working) , i need support, thank you alot $ this is code in the (views.py), from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as signin from django.contrib.auth import authenticate # This can replace the 3 uppers from .forms import SignUpForm def signup(request): form = SignUpForm() if request.method == 'POST' and 'btnsignup2' in request.POST: form = SignUpForm(request.POST) if form.is_valid(): user = form.save() signin(request, user) return redirect('index') else: form = SignUpForm() context = { 'basic': {'main': 'Project', }, 'form': form } return render(request, 'accounts/signup-dj.html', context) $ this is code in the (forms.py) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as signin from django.contrib.auth import authenticate from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=250, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username', 'password1', 'password2'] $ this is (urls.py) from django.urls import path from . import views urlpatterns = [ path('login', views.login, name="login"), path('signout', views.signout, name="signout"), path('signup', views.signup, name="signup"), ] $ this is code in the (HTML) {% extends 'base.html' … -
Using Javascript to parse Django Data in Leaflet Maps
Hi I am wondering if anyone can help me figure this problem out. I am trying to add addresses from my Django database into a Javascript which will convert the addresses to long/lat coordinates, and thus allowing me to use those new coordinates as markers on a leaflet map. Currently I have the map loaded in. <body> <div id="map"></div> <script> var map = L.map('map').setView([37.116386, -98.299591], 5); L.tileLayer('https://api.maptiler.com/maps/basic-v2/256/{z}/{x}/{y}.png?key=APIKEY', { attributions: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>' }).addTo(map) var marker = L.marker([37.116386, -98.299591]).addTo(map); </script> </body> Basically I want to replace the marker values with the value I render from the address provided in Django that I would filter through. {% for address in addresses %} <a>{{address.addresses}}</a> {% endfor %} If I were to filter say the business associated with the address, I would want it to render that marker for that specific business address. If anyone can help it would be greatly appreciated. -
Why are my converted Markdown HTML tags returned as text?
A function in my views.py file converts Markdown files and returns the HTML to another function which is used to show the current entry (entry()). In entry(), I have a dictionary that is gives a HTML template access to the converted content. However, when the tags like <h1> and <p> are shown on the page instead of being hidden. So, <h1>CSS</h1> <p>CSS is a language that can be used to add style to an <a href="/wiki/HTML">HTML</a> page.</p> is shown instead of CSS CSS is a language that can be used to add style to an HTML page. -- How do I get rid of the tags on the page and have them actually be used in the HTML file? entry.html: {% block body %} <div class="entry-container"> <div class="left"> {{ entry }} </div> <div class="right"> <a href="{% url 'edit' %}" class="edit-btn"> <button class="edit">EDIT</button> </a> </div> </div> {% endblock %} views.py: import markdown from . import util def entry(request, name): entry = util.get_entry(name) converted = convert(entry) if util.get_entry(name) is not None: context = { 'entry': converted, 'name': name } global current_entry current_entry = name return render(request, 'encyclopedia/entry.html', context) else: return render(request, "encyclopedia/404.html") def convert(entry): return markdown.markdown(entry) urls.py: path('<str:name>', views.entry, name='entry'), util.py: def … -
Django not using the form tag
In my Django template I don't wanna use {{form]] tag. Is there any way I can save the HTML form to my models without using {{form}} tag? myform.html <form id="firstform" action="{% url 'saveview' %}" method="POST"> {% csrf_token %} <input type="text" name="brand" id="brand"> <input type="text" name="series" id="series"> <input type="text" name="model" id="model"> <input type="submit" class="btn btn-primary" id="save-button" name="save-button" value="SAVE"> </form> views.py def saveview(request): return render(request,'myform.html')