Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MultipleObjectsReturned at /author/Ed Sheeran get() returned more than one Songs -- it returned 2
I was coding a song viewing website with Django then suddenly came across this error MultipleObjectsReturned at /author/Ed Sheeran get() returned more than one Songs -- it returned 2! I was trying to set up my website such that when users click on the name of the author of any song, they will be redirected to another page where there are songs of that author only. But unfortunately, my code is running into this error. My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) My views.py: def home(request): context = { 'songs': Songs.objects.all() } return render(request, 'home.html', context) class AuthorSongListView(ListView): model = Songs template_name = 'author_songs.html' context_object_name = 'songs' paginate_by = 2 def get_queryset(self): author = get_object_or_404(Songs, author=self.kwargs.get('author')) return Songs.objects.filter(author=author) My html: {% block content %} <h1 class="mb-3">Songs by {{ view.kwargs.author }}</h1> {% for song in songs %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a> </div> <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2> <p class="article-content">{{ song.lyrics }}</p> </div> </article> {% endfor %} {% endblock content %} -
Django: pass some paremeter to view in Django urls
I want to pass some string for some urls to my views in django Suppose i have path('someurl/', someview , name='someurl'), I want to pass some string to someview, when this url is called so is this possible path('someurl/', someview(somevar="test") , name='someurl'), and then i have the view def someview(request, somevar): access somevar here Is this possible in Django urls. -
Django migrations raw SQL update not working
I have a very simple migration which updates a table, when I run it on pgadmin, it just executes fine the values change, but in migration nothing is saved. # Generated by Django 3.0.5 on 2021-05-10 06:36 from django.db import migrations class Migration(migrations.Migration): atomic = False dependencies = [ ('api', '0073_fill_grid1000'), ] operations = [ migrations.RunSQL(""" UPDATE api_grid125 SET parent_grid_id = intersections.parent_id FROM ( SELECT api_grid125.id as id, api_grid250.id parent_id FROM api_grid250 JOIN api_grid125 ON ST_Intersects(api_grid250.area, api_grid125.area) AND ST_Area(ST_Intersection(api_grid250.area, api_grid125.area)) > 0.01 ) as intersections WHERE api_grid125.id = intersections.id """, ""), ] My database is PostgreSQL, thanks! -
How to set default values on django admin site for extended user model?
I want to create a user profile model as an extension of the original django user model. I implemented the model in models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) solved = models.IntegerField(default=0) profile_pic = models.ImageField(upload_to='profile_pic', default="/media/profile_pic/default-profile.jpg") school = models.CharField(max_length=200, blank=True, null=True) However, when I create a new user in the admin site, there is no default value for the profile_pic field. In addition, although the solved field shows a '0' on the form, the value is not saved after I pressed save: I registered the extended user model like this in admin.py: class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'User Profile' class UserAdmin(BaseUserAdmin): list_display = ('username', 'is_staff', 'solved') inlines = (UserProfileInline,) def solved(self, obj): return obj.userprofile.solved admin.site.register(User, UserAdmin) Am I doing something wrong? Is the default value only used when creating a user using python but not the admin site? Please help. Thanks. -
django - How to upload file to local and remote server directory at same time
I am implementing a feature in django where file uploaded by user should be saved in both local system and remote server location also. I am able to do both the process individually but not together. Is there any way we can upload a file to both the location local and remote? Django version - 3.0 -
ValueError at /student/ : save() prohibited to prevent data loss due to unsaved related object 'Qid'
models.py class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.OneToOneField(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() views.py : Trying to save Answer text field along with 1 One-to-One Field and 2 Foreign key fields in the database.but getting error when user saves answer through form. @login_required(login_url='login') @allowed_users(allowed_roles=['Student']) def handle_response(request): if request.user.is_authenticated: myuser = User.objects.all() title = quiztitle.objects.all() ques = question.objects.all() if request.method == 'POST': Answer = request.POST.get('{{x.Qid}}') Quiz_id = request.POST.get('Quiz_id') Qid = request.POST.get('Qid') quizid = quiztitle(Quiz_id=Quiz_id) quesid = question(Qid=Qid) response = answer(Answer=Answer) response.User_id = request.user #tried to save Foreign key field response.Quiz_id = quizid #tried to save Foreign key field response.Qid = quesid #tried to save one to one field response.save() return HttpResponseRedirect('/student') return render(request,"student.html",context={"ques": ques ,"title": title ,"myuser": myuser}) -
KeyError: 'postgraduate-course' in django webapp
I have used django to develop a web app. However, I got a key error, which is very confused. HTML: <form action="/content_checklist_name_url/" method="POST" onsubmit="return confirm('Do you want to confirm entries?');"> <label> Postgraduate Course: </label> <select id="postgraduate-course" name="postgraduate-course"> <option value="">--Select--</option> <option value="Yes">Yes</option> <option value="No">No</option> </select> </form> view.py: def content_checklist_name_url(request): if request.method == 'POST': Course_Form = ContentChecklistForm(data=request.POST) if Course_Form.is_valid(): postgraduate_course = Course_Form.cleaned_data["postgraduate-course"].map({'Yes': 1, 'No': 0}) I got the error: KeyError: 'postgraduate-course' at this line: postgraduate_course = Course_Form.cleaned_data["postgraduate-course"].map({'Yes': 1, 'No': 0}) -
How do I delete data on button click from django database?
I need to delete data on click of a button in django here's my view page views.py here's my button code html button onclick of that button data should get deleted. this button works as a refresh button. So even if I do not click on the button only do page refresh data get deleted -
cannot access user data from social-auth-app-django
I am overwhelmed by the authentication of Django and trying to wrap my head around it for a while. i have used social-auth-app-Django to use OAuth for authorization from GitHub and Facebook. GitHub worked and Facebook didn't worked, after log-in using GitHub I checked the admin page, in the user social auths part i wasn't able to access the provider name using the template syntax in the html Page didn't showed up! can someone explain what really going on here, and what is associations and nonces too? this is my html. -
Django Email Settings for different purposes
How to set django to have multiple EMAIL Settings. Example: Email for registration and email for reset password: if registration: # EMAIL SETTINGS EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'XXX' EMAIL_PORT = 'XXX' EMAIL_HOST_USER = 'registrationemail@gmail.com' EMAIL_HOST_PASSWORD = 'XXX' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL = True # EMAIL_USE_TLS = False else: # EMAIL SETTINGS EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'XXX' EMAIL_PORT = 'XXX' EMAIL_HOST_USER = 'resetpassword@gmail.com' EMAIL_HOST_PASSWORD = 'XXX' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL = True # EMAIL_USE_TLS = False Note: I can send email without problems. Should I send a parameter to my settings.py? If so, how should I do it? -
django admininstrator register accpetion
Now, I'm using django's basic form of registration. However, I want to make customed administrator site that can accpet registration and refuse it. I really need some help. basic form: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('login') else: form = UserRegisterForm() return render(request, 'home/register.html', {'form': form}) -
AuthFailed at /oauth/complete/github/ Error in Django for social login
Authentication failed: The redirect_uri MUST match the registered callback URL for this application. I have registered i my github account and the callback url i have set is: http://localhost:8000/oauth/complete/github/ and homepage url http://localhost:8000/ but the error is still there. and redirect Url in settings.py LOGIN_REDIRECT_URL = 'home' I have tried many other techniques please help me out my urls.py from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings from developer import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name='home'), path('profileEdit',views.profile_edit_form,name='profileEdit'), path('accounts/', include('accounts.urls')), path('<int:pk>', views.profile_view, name='profileview'), path('invites/', views.invites_view, name='invitesview'), path('invites/<int:pk>', views.inviter_view, name='inviterview'), path('oauth/', include('social_django.urls', namespace='social')), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Using get_natural_key and AbstractUser: "ValueError: Field 'id' expected a number but got <String>"
I'm trying to loaddata a yaml fixture using natural foreign key. The thing is: the foreign key in question is an AbstractUser. models.py: from django.contrib.auth.models import AbstractUser, BaseUserManager class MyUserManager(BaseUserManager): def get_by_natural_key(self, username): return self.get(username=username) class MyUser(AbstractUser): ... objects = MyUserManager() # use for serialization def __str__(self): return self.username def natural_key(self): return (self.username) class Cars(models.Model): owner = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) My fixture is a yaml file: (I've already a MyUser account with the username "Franck" in the database). - model: myapp.Cars fields: owner: - Franck But when doing: ./manage.py loaddata myfixture.yaml, I've got the error: ... ValueError: invalid literal for int() with base 10: 'Franck' The above exception was the direct cause of the following exception: ... ValueError: Field 'id' expected a number but got 'Franck'. -
Djongo DateTrunc returns nothing
Django 3.0.5 + Djongo 1.3.4 Database function (Trunc) as per below URL in Django returned nothing. https://docs.djangoproject.com/en/3.0/ref/models/database-functions/#trunc My context_processors.py as below, from .models import Article from django.db.models import Count, F, DateField from django.db.models.functions import Trunc # Reference: https://stackoverflow.com/questions/49440657/django-blog-archive-display-list-of-years-and-months-that-include-post # https://www.jianshu.com/p/3f846ecbd945 # return dictionary for parsing side menu def Side_Menu_Context(request): breakpoint() Year_Month = Trunc(Article.objects.all()[0].time_publish,'month', output_field=DateField()) Dict_Context = {'QS_YM_BlogCount': Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())).values('Year_Month').annotate(num_of_article = Count('id'))} return Dict_Context DEBUG output as below: [29] > /usr/src/app/IoTSite/context_processors.py(16)Side_Menu_Context() -> return Dict_Context (Pdb++) pp Article.objects.all()[0].time_publish datetime.datetime(2021, 5, 10, 1, 44, 4, 619000, tzinfo=<UTC>) (Pdb++) pp Year_Month Trunc(Value(2021-05-10 01:44:04.619000+00:00)) (Pdb++) pp Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())) (Pdb++) pp Dict_Context (Pdb++) whatis Dict_Context <class 'dict'> (Pdb++) whatis Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())) <class 'django.db.models.query.QuerySet'> (Pdb++) l. 11 def Side_Menu_Context(request): 12 breakpoint() 13 Year_Month = Trunc(Article.objects.all()[0].time_publish,'month', output_field=DateField()) 14 15 Dict_Context = {'QS_YM_BlogCount': Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())).values('Year_Month').annotate(num_of_article = Count('id'))} 16 -> return Dict_Context [EOF] (Pdb++) Year_Month = Trunc() returned something, but Dict_Context = {} returned nothing, why so since they use the same function Trunc() ?? -
Using other models in Django Manager causes ImportError: partially initialized module (due to circular dependency)
I have the following function in my UserManager that I use with my CustomUser model in my django app. from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): ... def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user I needed to create a corresponding UserProfile object when a user is registered, so I updated the _create function as follows: from profiles.models import UserProfile class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() # Create the user profile UserProfile.objects.create(user=user) return user But this throws: ImportError: cannot import name 'CustomUser' from partially initialized module 'user s.models' (most likely due to a circular import) (../users/models.py) My CustomUser is defined as follows: class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] auth_provider = models.CharField( max_length=10, default=AUTH_PROVIDERS.get('email')) objects = UserManager() And the UserProfile model is defined as follows: class UserProfile(models.Model): user = models.OneToOneField( CustomUser, null=True, on_delete=models.CASCADE, related_name="profile") … -
How to solve 'ImproperlyConfigured at /admin/filebrowser/browse/ Error finding Upload-Folder (site.storage.location + site.directory). '
My project structure is main -temp project -settings.py I want to browse main/temp/ folder while navigating to the link: localhost:8000/admin/filebrowser/browse Please help me with the correct settings of the django file browser, since the settings are not clear in the official documentation. https://django-filebrowser.readthedocs.io/en/3.13.2/settings.html#settings in settings.py from filebrowser import settings FILEBROWSER_DIRECTORY = getattr (settings, "FILEBROWSER_DIRECTORY", "main/temp") -
How to rectify account activation error in django
I'm trying to click on an email activation link so as to activate a user account after submitting a registration form but I keep getting this error: The connection for this site is not secure; 127.0.0.1 sent an invalid response.. I ought to be redirected to the dashboard. Account is successfully created since the new user appears in the database but clicking on the activation link sent to the email throws back an error. I'm following a tutorial though, but I can't figure out why the problem occurs. url.py urlpatterns = [ path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate'), path('dashboard/', views.dashboard, name='dashboard') ] templates account-activation_email.html: {% autoescape off %} Great {{ user.user_name }}! Please click on the link below to activate your account https://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} register.html <form class="account-form p-4 rounded col-lg-10 mx-auto" method="post"> {% csrf_token %} <h3 class="mb-2 font-weight-bold">Create an account</h3> <p class="mb-4">Sign Up</p> <label>{{ form.user_name.label }}<span class="text-muted small"> (Required)</span></label> {{ form.user_name }} <label>{{ form.email.label}}<span class="text-muted small"> (Required)</span></label> {{ form.email }} <label>{{ form.company.label}}<span class="text-muted small"> (Required)</span></label> {{ form.company }} <label>{{ form.license_number.label}}<span class="text-muted small"> (Required)</span></label> {{ form.license_number }} <label>{{ form.state.label}}<span class="text-muted small"> (Required)</span></label> {{ form.state }} <label>{{ form.city.label}}<span class="text-muted small"> (Required)</span></label> {{ form.city }} <label>{{ form.address.label}}<span … -
How can I unit test a POST request with custom permissions in Django Framework?
everyone. I hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development. I only know Python, so Django REST framework my best fit for the moment. Right now I'm trying to implement Unit tests for my API. It's a simple model to implement CRUD on the names and heights of NBA players. In my models I added a class to describe this data and translated it to a view with ModelViewSets. I wanted to make this data editable only for a specific type of user (a read-write user), only readable for another (read-only user) as well as unaccesible to non-authenticated users. To do so, I created a custom User Model and translated it to my views with a custom permission. Now I want to write a few Unit tests to check that: r/w user can create a new player r/w user can get a list of players r/o user cannot create a new player r/o user can get a list of players unauthenticated user cannot create a new player unauthenticated user cannot get a list of players So far I've managed to run unit tests on my GET REQUEST with an OK output. But … -
Uploading image is not creating media file
Guys I'm new to django I tried uploading images in the imagefield but it's not creating media folder and the database image column is also blank. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class Hotel(models.Model): name = models.CharField(max_length=50) hotel_Main_Img = models.ImageField(upload_to='images/') image.html <form method="POST" enctype="multipart/form-data> {% csrf_token %} <input type="file" class="form-control" id="customFile" name="image"/></div> </form> Even tried manually creating the media file Django. Still nothing!! Any help Will be appreciated -
Django Admin 403 - Forbidden: Access is denied IIS
first of all I apologize for my bad English. Did I upload the Django project to the windows server, but when I added data from the admin panel, the result I got is as follows. "403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied." Settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "home", 'django.contrib.sitemaps' ] MIDDLEWARE = [ 'htmlmin.middleware.HtmlMinifyMiddleware', 'htmlmin.middleware.MarkRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'umy.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'umy.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') web.config <?xml version="1.0" encoding="utf-8"?> … -
Display results of query in user admin section - django
Newbie question: I have my "users" app in the django admin but is there a way to implement a section that only shows users with criteria is_staff = False or any other criteria that I define? I'm a bit lost because I don't think it's necessary to create an app, because I don't need to create a new table, just query and display. For example: My query should I implement it in users / admin.py? But how do I render the result of the query? Thanks! -
django doesn't render a first <form> tag in the template
I have a base template to extend: {% load static %} {% load i18n %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width,initial-scale=1"> {% block title %} <title>taskmanager</title> {% endblock title %} <link rel="stylesheet" type="text/css" href="{% static 'common_static/base/styles/base.css' %}"> {% block extrahead %}{% endblock extrahead %} </head> <body> <header> <div class="header-main-area center-area"> <div id="switch-lang" class="header-element"> {% include 'svgpaths/language_icon.html' %} {% get_current_language as LANGUAGE_CODE %} {% get_language_info for LANGUAGE_CODE as current_language %} <div class="header-element-caption"> {{ current_language.name_local }}</div> <form action="{% url 'set_language' %}" method="post" class="lang-dropdown dropdown-content">{% csrf_token %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <button type="submit" name="language" value={{ language.code }} class="dropdown-item">{{ language.name_local }}</button> {% endfor %} </div> <div id="account" class="header-element"> {% include 'svgpaths/account_icon.html' %} {% if username %} <div class="header-element-caption">{{ username }}</div> {% else %} <div class="header-element-caption">{% translate "account" %}</div> {% endif %} <div class="acconunt-dropdown dropdown-content"> <a href="{% url 'logout' %}" class="dropdown-item">{% translate "log out" %}</a> <a href={% url 'user_settings' %}><div class="dropdown-item">{% translate "settings" %}</div></a> </div> </div> </div> </header> <main> {% block maincontent %} <h1>This is the base templated for extending</h1> {% endblock maincontent %} </main> {% block bodybottom %}{% endblock bodybottom %} … -
Uploading and Downloading Files with Django and Nginx
I'm currently trying to upload some files using Django and it seems to be working for the most part. I'm at least able to see that the file is added to the specific model in the Django admin panel but I'm unable to open it. Additionally, whenever I try to get the URL of the file, I get forwarded to the Django error page with a nice error that says, [Errno 2] No such file or directory: 'media/some_file.csv' Here is my file model : class File(models.Model): challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE, default="") file = models.FileField(default="", upload_to="media/") def __str__(self): return self.challenge.challenge_id Settings.py : STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'server', 'static'), os.path.join(BASE_DIR, '..', 'media'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' Upload Function : def uploadChallengeFile(request): latestChallenge = Challenge.objects.last() for file in request.FILES.items(): file_model = File(challenge=latestChallenge, file=file[0]) file_model.save() data = {"data": [True]} return JsonResponse(data, safe=False) Download Function : def downloadFile(request, challenge_id): challenge = Challenge.objects.filter(challenge_id=challenge_id) filename = File.objects.filter(challenge=challenge).values("file")[0]["file"] content = open(File.objects.get(challenge=challenge).file.url).read() response = HttpResponse(content, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response urls.py : url(r'^api/start/download/(?P<challenge_id>[\w.@+-]+)/$', views.backendServices.downloadFile, name="download") It seems like Django is saving the instance of the file but not actually storing it. Do I need to configure the nginx.conf to serve the … -
Is it possible to execute javascript through Wagtail's richtext field?
I was building a website with django and wagtail as cms, I was wondering if it's possible to execute javascript through wagtail's richtext field with wagtail's default richtext filter. For example, add a onclick attribute to a link. My goal is to prevent such thing from happening, for security reasons. -
What data is this?
I am using Django and I am getting a pdf file stored in BinaryField and trying to send it in a response as data-type (Preferably, I want to send it in as many data-types as I can as requested by a client). class CVPdf(generics.UpdateAPIView): permission_classes = [IsAuthenticated] parser_classes = [FileUploadParser] def get(self, *args): """ * ``:param request:`` GET request sent with ``Authorization: Bearer token_id``. * ``:return:`` Authenticated Seeker CV file """ pdf_file= CV.objects.get(id=1).pdf_file return HttpResponse(pdf_file) Doing a GET request with python requests library, I am getting the following data: '...0000000123 65535 f\r\n0000000124 65535 f\r\n0000000125 65535 f\r\n0000000126 65535 f\r\n0000000127 65535 f\r\n0000000128 65535 f\r\n0000000129 65535 f\r\n0000000130 65535 f\r\n0000000131 65535 f\r\n0000000132 65535 f\r\n0000000133 65535 f\r\n0000000134 65535 f\r\n0000000135 65535 f\r\n0000000136 65535 f\r\n0000000137 65535 f\r\n0000000138 65535 f\r\n0000000139 65535 f\r\n0000000140 65535 f\r\n0000000141 65535 f\r\n0000000142 65535 f\r\n0000000143 65535 f\r\n0000000144 65535 f\r\n0000000145 65535 f\r\n0000000146 65535 f\r\n0000000147 65535 f\r\n0000000148 65535 f\r\n0000000149 65535 f\r\n0000000000 65535 f\r\n0000032441 00000 n\r\n0000032871 00000 n\r\n0000235049 00000 n\r\n0000235493 00000 n\r\n0000236007 00000 n\r\n0000236479 00000 n\r\n0000432257 00000 n\r\n0000432285 00000 n\r\n0000432726 00000 n\r\n0000647350 00000 n\r\n0000647920 00000 n\r\n0000648462 00000 n\r\n0000648763 00000 n\r\n0000661917 00000 n\r\n0000661961 00000 n\r\n0000662439 00000 n\r\n0000778958 00000 n\r\n0000778986 00000 n\r\n0000798973 00000 n\r\ntrailer\r\n<</Size 169/Root 1 0 R/Info 36 0 R/ID[<B3EBF57233FC8C4C9A30C5ED4E046BAA><B3EBF57233FC8C4C9A30C5ED4E046BAA>] >>\r\nstartxref\r\n799587\r\n%%EOF\r\nxref\r\n0 0\r\ntrailer\r\n<</Size 169/Root 1 0 R/Info 36 0 R/ID[<B3EBF57233FC8C4C9A30C5ED4E046BAA><B3EBF57233FC8C4C9A30C5ED4E046BAA>] …