Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to pass an instance of a class defined in one view to another view in Django
Is it possible to pass an instance of a class defined in one view to another view in Django? I tried using session and am able to pass attributes but not able to pass a method. Ideally, I'd like to pass the class instance to session directly but I get an error saying 'Object is not JSON Serializable' More context, I have 2 views. One renders a page for each user. It also declares a class (MyClass) with a method get_response() that returns a response based on an input text. def display_user(request, pk, slug): obj = MyClass(...) ... request.session['obj_name'] = obj.name request.session['obj_method'] = obj.method(input_text) # <-- how to pass method to session return render(request, 'page.html', context = {...}) I have a view that I can make api calls to get the response from the method of the class defined above. def obj_api(request, pk, slug): obj_name = request.session['obj_name'] # this works if request.method == 'POST': input_data = json.loads(request.body.decode('utf-8')) response = obj.get_response(input_data) # <-- how to get method from session ## response = request.session['obj_method'](input_data) ... return JsonResponse(response_data, status=200) Any help would be appreciated. -
linking button to required html using django python
I am trying to build a web page, where if I am having 2 buttons I can refer to different links linked to them. I have tried multiple to pull info of clicked button of form, javascript,ahref somethings not working right. Currently I am trying this code: for views def indiCountData(request): if request.POST.get('US'): (code inside working) return render(request,'india.html',context) elif request.POST.get('India'): (code inside working) return render(request,'india.html',context) for html <button onClick="myOnClickFn()">US</button> <script> function myOnClickFn(){ document.location.href="us.html"; } </script> <button onClick="mynClickFn()">India</button> <script> function mynClickFn(){ document.location.href="india.html"; } </script> for url if use this path('',views.home,name='home'), path('us.html',views.indiCountData,name=''), path('india.html',views.indiCountData,name=''), The view covi.views.indiCountData didn't return an HttpResponse object. It returned None instead. if use this path('',views.home,name='home'), path('',views.indiCountData,name='us'), path('',views.indiCountData,name='india'), 404 error code Please guide I am confused here your answers are much appreciated. -
How to render pdf file as HTMl pages using pagination Django from django views?
I has a book pdf in my static files.I want to write a view that reads this book.pdf and renders this pdf as html pages using django pagination concept.Is it possible to perform it.please help. -
MultipleObjectsReturned at / get() returned more than one City -- it returned 2
I am new to Python and have inherited the code base from another developer. I am getting a MultipleObjectsReturned at / get() returned more than one City -- it returned 2! error. In the code below, I changed the get to filter and checked that there are no duplicates in the database. context['count_promotions'] = count_promotions = promotions.count() count_cities = 0 count_products = 0 for promotion in promotions: for location in promotion.store.all().values_list('city__name', flat=True).order_by('city__name').distinct('city__name'): count_cities += 1 primary_key = City.objects.filter(name__icontains=location).pk province = Region.objects.filter(city__name__icontains=location) new_text = location.replace(',', '') almost_finished = new_text.replace('&', '') finished = almost_finished.replace(' ', '-') store_locations.append({ 'pk': primary_key, 'city' : finished, 'province' : province.name, }) What else can I check to resolve the issue? Thanks in advance. -
django: How to put date value from database to "input type='date'"?
why is it i cant put value from my database to input type date? even though my query is correct? {% for feedback in feedbacks %} <input name="datef" value="{{feedback.dateSubmitted}}" type="date"> {% endfor %} this is my views.py feedback = obj.objects.all() print(feedback) this is the result for print <QuerySet [<TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords: mystudent>]> my models.py class TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords(models.Model): ..... dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) ..... the result in my webview -
Which is the best way to build an online code editor web application?
I am planning to build a leet code model website for my project. What is the best code editor I can embed into my web application. I am planning to build my application using Django and saw a recommendation that django-ace package can be used to embed Ace- editor into the web application. In that case, how will I able to run the code entered into the code editor? While researching about it , I found some concepts like sandbox , docker. Can someone suggest which is the best way to implement this project as I am new to software development? Thank you. -
register() missing 1 required positional argument: 'auth_user'
from django.shortcuts import render def register(request, auth_user): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] auth_user = auth_user.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) auth_user.save() print('user created') return redirect('/') else: return render(request,'register.html') -
Exception Value: 'QuerySet' object has no attribute 'password'
I'm getting an error Query set object has no attribute 'password'.Can any one please help me how to compare user entered password with return <QuerySet [<Customer: Customer object (42)>]> query set. Please find the below views.py for login. def login(request): if request.method == 'GET': return render (request, 'login.html') else: email = request.POST.get('email') password = request.POST.get('password') print(email,password) #Now we will try to match user entered email ID and search it in db(here we Can't use pass because it is in ecrypted mode we can see from admin panel # to filter result we can use Customer.objects.filter which will return match in list form but we want a single object so better is to use get # Customer.objects.get(email=email)) #drawback of get is that if result is matched then good else it will give error. login_customer = Customer.objects.filter(email=email) print(login_customer) print('-------') error = None if login_customer: print(email) flag = check_password(password, login_customer.password) #if user email ID is exit then we'll Check his password.:) if flag: return redirect('home') else: print(email, password) error = 'Entered Email ID OR Password is incorrect' return render(request, 'login.html',{'error':error}) customer.py(models): from django.db import models ##Customer Model Creation. # Create your models here. class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = … -
Incomplete Context in Template due to ManyToManyField
I have a beginners question, I am trying to debug and understand the reasons why my context is not showing in the template. I have followed a tutorial to show PDF invoices in the Django Admin but there seems to be something off with my code which I have been battling for a while. I want help to know what could be wrong with my code. So, to summarize the issue I have Project where there are 3 models: Item, OrderItem and Order. The Order has a Many-to-Many relationship with OrderItem and the OrderItem has a Foreign Key with Item. In the template, I am trying to loop between the Order.Items which is items = models.ManyToManyField(OrderItem) but it is not rendering any data. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only … -
How to send welcome emails when users log in to my website with django?
I want to send emails to my users when they log in for the first time with Python Django. How can I do that? -
Django CSRF cookie not being set inside iframe
Short story, I need my Django site to be used by a bunch third party sites. I was able to get the site to display inside iframes by using django-csp. But whenever I need any user to use a form, the main problem being the login, I get a CSRF verification error that's caused because the csrftoken cookie is not being created when the page is loaded inside an iframe. Also, I suspect any AJAX request made by the site will also fail as they required CSRF validations. I have already tried the following settings: CSRF_TRUSTED_ORIGINS = ['mydomain.com', 'examplethirdparty.com'] CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_SECURE = True It still doesn't work, I have read the Django documentation regarding CSRF and I found nothing else about this matter. I know I can disable CSRF protection but that's not an option for me. I'd greatly appreciate any suggestions to solve this. -
How can I validate data to be posted on a table with reference to the same table?
While creating donation I want to check whether the data with same donor_id exists or not. If data don't exists then create donation else if there is data then get the latest donated date and validate whether the latest donated is greater then 3 months or not (if latest donated date exceeds three month then create donation else display message with donation cannot be made.) Code of models.py from django.db import models GENDER_CHOICES = ( ('M', 'MALE'), ('F', 'FEMALE'), ('O', 'Others'), ) BLOOD_GROUP_CHOICES = ( ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ('AB+', 'AB+'), ('AB-', 'AB-'), ) class Donor(models.Model): first_name = models.CharField(max_length=20) middle_name = models.CharField(max_length=20, blank=True) last_name = models.CharField(max_length=20) blood_group = models.CharField(choices=BLOOD_GROUP_CHOICES, max_length=3, null=True) gender = models.CharField(choices=GENDER_CHOICES, max_length=1) email = models.EmailField(blank=True) mobile_number = models.CharField(max_length=15) telephone_number = models.CharField(blank=True, max_length=15) date_of_birth = models.DateField() def __str__(self): return self.first_name + ' ' + self.last_name class Donation(models.Model): donor = models.ForeignKey(Donor, related_name='donor_name', on_delete=models.CASCADE) date_of_donation = models.DateField() donation_address = models.CharField(max_length=200) def __str__(self): return self.donor.first_name code of views.py from django.shortcuts import render, redirect from .forms import DonorForm, DonationForm from .models import Donor, Donation from datetime import datetime def donorPage(request): donors = Donor.objects.all() context = {'donor': donors} return render(request, 'donor/donor_page.html', context) def createDonor(request): form … -
How can i use middleware decorator for class-based view in djabgo?
How can i use middleware decorator for classbased view? class APIViewMixin(): apiMiddleware = decorator_from_middleware(APISecretMiddleware) @apiMiddleware def dispatch(*args, **kwargs): return super().dispatch(*args, **kwargs) class ThemesView(APIViewMixin, View): def get(self, request, id= None, *args, **kwargs): if (id!= None): serializer = vocabulary.customserializers.ThemesSerialiser(showWords=True); return HttpResponse(serializer.serialize([vocabulary.models.Theme.objects.get(pk= id)]), content_type='application/json') else: serializers = vocabulary.customserializers.ThemesSerialiser(showWords=False); return HttpResponse(serializers.serialize(vocabulary.models.Theme.objects.all()), content_type='application/json',) this doesnt work -
Removing unused lookup_field generated from router on viewset
I have a viewset on a "/me" endpoint that doesn't require a lookup_field for detailing, as it uses the current request user for filtering, retrieving a single result. class ClientProfileDetail( mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet ): permission_classes = [IsOwnerOrAdmin] queryset = ClientProfile.objects.all() serializer_class = ClientProfileSerializer def get_object(self): queryset = self.get_queryset() obj = get_object_or_404(queryset, pk=self.request.user) return obj I'm registering the viewset using the default router: router.register(r"me", ClientProfileDetail) But even though i have no use for the on the URL, the router register these URLs: profile/ ^me/(?P<pk>[^/.]+)/$ [name='clientprofile-detail'] profile/ ^me/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='clientprofile-detail'] My question is: How can i remove the (?P<pk>[/.]+)/$ on my routes Overriding get_object() as explained here: RetrieveAPIView without lookup field? didn't work -
How to add an option to pdf files with Order model context in Django Admin
I have a beginners question, in my Django E-commerce Project, I want to add an Option to include Order details so that I can print them as Invoices. I have 3 models: Item, OrderItem and Order. The Order has a Many-to-Many relationship with OrderItem and the OrderItem has a Foreign Key with Item. I have found weazyprint that help do the trick but I am unable to include the correct context so I need advice in including the Order to appear in template Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) keywords = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) timestamp = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, unique=True, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) I have a problem in the views it is not correct so I need assistance in it @staff_member_required def admin_order_pdf(request, order_id): order = --------------------------------> having difficulty wiriting the right code for the template html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') template … -
Django-allauth login/signup in one view
I am working on a django project and i would like to have one website page called login_register where the user can see the login form and click on a button to change that form to the sign up form using javascript. So i am stuck on finding out how to make this work and have login and signup forms on one page. Thanks in advance! -
Trouble uploading Django to production w/ Digital Ocean Apps, "collectstatic no input" error
I'm trying to upload my django app to a production server using Digital Oceans Apps. However I keep getting this error and I've tried everything. I see that in the log below, there's an $ heroku config:set DISABLE_COLLECTSTATIC=1, I registered this app as heroku git before but never put it into production and just now have removed all traces of Heroku. I'm baffled at why I'm getting this error. Below are settings.py and my Digital Ocean log #settings.py """ Django settings for stockbuckets project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY_DJANGO_STOCKBUCKETS') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'dpd_static_support', 'channels', 'channels_redis', 'bootstrap4', 'blog', ] MIDDLEWARE = [ … -
Am new to web development using python and want to know the best framework to use
i have been using PHP for backend web development and now I want to try using a python framework, which python framework will you recommend to start learning and why? -
Django/allauth: Can you add oauth mid-project easily?
If I start my project with allauth but don't use the oauth (Google, Facebook), can I easily add oauth after there are real users? Or is it one of those things where you have to fuss with the database manually? -
Django urls for Website not pointing to the correct page
I am using django to help create a website. The problem is when I attempt to switch from page to page the page can't be found and the url reads: http://127.0.0.1:8000/mentorPage/ http://127.0.0.1:8000/mentorPage/mentorPage/ As I click on the mentorPage link multiple times. I have attached my urls code below and was wondering if anyone could tell me why this is happening. from django.urls import path, include from . import views from django.views.generic import ListView, DetailView from webapp.models import UE # Create your views here. app_name = "main" urlpatterns = [ path('', views.home, name = 'home'), path('home', views.home, name = 'home'), path('resourcePage/', views.resource, name = 'resource'), path('mentorPage/', views.mentorPage, name = 'resource'), path('aboutMePage/', views.aboutME, name = 'resource'), ] -
progress bar showing incorrect percentage
i followed a tutorial on how to implement a file upload progress bar with django using js but the problem is that the progress bar is reaching 100% before the file completed uploading this my uploader.js function check_ex() { var fullPath = document.getElementById("id_video").value; if (fullPath) { var startIndex = fullPath.indexOf("\\") >= 0 ? fullPath.lastIndexOf("\\") : fullPath.lastIndexOf("/"); var filename = fullPath.substring(startIndex); if (filename.indexOf("\\") === 0 || filename.indexOf("/") === 0) { filename = filename.substring(1); } var x = filename.split('.').pop(); if (x != 'mp4') { alert(x +' format is not allowed in video input, use only (mp4) extensions'); location.reload() }; } } $(document).ready(function () { $("form").on("submit", function (event) { event.preventDefault(); check_ex(); var formData = new FormData($("form")[0]); $.ajax({ xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function (e) { if (e.lengthComputable) { document.getElementById("loading_btn").classList.remove("d-none"); document.getElementById("save_btn").classList.add("d-none"); document.getElementById("progressdiv").classList.remove("d-none"); var percent = Math.round((e.loaded / e.total) * 100); if (percent == 100) { document.getElementById("message_button").click(); } $("#progressbar") .attr("aria-valuenow", percent) .css("width", percent + "%") .text(percent + " %"); } }); return xhr; }, type: "POST", data: formData, processData: false, contentType: false, seccess: function () {}, }); }); }); im new in javascript and i couldn't understand why this function is giving me so much smaller percentage comparing to the … -
How to grab 10 most recently created profiles in django?
Well i am want to show most recent created profiles but i dont understand how can i grab them by queryset. I am adding some information if more information require than tell me i will update my answer with that information models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() class ProfileManager(models.Manager): def top_profile(self): top_profile = self.get_queryset().get(user=self.request.user) qs = UserProfile.objects.filter( user=top_profile ).order_by('-create_date')[:10] return top_profile -
Django Celery How to run function every 5 sec?
I want the function update() to run every 5 seconds. In this case, my function just prints a message to the console. For this I decided to use celery. I put the following code in a file settings.py and nothing happens when the server runs. What am I missing? Some code perhaps? from celery import Celery from celery.schedules import crontab app = Celery() app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-monday-morning': { 'task': 'accounts.views.update', 'schedule': timedelta(seconds=5), }, } -
How do I display an integer from a database object in Django?
I am a beginner in Django and coding in general. I know that this must be an easy thing to do but I have been struggling with this for days. This is my model: class Bal(models.Model): balance = models.IntegerField(default='5000') def __int__(self): return "{}, {}".format(self.pk, self.balance) View: def add_stock(request): import requests ... bala = Bal.objects.get(pk=2) ''' return render(request, 'stocktrader/add_stock.html', {'ticker': ticker, 'output': output, 'bala': bala}) in the html page: <h4>Balance: {{ bala }}</h4> The output on the web page is: Balance: Bal object (2) Where "Bal object(2)" is I need it to display a number. The table in the database has one 'balance' entry for 5000 and it has an id if 2. I just don't understand how to get the value of '5000' to display instead of 'Bal object (2)'. -
Wrap string in ReportLab table cell in Django
I've been trying to get my cell strings to wrap, the table gets too wide and out of screen. I know that using Paragraph automatically wraps text, but the problem is that I'm sending my data from multiple views so the table width and number of columns varies. class NewPDF(View): def get(self, request, *args, **kwargs): arr= [(p.nombre, p.apellido, p.tipo+'-'+p.numero_identificacion, p.telefono , p.email, p.direccion) for p in Persona.objects.all()] data = { 'titulo':'LISTADO DE PERSONAS', 'headings':('NOMBRE', 'APELLIDO', 'IDENTIFICACION','TELEFONO','EMAIL', 'DIRECCION'), 'query': arr } pdf = generar_pdf(request,data) return HttpResponse(pdf, content_type='application/pdf') And using it on ReportLab like this. As you see, I'm using the data I'm sending directly and I don't know how to apply paragraphs styles to the query data. canv = Canvas(buff, pagesize=A4) frame = Frame(0,0,width,height, leftPadding=30, bottomPadding=30, rightPadding=30, topPadding=30, showBoundary=1) personas = [] header = Paragraph(data['titulo'], titleStyle) headings = data['headings'] allpersonas = data['query'] t = LongTable([headings] + allpersonas) t.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ] )) personas.append(t) frame.addFromList(personas,canv) And the table looks like this. Table Any help to get around this is appreciated. If I'm missing something, please tell me and I'll add it to the post.