Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to insert variable into path() kwargs
I'm trying to pass a boolean flag to my view: def lesson_detail_view(request, number, **kwargs): pass The documentation has an example of passing in kwargs, but only as hard coded. path('blog/<int:year>/', views.year_archive, {'foo': 'bar'}) My problem is getting the variable into the url pattern. I've tried to insert a variable the same way the path variables work with angle brackets, but it's not working. path('lesson-<number>/', views.lesson_detail_view, kwargs={'show_popup': '<show_popup>'}, name='lesson_detail'), Am I barking up the wrong tree? I feel like this should be pretty straight forward, but I'm not finding anything. -
render() got an unexpected keyword argument 'renderer' or crispy form
add article views.py error add article html -
Some of my HTMLs are not loading CSS file
I have a main.css file where all my styles are and some of my html files are loading them, but not all of them. All my html files extends base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <link href="static/css/main.css" rel="stylesheet" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/2a770f4891.js" crossorigin="anonymous"></script> <title>{% block title %}E-Learning{% endblock %}</title> </head> <body> <input type="checkbox" id="check"> <nav class="nav"> <label for="check"> <i class="fas fa-bars" id="sidebar_btn"></i> </label> {% if user.is_authenticated %} {% if user.first_name != '' or user.last_name != '' %} <b class="top-menu" style="font-size:20px; margin-right:5px;"> Hello, {{user.first_name}} {{user.last_name}}</b> {% else %} <b class="top-menu" style="font-size:20px; margin-right:5px;">Hello, {{ user.username }}</b> {% endif %} {% else %} {% endif %} {% if user.is_authenticated %} <a href="{% url 'logout' %}" class="top-menu">Log out</a> {% else %} <a href="{% url 'login' %}" class="top-menu"> Log In </a> <a href="{% url 'register' %}" class="top-menu">Register </a> {% endif %} </nav> <div class="sidebar"> <a href="{% url 'subject_new' %}" > <span> Add </span></a> </div> <main class="content"> {% block content %} {% endblock content %} </main> </body> </html> and for example my register.html extends base.html (with all css files) just fine {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} … -
ImageField URL is incorrect when reuploading new file or same to the same input form
If I create new listing and upload an image, there is no issue. But When I try to reupload new or same image, it does not get uploaded and its url is pointing to not found file (media/FILENAME) If I just create and, the image gets uploaded and stored at the right directory (media/images). As soon as I try to upload the same or new image,the image does not get uploaded and its url is incorrect or pointing to the nonexistent address (media/FILENAME) My model class Listing(models.Model): title = models.CharField(max_length=64) image = models.ImageField(blank=True, null=True, upload_to="images/") created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Listing {self.id}: {self.title}" def create(request): if request.method == "POST": form = NewListingForm(request.POST, request.FILES) listings = Listing.objects.all() if form.is_valid(): title = form.cleaned_data["title"] image = form.cleaned_data["image"] if image is None: image = "" try: listing = Listing.objects.get(title=title) except Listing.DoesNotExist: listing = None if listing is None and form.cleaned_data["edit"] is False: new_listing = Listing.objects.create(title=title, image=image) new_listing.save() return HttpResponseRedirect(reverse("auctions:listing", args=(new_listing.id,))) elif form.cleaned_data["edit"] is True: existing_listing = Listing.objects.filter(title=title) existing_id = Listing.objects.get(title=title).id existing_listing.update(title=title, image=image) return HttpResponseRedirect(reverse("auctions:listing", args=(existing_id,))) else: return render(request, "auctions/create.html", { "form": form, "error": "Duplicate Item.", "existing_title": title, }) else: return render(request, "auctions/create.html", { "form": NewListingForm() }) else: return render(request, "auctions/create.html", { "form": NewListingForm() … -
Django-wkhtmltopdf - dynamic templates
I'm wondering if it is possible to dynamically assign the template_name based on data provided to my class-based view using a form? for example I have the following form page: views.py def form_generate_pdf(request, project_id): """Form to collect data to insert into PDF""" project = Project.objects.get(id=project_id) if request.method == 'POST': form = PDFForm(request.POST) if form.is_valid(): request.session['field1'] = form.cleaned_data.get('field1') return redirect('myapp:generate_pdf') else: form = PDFForm() context = { 'project': project, 'form': form } And the page that generates the PDF: views.py class Generate_PDF(PDFTemplateView): """Generate a PDF using the values from form_generate_pdf""" filename = "test.pdf" # I want the field below to be dynamic depending on the value of field1 from the view form_generate_pdf template_name = "myapp/pdf.html" cmd_options = { 'page-size': 'Letter', 'viewport-size' : '1920x1080', 'footer-left' : '[page]/[topage]', 'no-outline' : True, } def get_context_data(self, **kwargs): context = super(Generate_PDF, self).get_context_data(**kwargs) field1 = self.request.session['field1'] context['field1'] = field1 } I would say I'm intermediate with django but I'm still fairly new to python and django in general (~5 months of playing now), I don't seem to have enough understanding to figure out how to insert some logic into the Generate_PDF class to programatically select the template type. Something like: if field1 = 'this': template_name = 'myapp/pdf_1.html' … -
How to validate data entered in the sign up form created in Django?
I have created a registration form using the class models.User (refer) in Django as follows: from Django.shortcuts import render, redirect from django.contrib.auth.models import User def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] if password == confirm_password: # some code user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('login') else: return redirect('register') return render(request, 'register.html') My problems: Now I want to make Full Name as optional but all other fields as required, also I want to apply length constraint on my fields, how can I do that? As this is an inbuilt model (class models.User), I am not sure how to set blank=True or use max_length for any field. Also I want to remove the spaces (if any) at the end and beginning of the entered data, before saving it using user.save() (e.g. if someone entered the name as " abc efg " I want to save it as "abc efg"). Basically, I want to use .is_valid() feature of the Django forms. I even tried doing that as: from django.shortcuts import render, redirect from django.contrib.auth.models import User def register(request): if request.method == 'POST': form = User(request.POST or None) if form.is_valid(): #my code … -
How to check for user authentication in Django's class-based view with get_context_data
When using function based views in Django, I normally would check for user authentication with: if not self.request.user.is_authenticated: return HttpResponseRedirect('/path/to/redirect') Now I am trying to use Class based views instead but I don't know how to implement the authentication if I am using the get_context_data() method instead of just get(). class MyGenericView(generic.ListView): model = models.MyModel template_name = 'path/to/template.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['foo'] = 'bar' return context -
Username from django auth_user as foreign key in another table
I have this model: models.py class InsertIP(models.Model): sourceIP=models.CharField(max_length=18) destinationIP=models.CharField(max_length=18) port=models.CharField(max_length=10) comment=models.CharField(max_length=200, null=True, blank=True) class Meta: db_table="fw_rules" And I need to add column User which contains the name of user who creates the record. I need to create foreign key from username from django auth_user Can you please help me? Thank you. -
Django: unable to pass queryset to CreateView
I want to pass a queryset to a form but, no matter the method which I use (get_initial, queryset, get_context_data) the query will not change. Model attribute: stock = models.OneToOneField('Stock', on_delete=models.CASCADE) The view: class YahooFinanceSymbolCreateView( YahooFinanceSymbolModel, YahooFinanceSymbolFormClass, GenericFormTemplateName, CreateView, ): success_url = reverse_lazy("stocks:index") def get_initial(self): # See which Stock YFS we have already added. already_registered_yfs = models.YahooFinanceSymbol.objects.all().values_list( "stock", flat=True ) # Exclude them from our Stock query. stocks = models.Stock.objects.filter(~Q(id__in=already_registered_yfs)) return {"stock": stocks} -
Django: How To Merge Two Object Lists With One List Appending To Every Fifth Element?
I am trying to make a list of posts wher every fifth post is an ad post so i want to make a list where every fifth element is from the ad list. i have tried something from this answer https://stackoverflow.com/a/34692876/14790632 What am i doing wrong with assigning these objects lists into one list views.py: def home(request, pk): #i tried this #post_list = [] #ad_list = [] #for p in Post.objects.all(): #post_list.append(p.Post) #for a in Ads.objects.all(): #ad_list.append(p.Ads) #and i have tried this below post_list = Post.objects.all() ad_list = Ads.objects.all() n = 5 iter1 = iter(post_list) post_ad_list = [] for x in ad_list: post_ad_list.extend([next(iter1) for _ in range(n - 1)]) post_ad_list.append(x) post_ad_list.extend(iter1) context = { 'posts': post_ad_list, } return render(request, 'new.html', context) -
Serializing model data leads to TypeError "Object of type ListSerializer is not JSON serializable"
I am not able to use the answers here or here for my own problem. I tried to customize the DRF tutorial part 3: models.py: class ProductData(models.Model): product_id = models.CharField('device_id', max_length = 20) price = models.DecimalField('price') product = models.ForeignKey(Product, on_delete = models.CASCADE) views.py: class ProductViewSet(viewsets.ViewSet): def list(self, request): data = [{"products": Product.objects.all(),}] results = ProductSerializer(data = data, many = True) if results.is_valid(): return Response(results) serializers.py: class ProductSerializer(serializers.ModelSerializer): product_id = serializers.CharField(max_length = 20) price = serializers.DecimalField(max_digits = 10) product = serializers.RelatedField(many=True) class Meta: model = ProductData fields = ["product_id", "price", "product",] I expected to get a JSON like response: { "product_id": "213123", "price": 2.99, "product": "bacon" } But I get the error: Exception Type: TypeError Exception Value: Object of type ListSerializer is not JSON serializable -
List_editable in django-django admin when check a boolean field modify other tables in database
I want to ask a question about the list_editable column in django-admin. If I have something like this: class fooAdmin(admin.ModelAdmin): list_display = ('name', 'age', 'boolean_field') list_editable = ('boolean_field') is it possible that when i enable (or disable) this list_editable field i trigger something that modify other table in database? e.g. if boolean_field became checked and I save it, automatically add or delete a row in another table? Thanks in advance. -
ValueError: The 'image' attribute has no file associated with it. when testing a model with a NULLABLE image field
I'm testing a model called Category that looks like this: class Category(models.Model): image = models.ImageField(upload_to='images', null=True, blank=True) title = models.CharField(max_length=200, unique=True, blank=False, null=False) As you can see the image field is nullable but when I try to create a Category instance in my TestCase Im getting the following error: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) ValueError: The 'image' attribute has no file associated with it. Here's the test: def setUp(self): self.category = Category.objects.create(title='test_category') I already tried creating it like this: Category.objects.create(title='test_category', image=Null) But it didn't work. -
I need to create a formatted reference code in django. the increment should be based on the category. any idea on how to this
class Category(models.Model): categories = models.CharField(max_length=100) shortterm = models.CharField(max_length=20, null=True, blank=True) class Requestor(models.Model): id = models.AutoField(primary_key=True) date_filed = models.DateTimeField(auto_now_add=True, null=True, verbose_name='date_filed') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, verbose_name="Category") **reference_code = models.CharField(max_length=500, verbose_name=( 'Reference'), default='Auto Assign', blank=True)** The result for the reference code should be like this. |id|date_filed|category|reference_code| |1 |01012021 |local |lsp-01012021-1| |2 |01012021 |foreign |fsp-01012021-1| |3 |01012021 |local |lsp-01012021-2| -
Getting <django.db.models.query_utils.DeferredAttribute object at 0x7fca8f1d3d50> in model fields instead of actual values
In the code below, I've created an endpoint to create a user in the database. class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer queryset = Clients.objects.all() @action(detail=True, methods=["POST"]) def create_client(self, request, pk=None): Clients.objects.create(client_id=pk, username=Clients.username, password=Clients.password, first_name=Clients.first_name, last_name=Clients.last_name, address=Clients.address) return Response("User Created", status= status.HTTP_200_OK) This indeed creates an instance in the the model, but each field contains texts similar to "<django.db.models.query_utils.DeferredAttribute object at 0x7fca8f1d3d50>" instead of the actual values. I used Postman as a tool, and is how I created this instance, if I just use a 'Post' method on the url ../client/ instead of ../client/pk/create_client/ it returns the correct values. -
Conditionally insert a piece of Django template with HTML code into my template using Javascript
I am trying to create a template with Django to use with all the pages I have in my project. All the pages display similar tables which makes it easier but some of them require an extra check or two. So in writing this one-size-fits-all template, I would like to have this piece of code if it is one type of page: {% if not package_check %} <p style="color:red">Package not found, so script did not run. Install package and try again</p> {% elif count|length %} <!-- rest of html template --> {% endif %} Otherwise, I would like to have this piece of code: {% if count|length %} <!-- rest of html --> {% endif | length %} Since they are very similar I am wondering if it's possible (and how can I do it) to insert it into the HTML with Javascript when loading the page and make it test for the Django variables in the template tags. -
How to send a query from the frontend (React) to Django with Rest Framework
i want to receive a particular input from the frontend react textarea to perform a certain function in django backend. Anybody to help. i want to send a input's from the textarea to my backend React Frontend import React, { Component } from 'react'; import axios from 'axios'; class QueryBuilder extends Component{ render() { return ( <div> <form> <textarea cols="100" rows="20" name="text" /> <br /><br /> <button>Execute Query</button> </form> </div> ) } } export default QueryBuilder; import React, { Component } from 'react'; import axios from 'axios'; class QueryBuilder extends Component{ render() { return ( <div> <form> <textarea cols="100" rows="20" name="text" /> <br /><br /> <button>Execute Query</button> </form> <br /><br/> </div> ) } } export default QueryBuilder; views.py from django import db from django.shortcuts import render, HttpResponse from rest_framework import generics from .models import Test from .serializers import TestSerializer from pymongo import MongoClient from ast import literal_eval from rest_framework import viewsets, permissions # from .models import Test # from .serializers import TestSerializer #Test Viewset class TestViewset(viewsets.ModelViewSet): client = MongoClient() db = client.test # collect = db['state_entry'].find({}) queryset = db['queryTest_test'].find({}) permission_classes = [ permissions.AllowAny ] serializer_class = TestSerializer ---------- Serializer.py from rest_framework import serializers from queryTest.models import Test # Test Serializers … -
Django import Error(from extras.plugins import PluginConfig)
I'm new to Django and I try to develope a plugin for NextBox using this framework. To get familliar with it I'm using documentation from NextBox for this. My Problem is that I try to import a class as shown in the tutorial I get an Error that the package is unkown. When I want to install the package via PyCharm it seems to be the wrong one. Maybe someone of you can help me? Doc: https://netbox.readthedocs.io/en/stable/plugins/development/ from extras.plugins import PluginConfig class NextBoxUIConfig(PluginConfig): In the IDE it says that extras is unkown after installing the package, .plugins is unkown as well as PluginConfig -
Find entities for specific user through multiple tables in Django Admin
I searched through stackoverflow about this particular scenario, but could not find a concrete answer, so i'm posting this. So my problem is that i need to display specific records to a specific user in Django Admin. I'm aware that i can get the concrete user through the get_queryset method extracting it from the request object. But the issue is i need to look through 6 tables to get to the information about the user. For example, if the records i need to display come from a Recommendation table, it has a reference to TableA, which has a reference to TableB .... which has a reference to TableF which has a reference to the User. I'm aware i could do this by executing a plain SQL query with multiple joins, but my guess is that there must be a pythonic or Django sophisticated solution to this. But i may be wrong. The model is unfortunately not in my control, nor i can change it, so i'm left to work with the state of the model that there is. Thanks in advance. -
How to access child class object that inherits parent class?
I have parent class and child class, that inherits parent class. And that is okay, I can iterate with for loop. Now I want to access child class (example: 'details = models...' So basically, I'm confused how we inherits stuff from child class inside the same loop... views.py from django.views import generic from . models import Category from django.shortcuts import render class CategoryListView(generic.ListView): model = Category template_name = 'category_list.html' models.py from django.db import models import uuid class Category(models.Model): name = models.CharField(max_length=100, help_text='Category name') def __str__(self): return self.name class Meta: verbose_name_plural = 'Categories' class Product(models.Model): product_name = models.CharField(max_length=255, help_text='Product name') # product_spec = models.TextField(max_length=5000, help_text='Product specs') product_type = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) def __str__(self): return self.product_name category_list.html {% extends 'base.html' %} {% block body %} {% for page in category_list %} <li>{{ page.name }}</li> <li>{{ page.product_name }} #<---------------- Now this is the point of # my problem, I want to get product name from child class, this returns empty <li> {% endfor %} {% endblock %} -
Correct way to pass parameters to django view
I'm implementing the Rango project from the Tango with Django 2 book and I need to add a view that counts redirects to external pages for each page. I thought that a good way to do this is to use angle brackets in the url mapping to capture the id of the page by passing it as argument in the template, but later noticed that the book uses a different approach and I'm wondering which one is better and why? I don't like it that my solution doesn't use the request parameter, but it looks cleaner to me. My solution: URL path: path('goto/<int:page_id>', views.goto_page, name='goto'), Anchor: <a href="{% url 'rango:goto' page.id %}">{{ page.title }}</a> View: def goto_page(request, page_id): try: requested_page = Page.objects.get(id=page_id) requested_page.views += F('views') + 1 requested_page.save(update_fields=['views']) except Page.DoesNotExists: return redirect(reverse('rango:index')) return redirect(requested_page.url) Book's solution: URL path: path('goto/', views.goto_page, name='goto'), Anchor: <a href="{% url 'rango:goto' %}?page_id={{ page.id }}">{{ page.title }}</a> View: def goto_page(request): if request.method == 'GET': page_id = int(request.GET['page_id']) try: requested_page = Page.objects.get(id=page_id) requested_page.views += F('views') + 1 requested_page.save(update_fields=['views']) except Page.DoesNotExists: return redirect(reverse('rango:index')) else: return redirect(reverse('range:index')) return redirect(requested_page.url) -
How to get user's phone number from python social auth(google-oauth2)
I use python social auth and django rest framework. I want to fetch the user phone number. Settings SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_ID') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_SECRET') SOCIAL_AUTH_RAISE_EXCEPTIONS = False SOCIAL_AUTH_USER_MODEL = 'users.TransUser' SOCIAL_AUTH_GOOGLE_OAUTH2_USER_FIELDS = ['email', 'firstname', 'lastname', 'phone_number'] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/user.phonenumbers.read', 'profile', 'email', ] Ouput {'access_token': 'xxxxxxxx', 'email': 'xxxxxxxx, 'email_verified': True, 'expires_in': 3582, 'family_name': 'xxxxxxx', 'given_name': 'xxxxx', 'id_token': 'xxxxxx', 'locale': 'es', 'name': 'xxxxxxx', 'picture': 'xxxxx', 'scope': 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/user.phonenumbers.read ' 'https://www.googleapis.com/auth/userinfo.profile openid', 'sub': 'xxxxxx', 'token_type': 'Bearer'} but never phone number. I use user's phone number to registration it. I activated people APi in google console. Thx you -
django with postfix doesn't send email and doesn't raise an error
i have configured postfix as a null client on my machine and the configuration also seems to be working, as $ echo "test" | mail -s "test" -r "sender@domain.com" recipient@domain.com successfully delivers the email. however if i try to use it with django with the following settings: EMAIL_HOST = "localhost" EMAIL_PORT = 25 EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" DEFAULT_FROM_EMAIL = "sender@domain.com" SERVER_EMAIL = "sender@domain.com" the process get's stuck without an error being raised: from django.core.mail import send_mail from django.conf import settings send_mail(subject="test", message="test", from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=["recipient@domain.com"]) i can't figure out why this function get's stuck, the /var/log/mail.log file is also empty. Edit: Note, that sender@domain.com and recipient@domain.com are both valid adresses but i replaced them in this question. -
How to test if user can register and is redirected to home page?
I am writing tests in order to see if a user can register and if successful, is redirected to home page. I have created a class RegisterPageViewtest(TestCase): def setUp(self): self.register_url=reverse('register') self.user={ 'username':'username', 'password':'password', 'password2':'password', 'first_name':'first_name', 'last_name':'last_name', 'email':'email@gmail.com' } with a function: def test_user_can_register(self): response = self.client.post(self.register_url,self.user,format='text/html') self.assertEqual(response.status_code,302) However, when I run tests I get a response in a console: AssertionError: 200 != 302 How can I fix it? -
How To Make Every Fifth Post An Ad Post In Django
I am trying to allow users to sponsor a post to bring more clicks to there posts. I want to make every fifth post a post that is a sponsored post but if i try to just use divisible by in the templates and loop through ads then it will post all of the ads after the fifth post here is some code i have tried models: class Ad(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) views: def home(request, pk): context = { 'products': Post.objects.all(), 'ads': Ads.objects.all(), } return render(request, 'new.html', context) templates i have tried but don't work: {% for item in products %} //prints products {% if forloop.counter|divisibleby:4 %} {% for i in ads %} {% with it = forloop.parent.loop.counter|div:4 %}//this will give error //prints ad post {% endwith %} {% endfor %} {% endif %} {% endfor %}