Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Design Database Efficiently with several relations - Django (PostgreSQL)
I want to know the most efficient way for structuring and designing a database with several relations. I will explain my problem with a toy example which is scaled up in my current situation. Here are the Models in the Django database 1.) Employee Master (biggest table with several columns and rows) class Emp_Mast(): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) desgn_mast = models.ForeignKey("hr.Desgn_Mast", on_delete=models.SET_NULL, null=True) qual_mast = models.ForeignKey("hr.Qualification_Mast", on_delete=models.SET_NULL, null=True) office_mast = models.ManyToManyField("company_setup.Office_Mast", ref_mast = models.ForeignKey("hr.Reference_Mast", on_delete=models.SET_NULL, null=True) refernce_mast = models.ForeignKey("hr.Refernce_Mast", on_delete=models.SET_NULL, null=True) This is how the data is displayed in frontend 2.) All the relational field in the Employee Master have their corresponding models 3.) Crw_Movement_Transaction Now I need to create a table for Transaction Data that that stores each and every movement of the employees. We have several Offshore sites that the employees need to travel to and daily about 50 rows would be added to this Transaction Table called Crw_Movement_Transaction The Crw_Movement Table will have a few additional columns of calculations of itself and rest of the columns will be static (data would not be changed from here) and will be from the employee_master such as desgn_mast, souring_mast (so … -
Applozic Django Web Integration Unresponsive
My Current Goal Access the Applozic web demo through my application Final Goal Add a 1 to 1 chat to my Django web application using Applozic with the Fullview UI. Users are able to log-in to my website and chat with each other through the Fullview UI while still having the same navigation bar as my website and being on my website. Expected results Being able to open the demo through my application and send a test message Actual results When I open the demo through my application nothing happens when I press the Enter Chat button What I've tried Sample I downloaded the demo, started it and entered my applozic account information. The first box (that requires the application id) said 'applozic-sample-app', I left this as is. Next, I entered my Applozic email and password to log in, as seen below. [![enter image description here][1]][1] It worked and I was able to send messages to their sample account. [![enter image description here][2]][2] Initial Integration to Django Application Next I copied and pasted the fullview.html file into my django project's template directory, created a new view that shows that file, added the url to redirect to the view and started … -
Django next page and prvious page not working
In my Django admin the previous and next page button is not working.it always go to the else part of the code. I don't know what's the issue. On clicking it always go on the same page {% load admin_list %} {% load i18n %} {% if pagination_required %} <ul class="pagination"> {% if cl.has_previous %} <li><a href="?p={{ cl.previous_page_number }}">&laquo;</a></li> {% else %} <li class="active"><span>&laquo;</span></li> {% endif %} {% for i in cl.paginator.page_range %} {% if cl.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?p={{ i|add:"-1" }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if cl.has_next %} <li><a href="?p={{ cl.next_page_number }}">&raquo;</a></li> {% else %} <li class="active"><span>&raquo;</span></li> {% endif %} </ul> <p style="float:right; margin:10px;">{{ cl.paginator.count }} Projects</p> {% endif %} -
Django progressive web app gives an error in all browsers after caching files
I was following this tutorial to make my website a PWA website using django-progressive-web-app. However, when I opened the app from firefox I get the following error: Oops. The site at http://localhost:8000/ has experienced a network protocol violation that cannot be repaired. The page you are trying to view cannot be shown because an error in the data transmission was detected. Please contact the website owners to inform them of this problem. When I open from Safari I get this error: Safari Can't Open the Page SAfari can't open the page "http://localhost:8000/base_layout/". The error is: "Response served by service worker has redirections" (WebKitInternal:0) I don't have chrome so I can't tell what is the error there, also running it from private -Incognito- window would solve the problem (and clearing data) So the problem is clearly with the cached code How can i fix? My code settings.py: INSTALLED_APPS = [ ... 'pwa', ... ] ... # Pwa settings PWA_SERVICE_WORKER_PATH = os.path.join( BASE_DIR, 'static/chat/js', 'serviceworker.js') urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('webpush/', include('webpush.urls')), path('', chat_views.home, name="home"), path('', include('pwa.urls')), path('base_layout/', chat_views.base_layout, name="base_layout"), ... ] serviceworker.js (path: Orgachat/static/chat/js/serviceworker.js var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function (event) { event.waitUntil( caches.open(staticCacheName).then(function (cache) { return cache.addAll([ '/base_layout' ]); … -
django_hosts - NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name
Versions: Django 2.2.10 django-hosts 4.0 I have installed django_hosts successfully as per this documentation. I can successfully now access pages like https://blog.mysite.com However, the urls on the page are NOT resolved correctly. I have followed the example shown in the django_hosts official documentation. This is what my setup looks like: mysite/urls.py # imports etc. truncated for brevity # ... urlpatterns = [ path('', include(('home.urls', 'home'), namespace='home')), path('blog/', include('blog.urls', namespace="blog")), # ... ] home/urls.py from django.urls import path from django.conf.urls import include, url from .views import HomePageView, AboutView, TermsView, PrivacyView, \ sample, register, signin app_name = 'home' urlpatterns = [ path('', HomePageView.as_view(), name='index'), path('about', AboutView.as_view(), name='about'), path('terms', TermsView.as_view(), name='terms'), path('privacy', PrivacyView.as_view(), name='privacy'), path('sample', sample), path('register', register, name='register'), path('signin', signin, name='signin'), ] blog/templates/index.html <div class="container"> 116 <!-- Logo --> 117 <a class="logo" href="{% host_url 'home' host 'www' %}" style="text-decoration: none; font-size: 250%;"> 118 <img src="/static/assets/img/logo.png"> 119 My Site 120 </a> 121 <!-- End Logo --> -
AttributeError: module 'rest_framework.serializers' has no attribute 'serialize'
I am trying to serialize model instance as i can't reach out the url or the details of the 'followiing' model. from django.core import serializers from django.contrib.auth import authenticate from django.contrib.auth.models import update_last_login from rest_framework_jwt.settings import api_settings from django.core import serializers from rest_framework import serializers from urllib import request from rest_framework.permissions import AllowAny,IsAuthenticated from rest_framework import routers, serializers, viewsets from django.http import HttpResponse class UserSerializer(serializers.HyperlinkedModelSerializer): jsonfollowing = serializers.serialize('json', [ followiing ,]) class Meta: model = User fields = ('id','email','username','password','followiing','jsonfollowing') But i get the following error AttributeError: module 'rest_framework.serializers' has no attribute 'serialize' Does anybody know why? -
Django Data Migration
I want to write a data migration that read the records in the right order and delete the older records when the newer record was found I write the sql for this one. But I want to write data migration How can I write this my sql query is this ;with cte as ( select cid,count(*),max(id) as id from automation_irrig_record_data group by cid having count(*)>1 ) Delete from automation_irrig_record_data irrigRec where irrigRec.id in (select irrig.id from automation_irrig_record_data irrig JOIN cte on cte.cid=irrig.cid and cte.id !=irrig.id ) how can I write the Data migration my model name is automation_irrig_record_data id is my primary key cid is my field -
Create a user with a signal
I am trying to implement a signal to create a user when I create another model. When I create the sender object, the signal does not go through. Here is the code. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Spender from django.contrib.auth.models import User @receiver(post_save, sender=Spender) def create_user(sender, instance, created, **kwargs): spender = Spender if created: User.objects.create( username=spender.spender_username, first_name=spender.spender_firstname, last_name=spender.spender_lastname, email=spender.spender_email, password1=spender.spender_password1, password2=spender.spender_password2, ) User.save() -
Best way to store thousands of different files in Django Rest Framework?
I have to create an app in my DRF project that will be used to store thousands of different files (mostly PDF an Excel). The app will allow the user simple ACL requests and simple standard functionalities of a repository (see Recent files, move to different folders..). I've always used the hard disk of the server to store files in Django (through static root), I would like to have some feedback for this situation. Is it better to save them as binary on a databse? what approach would you suggest? In case of an external storage, which one is more functional for my situation? Thank a lot for your answers :) -
Save multiple values in one field (Django)
The problem: I have a model, which is referencing the basic User model of django. Right now, if I submit the form Django updates my database by replacing the existing data with the new one. I want to be able to access both of them. (In weight and date field) Models file: I saw other posts here, where they solved a problem by specifying a foreign key, but that doesn't solve it for me. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) date = models.DateField(auto_now_add=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Views file: This is where I save the data that I get from my form called WeightForm from django.shortcuts import render from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from .forms import WeightForm def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, … -
Graphite Browser "Exception Value: attempt to write a readonly database"
Well, i got into graphite and graphite-web and got stuck at the "Exception Value: attempt to write a readonly database" Error. I already tried chmod and chown at the db itself and im still getting this Error. File is under /opt/graphite/storage/graphite.db it got rwx-rwx-rwx (chmod 777) perms and i tried www-data as owner and put root back at it cause it got the same error. Environment: Request Method: GET Request URL: http://IP:8000/composer Django Version: 1.8.18 Python Version: 2.7.16 Installed Applications: ('graphite.account', 'graphite.browser', 'graphite.composer', 'graphite.dashboard', 'graphite.events', 'graphite.functions', 'graphite.metrics', 'graphite.render', 'graphite.tags', 'graphite.url_shortener', 'graphite.whitelist', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'tagging') Installed Middleware: ('graphite.middleware.LogExceptionsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/graphite/webapp/graphite/composer/views.py" in composer 27. profile = getProfile(request) File "/opt/graphite/webapp/graphite/user_util.py" in getProfile 35. return default_profile() File "/opt/graphite/webapp/graphite/user_util.py" in default_profile 51. 'password': '!'}) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 127. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get_or_create 407. return self._create_object_from_params(lookup, params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _create_object_from_params 439. obj = self.create(**params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 348. obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save 734. force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 762. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in _save_table 846. result = self._do_insert(cls._base_manager, … -
Hy i have a problem in my django app sohow i can solve it you will see all of the requireddocuments in the desc
Hy guys i'm achraf chahin a beginner web developer so i have a problem in my django app so it's a school management system that give courses exercices also link of live streams but there is a problem in my app even if the file is stored in my static files it giving me file not found i don't know what is the problem here some pics [This Images][1] [1]: https://i.stack.imgur.com/62sZW.png [This Images][2] [2]: https://i.stack.imgur.com/L5zlO.png [This Images][3] [3]: https://i.stack.imgur.com/9OIaj.png [This Images][4] [4]: https://i.stack.imgur.com/jOHcA.png [This Images][5] [5]: https://i.stack.imgur.com/i1Nj7.png [This Images][6] [6]: https://i.stack.imgur.com/MzRDQ.png [This Images][7] [7]: https://i.stack.imgur.com/lWjV3.png please help your answers will really gonna help me and others like me a lot -
looking for the best economic solution to deploy a flask application on the web. if you have any suggestion (MVC flask with JWT token ) please advice
looking for the best economic solution to deploy a flask application on the web, and also wants to know the deployment process. I am a beginner in python and flask, if you have any good structural suggestion (MVC in the flask with JWT token ) for API will be helpful. -
Summing up total amount from multiple models in Django
The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code class FurnitureItem(models.Model): fur_title = models.CharField(max_length=200) fur_price = models.FloatField() fur_discount_price = models.FloatField(blank=True, null=True) fur_pictures = models.ImageField(upload_to='Pictures/', blank=True) label = models.CharField(choices=LABEL_CHOICES, max_length=1) category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24) fur_descriptions = models.TextField() slug = models.SlugField() date = models.DateTimeField(default=timezone.now) def __str__(self): return self.fur_title class FurnitureOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fur_ordered = models.BooleanField(default=False) item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.fur_title}" .... def get_final_fur_price(self): if self.item.fur_discount_price: return self.get_total_discount_fur_price() return self.get_total_item_fur_price() class FurnitureOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fur_items = models.ManyToManyField(FurnitureOrderItem) date_created = models.DateTimeField(auto_now_add=True) ordered_created = models.DateTimeField() fur_ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total_fur_everything(self): total = 0 for fur_order_item in self.fur_items.all(): total += fur_order_item.get_final_fur_price() return total class GraphicItem(models.Model): graphic_title = models.CharField(max_length=200) graphic_price = models.FloatField() graphic_discount_price = models.FloatField(blank=True, null=True) graphic_pictures = models.ImageField(upload_to='Pictures/', blank=True) label = models.CharField(choices=LABEL_CHOICES, max_length=1) category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24) graphic_descriptions = models.TextField() slug = models.SlugField() date = models.DateTimeField(default=timezone.now) def __str__(self): return self.graphic_title class GraphicOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) graphic_ordered = models.BooleanField(default=False) item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.graphic_title}" .... def get_final_graphic_price(self): if self.item.graphic_discount_price: return self.get_total_discount_graphic_price() return … -
i have erroe ith paginating in django
hi im trying to use django paginator but i get 404 error i want to reach to this url http://127.0.0.1:8000/products/2/?page=1 but i get 404 error where is the problem ?please help me views.py from django.core.paginator import Paginator, EmptyPage, InvalidPage def sort(request, value): category = Category.objects.all() if(value=='2'): products_list = Product.objects.all().order_by('price') elif(value=='3'): products_list = Product.objects.all().order_by('-price') elif(value=='4') : products_list = Product.objects.all().order_by('-id') elif (value == '5'): products_list = Product.objects.all().order_by('-view') paginator = Paginator(products_list,5) try: page=int(request.GET.get('page','1')) except: page = 1 try: products = paginator.page(page) except(EmptyPage,InvalidPage): products = paginator.page(paginator.num_pages) context = { 'products': products, 'category': category, 'value' : value } return render(request, 'shopPage.html', context) urls.py path('products/<value>', views.sort, name='sort'), shopPage.html <div> <ul> {% if products.has_previous %}> <li><a href="products/?page={{ products.previous_page_number }}">previous</a></li> {% endif %} {% for pg in products.paginator.page_range %} {% if products.number == pg %} <li class="active"><a href="products/?page{{ pg }}">{{ pg }}</a></li> {% else %} <li><a href="products/?page{{ pg }}">{{ pg }}</a></li> {% endif %} {% endfor %} {% if products.has_next %} <li><a href="products/?page={{ products.next_page_number }}">next</a></li> {% endif %} </ul> </div> -
Update multiple rows with Django (different ids) using different values for each id (as keys)
Let's say I have a model: I have some items: grocery = { status : True, fruits: ['1', '23', '55'], comments: {'1': "test", '23': "test2", '55': ""} I have a rough potential Django update query: Fruit.objects.all().filter(id__in=grocery.get('fruits')).update(status=grocery.get('status'), comment=grocery.get('comments')) I'm successfully updating the status but I want to dynamically update the comments so that if the Fruit object in question has, for example, id: 23, the fruit comment will be test2, or if the object has 'id: 55' it will be '' -
Django - Date problem in CRUD application
I'm using flatpickr for date informations in my Django application. The problem is when I want to update worker informations, in edit.html page default value of birth_date is not displaying correctly. For example, I've created worker Xen who was born in 01-05-1997, and click to update his name, in birth_date input it displays today's date. Here are my codes: forms.py class WorkerForm(ModelForm): class Meta: model = Worker fields = "__all__" widgets = { 'birth_date': DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class':'datetimefield'}) } models.py: class Worker(models.Model): ... birth_date = models.DateTimeField(blank=True, null=True) edit.html: ... <div class="form-group row"> <label class="col-sm-2 col-form-label">İşçinin doğum tarixi</label> <div class="col-sm-4"> <input class="datetimefield" type="date" name="birth_date" id="birth_date" value="{{ worker.birth_date }}" /> </div> </div> ... <script> window.addEventListener("DOMContentLoaded", function () { flatpickr(".datetimefield", { enableTime: true, enableSeconds: true, dateFormat: "Y-m-d H:i:S", time_24hr: true, locale: "az", }); }); </script> -
i got this Error TypeError at / Twitter() missing 4 required positional arguments: 'pwd', 'path', 'desc', and 'speed' i don't create models
i got this Error Twitter() missing 4 required positional arguments: 'pwd', 'path', 'desc', and 'speed' i don't create models import os from time import sleep from flask import Flask, render_template, request from selenium import webdriver from werkzeug.utils import secure_filename def Twitter(user, pwd, path, desc, speed): if user: driver = webdriver.Chrome( executable_path=r"C:\Users\pc\Downloads\chromedriver.exe" ) driver.get("https://twitter.com/login") user_box = driver.find_element_by_class_name( "js-username-field" ) user_box.send_keys(user) # password pwd_box = driver.find_element_by_class_name( "js-password-field" ) pwd_box.send_keys(pwd) login_button = driver.find_element_by_css_selector( "button.submit.EdgeButton.EdgeButton--primary.EdgeButton--medium" ) login_button.submit() sleep(speed) # Attach-Media img_box = driver.find_element_by_css_selector( "input.file-input.js-tooltip" ) img_box.send_keys(path) sleep(speed * 3) # Discription text_box = driver.find_element_by_id( "tweet-box-home-timeline" ) text_box.send_keys(desc) # Tweet tweet_button = driver.find_element_by_css_selector( "button.tweet-action.EdgeButton.EdgeButton--primary.js-tweet-btn" ) tweet_button.click() sleep(speed * 5) driver.refresh() driver.close() return 1 pass -
Email Verification in Django when a new user signs up
I am creating a user registration page for my website. I want to send an email verification mail to the mail the user inputs while registering. I tried many solutions but nothing seems to work for me. My code: views.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'Home/register.html', context) def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') return redirect('login') context = {} return render(request, 'Home/login.html', context) forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password1", "password2"] -
Django how the query GenericForeignKey relation(s)?
I want to display my users the content they have already brought by the "my_purchases" view (see below). For each object the user buy's a license is getting created and placed at the Licenses model: licensable_models = models.Q(app_label='App', model='model1') | \ models.Q(app_label='App', model='model2') class Licenses(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=licensable_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') license_holder = models.ForeignKey(User, verbose_name="License Holder", on_delete=models.CASCADE, null=True) paid_amount_usd = models.DecimalField(verbose_name="License Price (USD)", max_digits=8, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))], null=False) paid_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = "License" verbose_name_plural = "Licenses" ordering = ['-paid_date'] Creating a license and accessing the content after payment works fine! I expect that there is no buggy code but I currently don't really understand how I can create a query to grab all related objects the user has already brought and a license as been created. views.py def my_purchases(request): user = User.objects.get(pk=request.user.pk) template = 'App/my_purchases.html' if request.method == 'GET': list_my_purchases = sorted( chain( < how does this query have to look like? > ), key=attrgetter('paid_date'), reverse=True ) paginator = Paginator(list_my_purchases, 10) # Show 10 purchases per page page = request.GET.get('page') my_purchases = paginator.get_page(page) args = {'user': user, 'my_purchases': my_purchases, } return render(request, template, args) At each of my Model1 and Model2 (mentioned … -
Django password reset _getfullpathname error
I am trying to set up a password reset form but I get the following error after trying to send an email, weirdly I noticed that if I put email that doesn't match any of the emails provided by users it works, error only occurs when email matches one provided by a user. Error: TypeError at /password_reset/ _getfullpathname: path should be string, bytes or os.PathLike, not NoneType urls.py from django.contrib.auth import views as auth_views #import this urlpatterns = [ ... path('accounts/', include('django.contrib.auth.urls')), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), path("password_reset/", views.password_reset_request, name="password_reset"), ] views.py def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "registration/password_reset_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com' , [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("/password_reset/done/") password_reset_form = PasswordResetForm() return render(request=request, template_name="registration/password_reset_form.html", context={"password_reset_form":password_reset_form}) password_reset_form.html {% extends 'base.html' %} {% block content %} <!--Reset Password--> <div class="container p-5"> <h2 class="font-weight-bold mt-3">Reset Password</h2> <hr> <p>Forgotten your password? Enter your email address below, and we'll email … -
Django rest raising error "The submitted data was not a file. Check the encoding type on the form." to angualar Http Client
The are any solutions to the problem but m not able to find the root cause and also to mention no of the solution is working in my case. What I am trying to do is to upload a file to Django rest API from a angular Http Client Service. I am taking up the input form the user passing to the service at the end I have declared a type specific for the type of model I am creating an object for but I am not getting the same error again and again. I read some where that Django file uploader doesn't understand some char-set format but I still can't understand whats wrong with it. ``` var report = <CompleteReport> { title:'heelo', description:'sdfsdfs', author: 'report', article_upload_images: [uuid4(),], presentation_upload_images: [uuid4(),], report_article: article_object, report_image: image_object, report_podcast: podcast_object, report_presentation: presentation_object, report_video: video_object }; let headers = new HttpHeaders({ 'Accept': 'application/json' }); let options = {headers: headers}; return this.http.post<any>(url, report, options) -
How to pass Django view's data to jquery?
I want to pass page object data to jquery to print next and previous page. I used json.dumps(page), but it didn't workout, getting error. I used django pagination but on click next and previous buttons the page is reloading. so, i am trying using jquery. How to solve this, please suggest me. views.py: def render_questions(request): questions = Questions.objects.all() p = Paginator(questions, 1) page = request.GET.get('page', 1) try: page = p.page(page) except EmptyPage: page = p.page(1) return render(request, 'report.html', {'ques': page}) template.html: <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} <div class="divs"> <div class="questionscontainer"> {% for question in ques %} <h6>Q &nbsp;&nbsp;{{ question.qs_no }}.&nbsp;&nbsp;<input type="hidden" name="question" value="{{ question.question }}">{{ question.question }}</h6> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_a}}">&nbsp;&nbsp;&nbsp;A)&nbsp;&nbsp;{{ question.option_a }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_b}}">&nbsp;&nbsp;&nbsp;B)&nbsp;&nbsp;{{ question.option_b }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_c}}">&nbsp;&nbsp;&nbsp;C)&nbsp;&nbsp;{{ question.option_c }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_d}}">&nbsp;&nbsp;&nbsp;D)&nbsp;&nbsp;{{ question.option_d }}</label> </div> {% endfor %} </div> </div> <ul class="pagination"> <li><a class="button" id="prev">prev</a></li> <li><a class="button" id="next">next</a></li> <input type="submit" value="Submit" onclick="submitTest()" class="button"> </ul> </form> script: I need to get the page object in my script and i should print one by one question using next and previous buttons. $(document).ready(function(){ $(".divs .questionscontainer").each(function(e) { if (e … -
nginx directory forbidden using passenger_wgsi.py with django
I am trying to configure plesk with django nginx , I am using my vps with centos 8 and plesk 18 . I am getting 403 forbidden error . If a place index.html it works but it is not working with passenger_wsgi.py file this is my server log proxy_error logs 020/10/22 10:30:28 [error] 119522#0: *49 directory index of "/var/www/vhosts/xxx.com/httpdocs/djangoProject/" is forbidden, client: 162.158.165.181, server: xxx.com, request: "GET / HTTP/1.1", host: "xxx.com" error logs [Thu Oct 22 08:49:00.606752 2020] [ssl:warn] [pid 84873] AH01909: xxx.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Oct 22 08:49:00.632957 2020] [ssl:warn] [pid 84873] AH01909: xxx.com:443:0 server certificate does NOT include an ID which matches the server name passenger file code import sys, os ApplicationDirectory = 'djangoProject' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() nginx.conf user root; worker_processes 1; #error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; #pid /var/run/nginx.pid; include /etc/nginx/modules.conf.d/*.conf; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr … -
Django: Extending base.html in django admin
I've a base.html file which has vertical and horizontal menu-bar: Wherever I want to use that I just simply write: {% extends 'base.html' %} {% block content %} //html code {% endblock content %} But I don't know how to use the same file base.html from templates directory in djando admin. I want output like this: What I Tried: How to override and extend basic Django admin templates? How do I correctly extend the django admin/base.html template? Override Navbar in Django base admin page to be same as the base.html