Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template set all columns of a table at the same size
here is my templates, and what they display : template.html <div class="card"> <div class="card-body p-0"> <table class="table" style="width: 100%;"> <tbody> <tr> {% for field in fields %} {% if field != "rehabilitation" and field != "operation_type" and field != "subvention" and field != "history" %} {% if field|is_sortable == False %} <th bgcolor="gray" style="color: white; width: 5%">{{ field }}</th> {% elif field != "related_projects" and field != "history" %} <th bgcolor="gray" style="color: white; width: 5%"> <a href="?order_by={{ field }}" style="color: white">{{ field }}</a> {% include 'projects/functionalities/filter.html' %} </th> {% endif %} {% endif %} {% endfor %} </tr> <tr> <td>hey</td> <td>helllooooooo</td> <td>hello how are you ?</td> <td>yo</td> <td>teeeest</td> <td>aaa</td> <td>bbb</td> <td>cccccccccccccccccc</td> <td>wow</td> <td>testestestest</td> <td>test test test test</td> <td>i'm testing this</td> <td>whyyy does this don't work</td> <td>hello</td> <td>hey</td> <td>hey</td> </tr> </tbody> </table> </div> </div> filter.html <form class="d-flex flex-column bd-highlight mb-5" method="GET" action="{% url 'project-list' %}"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="search"> <div class="input-group-btn"> <button class="btn btn-success" type="submit"></button> </div> </div> </form> and here is what I have on my screen : As you can see, all the columns have a different size depending on what is written inside, and it makes my text input zones ugly. I would … -
foreign key serializer django rest framework
i have here small issue i just wanna return foreign key data using DRF my modles: class Trade(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) partsNum = models.IntegerField(null=True) class TradePart(models.Model): mainTrade = models.ForeignKey(Trade, models.CASCADE, null=True) data = models.JSONField() my serializers.py: class TradePartsSerializer(serializers.ModelSerializer): class Meta: model = TradePart fields = '__all__' class TradeSerializer(serializers.ModelSerializer): tradepart = TradePartsSerializer() class Meta: model = Trade fields = ['user', 'partsNum', 'tradepart'] my views.py if 'user' in request.query_params: userId = request.query_params['user'] user = User.objects.get(id=userId) trades = Trade.objects.filter(user=user) serializer = TradeSerializer(trades, many=True) return Response({'trades': serializer.data}, status=200) it shows this error: "'Trade' object has no attribute 'tradepart'" how can i fix this? i wanna return response including trade + tradepart for each trade -
Autofill foreign key field based on the slug in the URL
I'm working on a forum website where the user selects the game that they want to post about and writes the post. The problem is I don't want the user to select the game from the drop-down foreign key field. I want the foreign key field to populate itself based on the slug provided in the URL. models.py posts app class Post(models.Model): title = models.CharField(max_length=200, blank=True, null=True) user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() # need this field automatically filled out game = models.ForeignKey(Game, related_name="posts",null=True, blank=True,on_delete=models.CASCADE) slug = models.SlugField(allow_unicode=True, unique=False, null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk, "slug": self.game.slug, } ) models.py games app class Game(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("games:single", kwargs={"slug": self.slug}) urls.py posts app urlpatterns = [ path('', views.PostList.as_view(), name="all"), # need this slug to match the game path("new/<slug>/", views.CreatePost.as_view(), name="create"), ] views.py posts app class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('title','message','game') model = models.Post select_related = ('user', 'game') I'm guessing I need to grab the game object … -
DEBUG Django variable in production mode stays True [closed]
in my Django project in production mode, I always see debug messages. Yet the DEBUG debug variable stays true but in my code it's DEBUG=FALSE -
Is there a way to use {% block content %} where it only displays on certain @media's?
I'm currently doing a coding course and learning about block content and designing a website using django and bootstrap. I've got some code in a seperate HTML page that I'm inserting into other HTML pages using {% block content %} {% include 'html page' %}. I was wondering if there was a way within the {% -- %} or maybe a CSS @media style where the block content only shows on certain devices? Thanks! -
Django modelformset_factory widget validation
I'm having trouble understanding how form/model field validation works in Django 4.1.1. I want to use the models.CharField in my model with the stores = models.CharField(validators=[validate_comma_separated_integer_list], max_length=255) however when inputting and posting my formset no validation is carried out like it would be if I used models.EmailField and forms.EmailInput in the form/widget. I'm probably not understanding something properly but can't for the life of me work it out. Hopefully someone can point me in the right direction. Be as harsh as you like. forms.py - ServerFormSet = modelformset_factory( RequestServersStores, fields=("server_number", "store_numbers"), extra=1, validate_max=True, validate_min=True, labels={ 'server_number': 'Server Number', 'store_numbers': 'Store Numbers' }, widgets={ 'server_number': forms.Select( choices=server_choices ), 'store_numbers': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'comma separated list of store numbers e.g. 7,15,29' } ) }) views.py - ... elif request.method == 'POST': create_request = CreateUserForm(request.POST) server_formset = ServerFormSet(request.POST) if create_request.is_valid() and server_formset.is_valid(): request = create_request.save() for form in server_formset: server = form.save(commit=False) server.request = request server.save() models.py - class RequestServersStores(models.Model): objects = models.manager server_number = models.CharField(max_length=6) store_numbers = models.CharField(validators=[validate_comma_separated_integer_list], max_length=255) request = models.ForeignKey( CreateUserRequest, related_name='servers', on_delete=models.SET_NULL, null=True ) -
How can i ignore a many to many field in a Model. Because i cannot set to cache
I have a model that contains many to many field but in some code this model needs to be cached. but when i call the cache.set(model) django raises exception PicklingError: Can't pickle <class 'django.db.models.fields.related_descriptors.RelatedManager'>: attribute lookup django.db.models.fields.related_descriptors.RelatedManager failed i am using django 1.1 and python 2.7 -
Django: select columns across apps with the same foreign key
This is a follow-up question of this. I have app1/models.py: class A(models.Model): id = models.IntegerField(primary_key=True) text = models.CharField(max_length=20) class B(models.Model): fid = models.ForeignKey(A, models.CASCADE) text = models.CharField(max_length=20) class C(models.Model): fid = models.ForeignKey(A, models.CASCADE) text = models.CharField(max_length=20) and app2/models.py: from app1.models import A class D(models.Model): fid = models.ForeignKey(A, models.CASCADE) text = models.CharField(max_length=20) I wish to get A.text B.text C.text D.text where A.id == B.fid == C.fid == D.fid == 1. From the referred question, I was able to retrieve the first 3 columns using: B.objects.filter(fid=1).values('text', 'fid__text', 'fid__c__text') # B.text, A.text, C.text However I cannot get D.text using this query. I know I can do a filter on D and give it a manual calculation, but I'm looking forward to a more Djangoic way. (In case of a multi-match, product the rows, so if there are 2 rows in B that matches the given fid and 3, 4 for C, D, a total of 24 rows in returned.) -
access django channels' consumer class variables from outside
class ExampleConsumer(AsyncWebsocketConsumer): async def connect(self): self.id = 1 self.foo = 'bar' await self.accept() Is it possible to get all existing instances of ExampleConsumer, filter them by id and get foo value? Somewhere in a django view -
I want to show products by category using the . feature (.filter)
I am a beginner to Django, I want to show products by category using the .feature (.filter), I tried many times but I couldn't do it I hope someone can help me. Please write the code with explanation MODELS: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=200) slug = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): Category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=False, blank=False) slug = models.CharField(max_length=200, null=False, blank=False) description = models.TextField(max_length=350, null=False, blank=False) image = models.ImageField( null=False, blank=False) quantity = models.IntegerField(null=False, blank=False) def __str__(self): return self.name URLS: from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('f/<str:slug>', views.fd, name="fd"), path('category', views.category, name="category"), path('category/<str:slug>', views.categoryslug, name="categoryslug"), ] VIEWS: def home(request): context = { 'Pr': Product.objects.all(), } return render(request, 'pages/home.html', context) def fd(request, slug): context = { 'gfd' : Product.objects.get(slug=slug), } return render(request, 'pages/product.html', context) def category(request): context = { 'Categorys': Category.objects.all(), } return render(request, 'pages/category.html', context) Please write the code with explanation i need to show product by category -
how to get book_title written by author_name in for loop
how to get book name which is related author, i want author name in first column and book name in 2nd column, by querying authors.objects.all() i got author name buy i want book name which related to that author. models.py class Author(models.Model): author_name = models.CharField(max_length = 100) def __str__(self): return self.author_name class Book(models.Model): book_title = models.CharField(max_length = 100) desc = models.TextField(max_length = 300) authors = models.ManyToManyField(Author, related_name ='author') def __str__(self): return self.book_title def written_by(self): return ",".join([str(p) for p in self.authors.all() ]) views.py from .models import Author, Book # Create your views here. def manytomany(request): authors = Author.objects.all() book = Book.objects.all() # author_first = Author.objects.get(author_name='Mahesh') # book_author = author_first.author.all() book_author = Author.objects.get(id=1).author.all() context = { 'authors':authors, 'book': book, 'book_author':book_author, } return render(request, 'many-to-many.html', context) HTML <div class="col-lg-12"> <table class="table table-striped"> <thead> <tr> <th>Author Name</th> <th>Book</th> </tr> </thead> <tbody> {% for author in authors %} <tr> <td>{{ author.author_name }}</td> {% for j in book_author %} <td>{{ j }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> -
MultiValueDictKeyError at /signup
I am creating a login in page in django but facing the issue MultiValueDictKeyError at /signup Below is views.py ''' from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages def home(request): return render(request, "authentication/index.html") def signup(request): if request.method == "POST": uname = request.POST['uname'] fname =request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(uname, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, "Your account has been successfully created.") return redirect('signin') return render(request, "authentication/signup.html") def signin(request): return render(request, "authentication/signin.html") def signout(request): pass ''' Below is the signup.html ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Database</title> </head> <body> <h3>Sign Up</h3> <form action="/signup" method="post"> {% csrf_token %} <label for="">Username</label> <input type="text" id="uname" placeholder="Create a username", Required> <br> <label for="">First Name</label> <input type="text" id="fname" placeholder="Enter First Name", Required> <br> <label for="">Last Name</label> <input type="text" id="lname" placeholder="Enter Last name", Required> <br> <label for="">Email</label> <input type="email" id="email" placeholder="Enter Email address", Required> <br> <label for="">Password</label> <input type="password" id="pass1" placeholder="Create a Password", Required> <br> <label for="">Confirm your password</label> <input type="password" id="pass2" placeholder="Confirm your password", Required> <br> <button type="submit">Sign Up</button> </form> </body> </html> ''' Below is the Error Message MultiValueDictKeyError at /signup … -
Heroku and AWS, Disappearing images
I have built a heroku app that basically stores photos that I upload. I have set up an AWS account with an s3 bucket and I have also set up my IAM user for full access. When I upload my images via the website, everything goes well and the images show in my bucket and on my albums, but I've just logged onto my website after around 24hrs and all the images I uploaded are gone and some are just not rendering. Now I know that this would happen if I was trying to store them on Heroku, but does anyone have any ideas why they're disappearing whilst I'm using AWS for storage? TYIA EDIT When I click on the images that are not rending to open in a new tab i get the following error. I removed some of the data just incase its private. Error Code AccessDenied Code Message Access Denied Message RequestId RequestId HostId HostId Error -
How can i convert this function to class in django
def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): if request.user.type in allowed_roles: return view_func(request, *args, **kwargs) else: return render(request, '403.html') return wrapper_func return decorator -
Changes in html template are not reflecting
I have made changes in html file and saved it but the changes won't reflect on the browser. I have refreshed the page but still nothing changed. I changed the colour of the text actually. -
How to prevent specific user from accessing django admin url?
I am working on django blog project. I noticed any one can see login panel if they visit www.example.com/admin/ Is it possible to restrict specific users from accessing the admin url path -
How can I get rid of the ModuleNotFoundError: No module named <modulename> error?
I'm getting ModuleNotFoundError: No module named 'bookList' when trying to run the bot I wrote. In the bkmBooks.py file, I imported my model " from bookList.models import BookList " in this way. However, after the migrate, the functions inside my bkmBooks.py file did not work. What might be causing this error? The order of file structure is as follows: bookList>bookfiles>bkmBooks.py Contents of my bkmBooks.py file: from ast import Str from base64 import decode import requests from bs4 import BeautifulSoup import pandas as pd import csv from time import sleep from random import randint import numpy as np from bookList.models import BookList # import bookfiles.bkmBooks as bkmBooks headers = dict() headers[ "User-Agent" ] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36" def sendBooksToMysql(): bkmArt() def bkmArt(): pages = range(1, 3, 1) for page in pages: url = "https://www.bkmkitap.com/sanat" results = requests.get(url, headers=headers) soup = BeautifulSoup(results.content, "html.parser") book_div = soup.find_all("div", class_="col col-12 drop-down hover lightBg") sleep(randint(2, 10)) for bookSection in book_div: img_url = bookSection.find("img", class_="lazy stImage").get('data-src') name = bookSection.find("a",class_="fl col-12 text-description detailLink").get('title') author = bookSection.find("a", class_="fl col-12 text-title").get('title').replace('Model:', '') publisher = bookSection.find("a", class_="col col-12 text-title mt").get('title').replace(name, '') price = bookSection.find("div", class_="col col-12 currentPrice").text.replace('\n', '').replace('TL', ' TL') b_link … -
Image not updating django
In my edit.html I have a form where the user can edit information on a trainee. The user can add many trainees, edit them, delete them etc. Everything works fine there except the image. The imagefield of form appears in a very messy state. Also it does not update when I select a new image. Here is my code. I have cut down my code to make it more readable models.py class Trainee(models.Model): TraineePic = models.ImageField(null=True, blank= True, upload_to="traineeImg/") Name = models.CharField(max_length=50) class Meta(): db_table = "Trainee" forms.py class TraineeForm(forms.ModelForm): TraineePic = forms.ImageField(label="Image :", required=False) Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') class Meta(): model = Trainee fields = ("Name","TraineePic",) views.py class UpdateTrainee(UpdateView): model = Trainee template_name = 'MyTestApp/edit.html' form_class = TraineeForm success_url = reverse_lazy('show') edit.html {% extends "MyTestApp/base.html" %} {% block body_block %} {% load static %} <link rel="stylesheet" href="{% static '/css/bootstrap.min.css'%}" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <style> ul#id_Gender li{ display: inline-block; } </style> <body> <div class="jumbotron"> <h2> Edit Trainee </h2> <form method="post" class="form-group" type="multipart/form-data" data-ajax="false"> {%csrf_token%} {{form.errors}} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.TraineePic.label }}</label> {{form.TraineePic}} </div> <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Name.label }}</label> {{ form.Name }} </div> <input type="submit" value="Update" class="btn btn-dark"> </form> </div> </body> {% endblock %} Here … -
Can Elasticsearch be used as a database in a Django Project?
Can we directly use Elasticsearch as a primary database in Django? I have tried finding the solution or a way out but could not find any relevant information. Everywhere it is said that we can use Elasticsearch as a search engine over any other primary database. But as per my understanding Elasticsearch is a NoSQL Database, so there should be a way to use it as a Primary Database in a Django Project. Please help, if someone has any idea about it. -
'builtin_function_or_method' object has no attribute 'model'
I'm sorting by category and I get this error when starting the server. How to solve it? Error Image: https://i.stack.imgur.com/W4ROr.png filter/views.py from django.shortcuts import render from .filters import * from .forms import * # Create your views here. def filter(request): index_filter = IndexFilter(request.GET, queryset=all) context = { 'index_filters': index_filter, } return render(request, 'filter.html', context) filter/filters.py import django_filters from search.models import * class IndexFilter(django_filters.FilterSet): class Meta: model = Post fields = {'brand'} search/models.py from django.db import models class Post(models.Model): BRAND = [ ('apple', 'apple'), ('samsung', 'samsung'), ('huawei', 'huawei'), ('nokia', 'nokia'), ] img = models.URLField(default='https://omsk.imperiya-pola.ru/img/nophoto.jpg') title = models.CharField(max_length=80) brand = models.CharField(max_length=20, choices=BRAND) content = models.TextField() price = models.FloatField(default=1.0) def __str__(self): return self.title filter/urls.py from django.urls import path from .views import * urlpatterns = [ path('filter/', filter, name='filter') ] templates/filter.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="get" action="{% url 'index' %}"> {{ index_filters.form }} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </body> </html> -
When I pass a url parameter to modelform, None is passed instead of the url parameter
I am trying to build up a posting webpage. This is how it works: you click a button, the posting form will appear, you fill in the form, you click the submit button, and the process is complete. And when the form is submitted, a url parameter will be passed as the value of a hidden input in the modelform in the views.py. However, when I browse the model in manage.py shell, None is saved instead of the url parameter. Here are the codes: models.py from django.db import models from django.db.models import CharField, TextField, DateField class Post(models.Model): username = CharField(max_length=30, blank=True, null=True) content = TextField() dt_created = DateField(auto_now_add=True) dt_modified = DateField(auto_now=True) def __str__(self): return self.username forms.py from django import forms from django.forms import Textarea, HiddenInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'username'] widgets = { 'content': Textarea(attrs={ 'class': 'write_input', 'placeholder': 'write your story here...' }), 'username': HiddenInput(attrs={ 'value': ' ' }) } labels = { 'content': '' } urls.py from django.urls import path, include from . import views urlpatterns = [ path('<str:username>/main/', views.account_main, name='account_main') ] views.py from django.shortcuts import render, redirect from .forms import PostForm from .models import Post def account_main(request, username): … -
How to reduce ram usage when you load a model
when I try to load the model in my views.py the RAM usage get higger after that it gets normal, So how to make it always on normal usage ? I am using model Wave2Vec2Inference("facebook/hubert-xlarge-ls960-ft",cuda_flag = True) can anyone help me out -
How to implement reject/approve functionality with Django
For example, a model called Request, this model has a status field, status is by default "Awaiting", I want to make it possible for someone to change that through a form to "Approved" or "Rejected" I tried using some methods but they all didn't work. -
How to simplify phone_number field update Process in django including verification
Problem Description: We have a User model where Phone number is been set as username and its unique=True, We also have a field where to represent verified/unverified users. And we verify users by OTP verification to phone number. So now we need to add a new feature where user can replace his phone_number and then he will go to verification process and then we will change his number. And also We need to preserve his previous number (which he already verified) until this new number is verified. If for some reason user decides to go back without verification we delete newly added number and keeps his old number as username. So what would be the best way to approach this problem What I'm considering to have another Model linked with ForeignKey to User class AlternativeNumber(models.Model): user = User() # forignkey number = Charfield is_verfied = BooleanField So we will be verifying users number and replacing his original number from his alternativenumber_set Do you think we can simply it more. Do you think it might have some flaws or we go with a better appraoch ? thanks. -
Print several separate tables from one HTML document
I did the work and was able to render the data into tables. Now I have the following structure on the page: <div class="report-table-container mt-5" id="**current_pko_table**"> *some data* </div> <div class="report-table-container mt-5" id="**current_report_table**"> *some data* </div> <div class="report-table-container mt-5" id="**current_refund_to_customers_table**"> *some data* </div> Can anyone suggest a solution to make the "print all" button so that it only prints: current_pko_table, current_refund_to_customers_table, current_refund_to_customers_table? And also offer to separate the pages for printing, so that each of these documents is on a separate page when printed. I will be glad for any help. My whole project is built on django, but my experience with JS small. I will be glad for any help!