Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(begginner) how complete is really django?
Hello i am new in python programmation and programation in general(even if i have some IT related knowledge) i have few basic questions to be sure about how django work so as i understand its a framework for web, and you can use it fully with python What are the limitations of django compared to "basic" html/css/sql/php/js combo ? i also know that django is server side framework which make it work kinda like an app running on your web browser Is it possible/most convenient to do a website ONLY by using python with django ? does the framework really take care of all by itself and we can use python for anything ? How does it handle sql ? does it do some kind of local sql base ?(i only knew basic of sql) Thank you -
Django RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1
Comments Functionality I decided to add a "comments" functionality for anyone to post comments on anyone's post. Everything works except one line of code which is giving me the problem. I receive the following error: RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1 Comment has no post. The error is directed to the views.py Specifically this line of code: form.instance.post.slug = self.kwargs['slug'] Please kindly advise how this code can be altered to remove the error. views.py class AddCommentView(CreateView): model = 'Comment' form_class = CommentForm template_name = 'HomeFeed/add_comment.html' def form_valid(self, form): form.instance.post.slug = self.kwargs['slug'] return super().form_valid(form) success_url =reverse_lazy('main') urls.py path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"), forms.py class CommentForm(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 BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") def __str__(self): return self.chief_title def total_likes(self): return self.likes.count() class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateField(auto_now_add=True) def __str__(self): return '%s - %s' %(self.post.chief_title, self.name) add_comment.html (this html is for ppl to add their comments) <div class="form-group"> <form method="POST"> {% csrf_token … -
NoReverseMatch at /admin/ when add custom url
I'm trying to add a custom page in django admin. I wrote code as I've learned, but everytime I try to access the custom page I created, NoReverseMatch exception keeps occuring. NoReverseMatch at /admin/order/order/date_view/ Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|fcuser|product|order)/$'] I've tried various code I could find online, but none is working. Following is my code. class OrderAdmin(admin.ModelAdmin): .... def get_urls(self): urls = super().get_urls() # urls = super(OrderAdmin, self).get_urls() custom_urls = [ # path('date_view/', self.admin_site.admin_view(self.custom_date_view)) # url(r'^date_view/', self.admin_site.admin_view(self.custom_date_view)) path('date_view/', self.custom_date_view) ] return custom_urls + urls def custom_date_view(self, request): context = dict() return TemplateResponse(request, 'admin/order_date_view.html', context) None of the comment solved the issue. I'd be really grateful if anyone can help me out. I want my OrderAdmin class keeps inheriting ModelAdmin. -
how to make attribute in django 3
(myvenv) basekmacbook@BASEK-MACBOOK-PRO portfolio-project % python manage.py makemigration Traceback (most recent call last): File "/Users/basekmacbook/Desktop/portfolio-project/manage.py", line 22, in main() File "/Users/basekmacbook/Desktop/portfolio-project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/core/management/init.py", line 377, in execute django.setup() File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File"/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.9/3.9.1_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 790, in exec_module File "", line 228, in _call_with_frames_removed File "/Users/basekmacbook/Desktop/portfolio-project/jobs/models.py", line 3, in class Job(models.Model): File "/Users/basekmacbook/Desktop/portfolio-project/jobs/models.py", line 5, in Job summary = models.Charfield(max_length=200) AttributeError: module 'django.db.models' has no attribute 'Charfield' -
Django foreign key field not updating with selected value from React Select component
I have a webpage in my issue tracker project that allows a project manager to assign a user to a project. I am using React Select to allow the manager to select a user from a dropdown. When they click the add user button, the selected value gets sent to the backend through an api call. I have an APIView called assignuser, which takes in the post request and updates the user foreign key field in my Project model. Am I referencing the selected value wrong? I have tried sending selectedValue.value to my backend but it keeps on coming up as undefined. React Frontend import React, { Component } from "react"; import { useState, useEffect } from "react"; import { Grid, TextField, Button, Typography } from "@material-ui/core"; import { FixedSizeList as List } from 'react-window'; import css from './style.css'; import Select from 'react-select'; import {useLocation} from "react-router"; const manageusers = () => { const [role, setRole] = useState([]); const location = useLocation(); const [project_name, setProjectName] = useState(); const [selectedValue, setSelectedValue] = useState() const rolelist = []; const handleChange = obj => { setSelectedValue(obj); } useEffect(() => { fetch("/api/manageroles") .then((response) => response.json()) .then((data) =>{ setRole(data) }) }, []) const post = … -
TemplateDoesNotExist at
I have a problem with REQUEST. Add myapp, so that it recognizes the parameters in request, however, it keeps throwing me an error when reloading the page. What is the problem? Ilustration of problem in WEB CMD def index(request): def index(request): html= """ <h1>Inicio</h1> <p>Años hasta 2050:</p> <ul> """ year =2021 while year<=2050: if year%2 == 0: html+=f"<li>{str(year)}</li>" year+=1 html +="</ul>" #return HttpResponse(layout + html) return render(request, 'index.html') (Index function) -
I Want to create a unique id in django model with customer-auto incremented number
There are 2 models, customer model and ticket creation for a customer class cust_M(models.Model): customer = models.TextField(max_length=8) class TKT(models.Model): tkt_unique_id = models.ForeignKey(customer) + autoincremented when ever we create a instance for the TKT i want to increment the number for the customer. eg: customer1 - 1 customer1 - 2 customer1 - 3 customer2 - 1 customer2 - 2 customer2 - 3 ... ... -
Django custom form - is_valid does not call clean method when __init__ method available
I have the following custom form code in Django: class JoinMeetingForm(forms.Form): meeting_id = forms.UUIDField(help_text="Enter the UUID") def __init__(self,user,*args,**kwargs): self.user=user super(JoinMeetingForm,self).__init__(*args) def clean_meeting_id(self): data = self.cleaned_data['meeting_id'] meeting = Meeting.objects.filter(pk=data) querySuccess = False if len(meeting) == 1: if(meeting[0].joined_user==None): querySuccess = True # ToDo return data First, I call JoinMeetingForm(request.user), which calls the init method. Then, I call form.is_valid(), however, this does not call the clean_meeting_id() method - why is this the case? Strangely, if I comment out the init method, the is_valid() method calls the clean_meeting_id() method. Thanks in advance! -
ValueError: The view mode.views.userSettings didn't return an HttpResponse object. It returned None instead
I am trying to fix this error but I don't know what is the reason for getting it. I am working on a Django Project trying to add a Theme Selection Functionality. The user can select the theme either Light or Dark and it reflects in the backend by the CSS file under the setting.value. The idea is that when a user selects a theme it is saved in the backend and it doesn't chage(unless another theme is chosen). The problem now is that when I refresh the page it returns back to the initial theme and I receive the below error: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 307, in check_response raise ValueError( ValueError: The view mode.views.userSettings didn't return an HttpResponse object. It returned None instead. Here is the model.py class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name Here is the views.py def userSettings(request): user, created = User.objects.get_or_create(id=1) setting = getattr(user, 'setting', None) if setting: seralizer = UserSerailizer(setting, many=False) return JsonResponse(seralizer.data, safe=False) def updateTheme(request): data = json.loads(request.body) theme = data['theme'] user … -
Many-to-many and hierarchical database design
i'm designing a database and run into some problems: I have a Document entity consisting of many fields. Mostly i want to use the same version of that document but sometimes users should be able to customize some of the fields for a specific usage of the document. Not customized fields should use the value of the parent document as a default. Changes to the parent document should get propagated to any not customized field of a specific usage. I have a table Document: Document: id | field1| field2 | field3| parentDocumentId For parent documents is parentDocumentId = Null. Customized usages of a document have the new value for the customized fields saved and for not customized fields simply null. Is this a good design? Furthermore the Document entity has a many-To-many relationship with another entity Course. My problem now is when i look at a row of Document with parentDocumentId != null and courses = null i can't determine if the relationship is either not customized by the user yet and i should use the value of the parent document or the field is customized by the user and simply has no courses. How can i solve that? Thanks -
Django Error - Reverse for 'new_bid' with arguments '('',)' not found. 1 pattern(s) tried:
I'm somewhat new to Django and creating a way for users to 'bid' on items, similar to ebay. I am getting the error: Reverse for 'new_bid' with arguments '('',)' not found. 1 pattern(s) tried: ['new_bid/(?P[0-9]+)$'] I know I have some things mixed up, specifically the end of views.py in the return render request but I'm not sure what I need to have there. I know in the html {% url 'new_bid' i.id %} is also not correct, but I'm struggling to figure out what should be here as well. Any help is appreciated as I'd like to learn more. views.py def new_bid(request, listingid): current_bid = Listings.objects.get(id=listingid) current_bid = current_bid.starting_bid if request.method == "POST": user_bid = int(request.POST.get("bid")) if user_bid > current_bid: listing_items = Listings.objects.get(id=listingid) listing_items.starting_bid = user_bid listing_items.save() try: if Bid.objects.filter(id=listingid): bidrow = Bid.objects.filter(id=listingid) bidrow.delete() bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() except: bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() Bid.objects.filter(id=listingid) return render(request, "auctions/listing.html", { "i": "id" }) else: response = redirect('listingpage', id=listingid) response.set_cookie('error', 'Bid should be greater than current price', max_age=3) return response else: return redirect('index') The urls in urls.py path("listings/<int:id>", views.listingpage, … -
Return the instance of the model, if a value in it contains a string passed in by a user. Django Rest Framework, filtering
So lets say i have a model called Article, which hold a field called article_title(CharFiled). On the client side, the user passes in a keyword and sends it to the server. Can i make a serialized view, which returns every database instance, on a condition that it contains the passed in keyword in the article_title field? Is there a way to implement this? -
When building forms in Django, is it good practice to use one 'fat' model to contain all my fields for multiple forms?
Context: I am building a car dealership app and have multiple forms to create such as: A basic contact requesting a name, email, phone and comments. A service form requesting the above along with the users make, model and mileage A sales form, requesting all the above again along with a few other similarly relevant questions. Problem: So I'm trying to find out is it best practice to have one 'fat' model containing all these fields and then create multiple forms from them or to create a model per form? I know that I should stick to the DRY practices but I would really benefit from a stronger understanding. -
I can extends + with?
I need to pass the value from the template when connecting extends. So that I can check whether to connect the style or not. I need to pass the page title, is main page {% extends "base_not_auth.html" with page="main" %} If main page, i use css file {% if page == "main" %} <link rel="stylesheet" href="{% static 'css/page.css' %}"> {% endif %} -
user.is_authenticated works in html but not views
I just learned about the django.contrib.auth built-in package and am trying to implement user authentication for my blog application! Doing user.is_authenticated in my html works: <div class="footer"> <div class='sub-footer'> <ul style="list-style:none;"> <li>-<a href="{% url 'login' %}">Admin, Login Here!</a></li> <li>- <a href="https://www.flaticon.com">Pencil Icon made by </a><a href="https://www.flaticon.com/authors/becris">Becris </a><a href="https://www.flaticon.com">from www.flaticon.com</a> <li>- <a href="https://www.flaticon.com">Heart Icon made by </a><a href="https://www.flaticon.com/authors/gregor-cresnar">Gregor Cresnar </a><a href="https://www.flaticon.com">from www.flaticon.com</a> </ul> </div> </div> {% if user.is_authenticated %} yo whats good authenticated user {% endif %} But, when I try this in my views: if user.is_authenticated: return render(request, 'admin.html', context) return render(request, 'registration.html') I get this error: NameError at /admin-dash/ name 'user' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/admin-dash/ Django Version: 3.1.2 Exception Type: NameError Exception Value: name 'user' is not defined Exception Location: C:\Users\benja\Desktop\mysite\mysite\blog\views.py, line 137, in admin_view Python Executable: C:\Users\benja\anaconda3\envs\mysite\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\benja\\Desktop\\mysite\\mysite', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\python38.zip', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\DLLs', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\lib', 'C:\\Users\\benja\\anaconda3\\envs\\mysite', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\lib\\site-packages'] Server time: Sun, 10 Jan 2021 00:03:09 +0000 Traceback Switch to copy-and-paste view C:\Users\benja\anaconda3\envs\mysite\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\benja\anaconda3\envs\mysite\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\benja\Desktop\mysite\mysite\blog\views.py, line 137, in admin_view if user.is_authenticated: … ▶ Local vars It makes sense, but I … -
How to autofocus a Charfield in a Django ModelForm
In my django app I want to set focus to the first CharField (task) when the page loads. my models.py is from django.db import models class ListModel(models.Model): task = models.CharField(max_length=255) status = models.BooleanField(default=False) def __str__(self): return f"{self.task} : {str(self.status)}" and forms.py is from django.forms import ModelForm from .models import ListModel class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] I have tried adding the following widget in my CharField (in models.py): task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True}) but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput' I have also tried adding the following to the ListForm class (in forms.py): def __init__(self): self.fields['task'].widget.attrs.update(autofocus = 'autofocus') though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField? -
Setup a ready signup template in django instead of the UserCreationForm
So I have a designed signup form template in html & css and I want to know how to setup it in Django instead of using its forms -
Django Rest how to test a DELETE request using pytest
So i'm trying to test deleting a post. my post view is using RetrieveUpdateDestroyAPIView which enable me to use GET, PUT and DELETE requests. but for some reason I get a testing error saying: Method Not Allowed @pytest.fixture def delete_post(api_client): post_id = Post.objects.all()[0].id delete_post_url = '/posts/{post_id}/' delete_post = api_client.delete(delete_post_url) return delete_post @pytest.mark.django_db def test_post_detail_render(self, api_client, login, create_post ,delete_post): delete_post_page_render = delete_post assert delete_post_page_render.status_code == 200 E assert 405 == 200 E + where 405 = <HttpResponseNotAllowed [GET, HEAD, OPTIONS] status_code=405, "text/html; charset=utf-8">.status_code WARNING django.request:base.py:101 Method Not Allowed (DELETE): /posts/{post_id}/ WARNING django.request:log.py:224 Method Not Allowed: /recipes/{recipe_id}/ -
Django3 ListView with Conditional WHERE
I have simple ListView in Django 3: path("show/<int:pk>", ApplicantListView.as_view(), name='applicant-list'), my view is as follow: class ApplicantListView(ListView): model = Applicant paginate_by = 100 template_name = 'applicant_list.html' and the model class Work(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(False) date = models.DateTimeField() def __str__ (self): return self.title class Applicant(models.Model): name= models.CharField(max_length=200) email = models.EmailField(max_length=100) country = CountryField(blank_label='(select country)') work= models.ForeignKey(Work, on_delete=models.CASCADE) upload = models.FileField(upload_to='up/') def __str__ (self): return self.name so what I would like to achieve is to show only the applicants for the work ID used in the URL path. At the moment it shows all the records diregrading the pk used in the path. -
"Unable to log in with provided credentials."
When I tried to login and get the token, I get this error(with superuser works without error.): { "non_field_errors": [ "Unable to log in with provided credentials." ] } I am sure that I am sending the correct password and login I searched a lot for an answer and met someone. He says that the problem is that the password is encrypted on the base and I send it in plain text. If someone understands, please help! My code: Settings.py DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': False, 'SERIALIZERS': {}, } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path('auth/', include('djoser.urls.jwt')), ] -
Django - Redis SESSION_ENGINE only allow one session at a time
I would love to use redis (django-redis-cache) at my website as SESSION_ENGINE and site cache. The problem is that I only want to allow one session per user at a time. Previously It did that using the following signal: @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions old_sessions = Session.objects.filter(usersession__user=user) if request.session.session_key: old_sessions = old_sessions.exclude(session_key=request.session.session_key) old_sessions.delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) and the following model: class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) which was working pretty well so far. Sadly I made the experience that when using a scaleable Database like Galera wired HTTP error 400 are getting returned by my site as the session key seems to be unreachable on high I/O, that's why I wanted to switch over to Redis and have it all located at the In-Memory Database Redis provides. But how I can fetch session keys to check if there is already a session existing for a user and if so delete the session like shown above ... Thanks in advance -
Make Calculations and Output result
I am creating an App using Django and React. I would like the user to input several numeric values on the Frontend and based on these values to perform some calculations and output the result in the Frontend (also store the values in the database). I am confused on where on the backend I should add the logic to perform the calculations. On views.py or admin.py or on another file? I am currently trying to create the logic on the admin.py file but I am not sure if this will allow me to make the result visible on the frontend. -
Sort by aggregated foreign field in Django ModelAdmin changelist
In my current project I am trying to set up a simple testing app in Django. For management I use the generated Django admin, but I struggle to include a sortable computed field with best test result in changelist view of a model. My models are as follows (simplified): class Candidate(models.Model): name = models.CharField(max_length=255, null=False) email = models.EmailField(unique=True, null=False) class Test(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, null=False) result = models.PositiveIntegerField(null=True) class Question(models.Model): text = models.TextField(null=False) correct_answer = models.CharField(max_length=1, choices=OPTIONS, null=False) class Answer(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=1, choices=Question.OPTIONS, null=True) A candidate may have multiple tests and I want to display a field with his best result in the changelist view and be able to sort by it. The result is a percentage of correct answers (Answer.question.correct_answer == Answer.answer) out of all answers with the same test FK. Discovered I cannot use a custom computed field defined by a function, because Django then cannot sort by it as sorting needs modification of a queryset which translates directly to SQL. So I added the Test.result field with calculated percentages (which denormalized the scheme :-/ ) and try to add annotated field in queryset with SELECT MAX(Test.result) … -
Django - Login page with Username, Company Code and Password
How to create a custom field in the User model where besides email and password it will also require Company Code in the Login page. I am currently using the default Forms and Views that comes with User. forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] urls.py path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), -
Django: Unable to load embedded PDF dynamically
I'm trying to display a PDF (uploaded by the user) in my template in an embedded frame. What's strange is that the url only works if I use an anchor tag but not if it's embedded. I get : Template ✓ Works <a href="{{booking.lease.url}}">Lease</a> (url = http://127.0.0.1:8000/media/leases/lease_CZORz79.pdf) X Doesn't Work <embed src="{{booking.lease.url}}" width="500" height="375" type="application/pdf"> (url = http://127.0.0.1:8000/media/leases/lease_CZORz79.pdf) (ie, exact same) Views.py def review_lease(request, pk): booking = Booking.objects.get(id=pk) context= { 'booking': booking, } return render(request, 'dashboard/review_lease.html', context) Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Models.py class Booking(models.Model): status = models.PositiveSmallIntegerField(choices=BOOKING_STATUS_OPTIONS, default=0) tenant = = models.ForeignKey('TenantProfile', on_delete=models.CASCADE, related_name='booking') lease = models.FileField(upload_to='leases/', null=True)