Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can we add 1 template to 2 view?
i wonder if i can add 1 template like art_detail.html into 2 views template_name if so objectcontains which ones data? unfortunately i got a problem with adding comment to posts ,i asked it in reddit but since got 0answer i would be pleased if you answer it:https://www.reddit.com/r/learnpython/comments/1029qyk/why_createview_doesnt_create_text_input/?utm_source=share&utm_medium=web2x&context=3 my only purpose was to add comment into posts -
How to stop docker-compose application from inside one of the containers
I have a simple django application, that uses a scheduler to check if the cpu_usage of the server is too high. When the cpu_usage exceeds a certain threshold a want all docker-container applications running on the server to stop. How can I stop docker-container applications from inside on of the containers ? -
Django plantillas - error al usar variables en {% x == y %}
quiero usar una variable selecionada en un lista desplegable para que me muestre todos los datos de la BD en un card, no entiendo porque no funciona con un for me funciona perfecto, cuando le agrego el if no muestra mas nada listados.html <table class="table table-bordered" style="color:white;"> <thead> </thead> <tbody> <select name="localidad_select"> <option selected disabled="true" style="color:white; background-color: rgba(24, 64, 8);"> Seleccione Localidad </option> {% for localidad in localidades %} <option>{{localidad.nombre}}</option> {% endfor %} </select> </tbody> </table> localidades.html {% extends "ipecd_webApp/base.html" %} {% load static %} {% block content %} <div class="container"> <div style = "color:white; padding:10px;" > {% include "listados/listados.html" %} </div> <div class="row"> {% for localidad in localidades %} {% if localidad.nombre == localidad_select %} <div class="col-md-3"> <div class="card" style="width: 80%; margin: 2px 2px;padding-top: 10px;"> <p class="card-text" style ="text-align:center;line-height:5px;"> {{localidad.nombre}}</p> <p class="card-text" style ="text-align:center;line-height:5px;">{{localidad.anio}}</p> <img src="{{localidad.imagen_base.url}}"class="card-img-top"> <img src="{{localidad.imagen_clasif.url}}"> {% endif %} {% endfor %} </div> </div> </div> </div> {% endblock %} views.py def localidades(request): ciudades=Localidad.objects.all() return render(request, 'localidades/localidades.html', {'localidades':ciudades}) def localidad_list(request): local_list=Localidad.objects.all() return render(request,'listados/listados.html',{"localidades":local_list}) def localidad_select(request): result = request.GET["localidad_select"] return render(request, 'localidades/localidades.html', {"localidad_select":result}) Podrian darme una manito? Necesito que solo me traiga los datos de la opcion seleccionada -
Django blog categories predefined
I'm working on my blog, I'm stuck with categories because I was following instructions. I want to have option by superuser to add categories on admin dashboard but not regular user. Also I need to predefined categories, right now they are not preexisted when I want to publish article. This is models.py from django.db import models from django.utils import timezone STATUS = ( (0,"Draft"), (1,"Publish") ) class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at") title = models.CharField(max_length=200, verbose_name="Title") slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) text = models.TextField(verbose_name="Text") status = models.IntegerField(choices=STATUS, default=0) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['-created_at'] def publish(self): self.is_published = True self.published_at = timezone.now() self.save() def __str__(self): return self.title This is views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Category, Post def post_list(request): posts = Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at') return render(request, 'home.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return … -
Python/Django: setuptools/flit entry_point found, but module not despite being there?
I have a problem that I can't solve since days. I use a python module "medux_timetracker" packaged as GDAPS plugin, details below, using an entry point. But the entry point is not recognized - and I'm stuck. The module is installed using flit install --symlink . from within the medux-timetracker directory, using the venv of the main project. pyproject.toml [build-system] requires = ["flit_core >=3.2,<4"] build-backend = "flit_core.buildapi" [project] name = "medux_timetracker" # ... [tool.flit.module] name="medux.plugins.timetracker:apps.TimeTrackerConfig" # medux.plugins are namespace modules. [project.entry-points."medux.plugins"] timetracker = "medux.plugins.timetracker" The class TimeTrackerConfig in this module is basically a Django app, inheriting AppConfig. # settings.py INSTALLED_APPS = [ # ... ] INSTALLED_APPS += PluginManager.find_plugins("medux.plugins") Here the installed apps are dynamically appended by the PluginManager's method which is this (the relevant part where GDAPS/Django loads the entry_point): @classmethod def find_plugins(cls, group: str) -> List[str]: """Finds plugins from setuptools entry points. This function is supposed to be called in settings.py after the INSTALLED_APPS variable.... :param group: a dotted path where to find plugin apps. This is used as 'group' for setuptools' entry points. :returns: A list of dotted app_names, which can be appended to INSTALLED_APPS. """ # ... cls.group = group # ="medux.plugins" installed_plugin_apps = [] # here … -
how to open html template by javascript function in django
I am new to django. I want to open an html page named "addstylist.html" located in the project's templates folder. I want to implement a certain condition on a button click. If that certain condition is true only then I want to navigate a user to "addstylist.html" otherwise stay on the same page. My button function is working fine but I am unable to navigate to that page. Overall my navbar anchor tags are navigating properly. But I am confused what file path of addstylist.html to give exactly in the js file which is in my static folder. I have configured urls.py, views.py and settings.py for static and templates files. HTML FILE ` <form> <div class="form-group"> <label for="Password1">Enter Admin code</label> <input type="password" class="form-control" id="Password1" > </div> </div> <div class="modal-footer justify-content-center" > {% comment %} goes to href="addstylist.html" {% endcomment %} <button class="LogInBtn" id="LogInBtn">LogIn</button> </div> </form> validateadmin.js document.getElementById("LogInBtn").onclick = function () { var code = document.getElementById("Password1").value; //check empty password field if(code == "") { alert("**Fill the password please!"); return false; } else if(code == "famu") { alert("Admin logging..."); window.location.assign("addstylist.html") } else{ alert("Code is not validated. We can't log you in :("); ` urls.py ` from django.contrib import admin from django.urls import … -
How can I restrict the list of objects in API view once an object has been added to a relationship?
I am working in django-rest-framework and I have three models: Event, Performer, and Link. I have many-to-many relationships established on the Event and Performer models as 'links' pointing to the Link model. In the API view, when I am creating or updating an event or performer, I am given a list of all links. I would like them to be removed as options once they've been associated with another object, but I can't seem to figure out how to. Below is my code: class Link(models.Model): created = models.DateTimeField(auto_now_add=True) address = models.URLField() def __str__(self): return f"{self.address}" class Meta: ordering = ['created'] class Performer(models.Model): created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) links = models.ManyToManyField(Link) def __str__(self): return f"{self.first_name} {self.last_name}" class Meta: ordering = ['created'] class Event(models.Model): created = models.DateTimeField(auto_now_add=True) sale_date = models.DateTimeField() event_date = models.DateTimeField() performer = models.ForeignKey(Performer, on_delete=models.CASCADE) links = models.ManyToManyField(Link) class Meta: ordering = ['event_date'] and I'm using this for serializers: class LinkSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Link fields = ['url', 'address'] class PerformerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Performer fields = ['url', 'first_name', 'last_name', 'links'] class EventSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Event fields = ['url', 'performer', 'sale_date', 'event_date', 'links'] I thought about using ManyToManyField.limit_choices_to but I don't know … -
When "select_related" is needed?
In my project , Each candidate can takepart in some assessments,each assessment havs some tests, each test has some questions in it and candidates should answer the questions al last the scores is saved in question_score and test_score table I need to get some values of field and use them I write a method for question_result table, to get them but i dont know if it is needed to use select_related or not if it is needed how can i use it ? Assessment: class Assessment(BaseModel): company = models.ForeignKey( 'company.Company', on_delete=models.CASCADE, related_name='assessments', ) title = models.CharField(max_length=255) job_role = models.ForeignKey( JobRole, on_delete=models.PROTECT, related_name='assessments', blank=True, null=True, ) tests = models.ManyToManyField( 'exam.Test', related_name='assessments', blank=True, through='TestOfAssessment', ) candidates = models.ManyToManyField( 'user.User', related_name='taken_assessments', blank=True, through='candidate.Candidate' ) def __str__(self): return self.title Test: class Test(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 company = models.ForeignKey( 'company.Company', on_delete=models.PROTECT, related_name='tests', null=True, blank=True, ) questions = models.ManyToManyField( 'question.Question', related_name='tests', blank=True, help_text='Standard tests could have multiple questions.', ) level = models.IntegerField(default=1, choices=DifficultyLevel.choices) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title Question : class Question(BaseModel): company = models.ForeignKey( 'company.Company', on_delete=models.SET_NULL, null=True, blank=True, related_name='company_questions', ) question_text = models.TextField() def __str__(self): return truncatewords(self.question_text, 7) TestResult: class TestResult(BaseModel): candidate … -
How to check user is authorised or not in urls.py?
I'm using a library for creating several calls in the front end but I have a problem. The library does not have authenticated user control, which is a severe problem, and also I cannot change the library for some reason. Is there a way to control the user login in urls.py? urls.py from drf_auto_endpoint.router import router ... path('api/v1/', include(router.urls)), -
Django : Only display model items that match with for each category
Here are the models I've created class Jeu(models.Model): nom = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField(blank=True) class Course(models.Model): jeu = models.ForeignKey(Jeu, verbose_name='Nom du jeu', on_delete=models.CASCADE) ligue = models.ForeignKey(Ligue, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) date_evenement = models.DateTimeField("Date de la course") Here is the view : def home(request): courses_a_venir = Course.objects.filter(date_evenement__gte = datetime.today()).order_by('date_evenement') courses_passees = Course.objects.filter(date_evenement__lt = datetime.today()).order_by('-date_evenement')[:3] jeux = Jeu.objects.all() return render(request, 'base_site/home.html', context={'title': 'Accueil', 'courses_a_venir': courses_a_venir, 'jeux': jeux, 'courses_passees': courses_passees}) And then here is the HTML code : {% for jeu in jeux %} <h3>{{ jeu.nom }}</h3><br> <div class="row row-cols-1 row-cols-md-3 g-4"> {% for course in courses_a_venir %} <div class="col"> <div class="card"> <!--<img src="..." class="card-img-top" alt="...">--> <div class="card-body"> <h5 class="card-title">{{ course.jeu }}</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer"> <small class="text-muted">{{ course.date_evenement }}</small> </div> </div> </div> {% endfor %} </div><br> {% endfor %} <br><br> What I'd like to do, is to display only the "Course" items that match with the name of the "Jeu". I know that I have to insert an if statement in the HTML code, and I tried different things, such as : {% for jeu … -
Bulk delete with many-to-many field django ORM
Hii i have 1 model named College and in the model i have document_files field which is Many2ManyField now when i delete College objects i have to delete document_files also Below is my code and Model, college_datas = College.objects.filter(id__in=[1,2]) if college_datas.exists(): for college in college_datas: college.document_files.all().delete() college.delete() class College(models.Model): name = models.CharField(null=True, blank=True) document_files = models.ManyToManyField(CollegeDocuments, through='CollegeDocumentsThrough') class Meta: verbose_name_plural = "College" Here i am using for loop which i think its time consuming so i am finding efficent way to bulk delete the college queryset and also removes the associated Many2ManyField data also. -
Pass request.session after function is executed
I have app, with authentication and when user logs out, I want a notification message to be displayed. My logout view looks like: def logout_view(request): logout(request) message = 'Logout successfull' request.session['message'] = message return redirect('index') And my index(the one i'm redirecting to) view looks like: def index(request): context = {} if request.session: message = request.session['message'] context['message'] = message return render(request, 'index.html', context) My index.html: {{ message }} Now logged in or out when i go to my index view I see message. When I click on button which logs me out I still see message. I want users only to be able to see messages if they logged out. I don't know if this is possible and if it isn't then you may tell me another way to pass context with redirect function. Thanks for help! -
Django accessing values returned in Array with POST
I'm trying to return form data as an array, my html looks like this : {% for f in factures %} <tbody> <td>{{ f.numero }}</td> <td>{{ f.date}}</td> <td>{{ f.sommeRestante }}</td> <td><input type="number" name="valeur[]" value=0></td> </tbody> {% endfor %} in my view when i execute print(request.POST) i get : <QueryDict: {'csrfmiddlewaretoken':[...], 'valeur[]': ['100', '0']}> how can i access the values '100' and '0'? i tried request.POST['valeur[]'][0] but it returns 0 (it's returning the default value set inside html) -
Inherited apollo entities resolving to null
I faced a problem with Apollo federation, which in the end I couldn't resolve. I dug through the documentation and issues, which I was able to google out here on stackoverflow and github. Let me introduce you to a context a little bit. I am using django, together with graphene and graphene-federation. For the sake of this example (and to simplify it as much as I can) let's say I have two graphql APIs combined together using Apollo federation. Let's call them car-service and race-service. These APIs expose two schemas, each has it's own URL. One is /internal/graphql/ and another one is /external/graphql/. For that reason I have separate graphene types for internal and external schemas. The purpose may not be clearly visible in my examples, but imagine I am resolving additional fields here and there and want them to be internal only. Let's assume for that The problem I faced is that my internal entities are not resolved by graphene at all. In urls.py (both APIs): urlpatterns = [ path( "internal/graphql/", csrf_exempt( GraphQLView.as_view( graphiql=True, schema=internal_schema, ) ), ), path( "external/graphql/", csrf_exempt( GraphQLView.as_view( graphiql=True, schema=external_schema, ) ), ), ] In external_schema.py of car-service: @key(fields="uuid") class CarTypeExternal(django_filters.DjangoObjectType): class Meta: model = … -
The included URLconf does not appear to have any patterns in it. Error in Django
The included URLconf '<module 'myapp.urls' from 'C:\\Users\\Hp\\Desktop\\Python\\Django Projects\\myproject\\myapp\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. This is the error that I am getting while building my django app. Here is urls.py from myapp - from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index') ] Here is views.py - from django.shortcuts import render from django import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1>Hey, Welcome</h1>') this is from urls.py from myproject- """myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] -
Django links, url parameters overwriting
I've got django template with table/list with sorting action: <a href="?order_by=name">Name</a> and later I've got paging: <a href="?page=1">first</a> What I want to achieve is a link: http://localhost:8000/list/?page=3&order_by=name while - clicking a link, I can get either page or order_by. How to solve it? (for 2 and more parameters). -
Include Stripe in angular project
I am working on a website which uses angular for client and django for backend and I want to include stripe for payments. To configure stripe on the backend I have a microservice which runs on docker and accepts the following requests: one for creating a stripe customer another one for creating a payment I configured stripe on the client using the provided form as follows: export class PaymentComponent implements OnInit { paymentHandler:any = null; constructor(private checkoutService: CheckoutService) { } ngOnInit() { this.invokeStripe(); } initializePayment(amount: number) { const paymentHandler = (<any>window).StripeCheckout.configure({ key: 'pk_test_51MKU1wDo0NxQ0glB5HRAxUsR9MsY24POw3YHwIXnoMyFRyJ3cAV6FaErUeuEiWkGuWgAOoB3ILWXTgHA1CE9LTFr00WOT5U5vJ', locale: 'auto', token: function (stripeToken: any) { console.log(stripeToken); alert('Stripe token generated!'); paymentStripe(stripeToken); } }); const paymentStripe = (stripeTocken: any) => { this.checkoutService.makePayment(stripeTocken).subscribe((data:any) => { console.log(data) }) } paymentHandler.open({ name: 'Card Details', description: 'Introduce the information from your card', amount: amount * 100 }); } invokeStripe() { if(!window.document.getElementById('stripe-script')) { const script = window.document.createElement("script"); script.id = "stripe-script"; script.type = "text/javascript"; script.src = "https://checkout.stripe.com/checkout.js"; script.onload = () => { this.paymentHandler = (<any>window).StripeCheckout.configure({ key: 'pk_test_51MKU1wDo0NxQ0glB5HRAxUsR9MsY24POw3YHwIXnoMyFRyJ3cAV6FaErUeuEiWkGuWgAOoB3ILWXTgHA1CE9LTFr00WOT5U5vJ', locale: 'auto', token: function (stripeToken: any) { console.log(stripeToken) alert('Payment has been successfull!'); } }); } window.document.body.appendChild(script); } } } The makePayment method makes a request to the django server sending the stripe tocken. From the server … -
Convert case sensitives
i want to convert any new enter user name to lowercase and check if the user is exist or now and use iexact to login in capital or small where should determine the login uses small or capital forms.py class AddCompanyForm(forms.ModelForm): """ Add company model form """ name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput()) logo = forms.ImageField(required=False) phone_number = forms.CharField(widget=forms.NumberInput()) label = forms.CharField(max_length=20) country = forms.ModelChoiceField(queryset=Country.objects.all()) city = forms.ModelChoiceField(queryset=City.objects.all()) area = forms.ModelChoiceField(queryset=Area.objects.all()) latitude = forms.CharField(max_length=50, required=False) longitude = forms.CharField(max_length=50, required=False) water_source = forms.ModelChoiceField(queryset=WaterSource.objects.all()) class Meta: model = User fields = ['name', 'username', 'email', 'password'] def __init__(self, *args, **kwargs): super(AddCompanyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.layout = Layout(Row(Column('name', css_class='form-group col-md-6 mb-0'), Column('username', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('email', css_class='form-group col-md-6 mb-0'), Column('password', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('phone_number', css_class='form-group col-md-6 mb-0'), Column('logo', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('label', css_class='form-group col'), css_class='form-row'), Row(Column('country', css_class='form-group col'), Column('city', css_class='form-group col'), Column('area', css_class='form-group col'), css_class='form-row'), Row(Column('latitude', css_class='form-group col'), Column('longitude', css_class='form-group col'), css_class='form-row'), Row(Column('water_source', css_class='form-group col'), css_class='form-row')) self.helper.layout = self.layout views.py class Companies(LoginRequiredMixin, UserPassesTestMixin, FormView, ListView): """ Company add edit delete view search paginator """ model = Company template_name = 'company/index.html' form_class = AddCompanyForm success_url = reverse_lazy('companies:index') object_list = Company.objects.all() def form_valid(self, form): user, created = User.objects.get_or_create(username=form.cleaned_data['username'], … -
How to set 0, instead of null?
I have 'average_rating' field that takes values from field 'rates' and calculate average value. But when 'rates' field is empty, its shows null. views.py: class BooksView(viewsets.ModelViewSet): serializer_class = BooksSerializer queryset = BooksModel.objects.all() filter_backends = [filters.DjangoFilterBackend, filtersrest.SearchFilter, filtersrest.OrderingFilter,] filterset_class = Myfilter filterset_fields = ('genres','date',) search_fields = ['title'] def get_queryset(self): return BooksModel.objects.all().annotate(average_rating=models.ExpressionWrapper(Round(Avg('rates__rate'), 2), output_field=models.FloatField()), _sum_users_cart=Count('users__user')) In the output i have this: "id": 18, "authors": [ { "author": "Андрей курпатов" } ], "age": [], "tags": [], "users": [], "genres": [], "rates": [], "average_rating": null, "sum_users_cart": 0, "title": "Мозг и бизнес", "desc": "123", "url_photo": "https://s1.livelib.ru/boocover/1007572198/o/fde7/Andrej_Kurpatov__Mozg_i_biznes.jpeg", "is_published": true, "date": "Декабрь 29, 2022", "time": "20:20:02" And i need something like this: "id": 18, "authors": [ { "author": "Андрей курпатов" } ], "age": [], "tags": [], "users": [], "genres": [], "rates": [], "average_rating": 0, "sum_users_cart": 0, "title": "Мозг и бизнес", "desc": "123", "url_photo": "https://s1.livelib.ru/boocover/1007572198/o/fde7/Andrej_Kurpatov__Mozg_i_biznes.jpeg", "is_published": true, "date": "Декабрь 29, 2022", "time": "20:20:02" -
django model form is not saving
When i fill the form and save it, does not save but stays on the same form page. views.py def locker_form(request): form = LockerForm() if request.method == 'POST': form = LockerForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'You have successfully added to your locker.') return redirect('user-page') print(form.errors) context = {'form': form} return render(request, 'pwdbank/locker_form.html', context) template {% extends 'pwdbank/base/main.html' %} {% load static %} {% block title %}User Account{% endblock %} <!-- content --> {% block content %} <h2 class="mt-5 user-page">YOUR LOCKER</h2> <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-5"> <a class="btn btn-dark btn-sm" href="{% url 'locker-form' %}" role="button" >add to locker</a > </div> <hr /> <div class="row gx-4 row-gap-4 mb-5"> {% for info in saved_info %} <div class="col-lg-4"> <div id="saved-details"> <h4>Site Name - {{ info.site_name }}</h4> <p> Site Url - <a href="{{ info.site_url }}" target="_blank">{{ info.site_url }}</a> </p> <p>Created Date - {{ info.created_date }}</p> <hr /> <a class="btn btn-primary" href="{% url 'selected-savings' info.id %}" role="button" >View All</a > </div> </div> {% endfor %} </div> {% endblock %} forms.py class LockerForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['site_name'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'site name', }) self.fields['site_url'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'site url', }) self.fields['username'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'username', }) self.fields['email'].widget.attrs.update({ 'class': 'form-control', 'placeholder': 'email', }) self.fields['password'].widget.attrs.update({ … -
Idle connections after update to django 4
We were using Django 3.2 and before the update everything was fine, but now, after the update to 4.0 we have a problem with too many open database connections. We getting errors like this: FATAL: remaining connection slots are reserved for non-replication superuser connections. We using CONN_MAX_AGE=60, but connections are sometimes not closed at all. Django 4.0.8 Daphne 4.0.0 channels & channels-redis 4.0.0 DB: postgresql 11/14 CONN_MAX_AGE=0 works well, but it is probably not the best option for efficient production. I also set the environment variable ASGI_THREADS=1, but nothing changed, we still have dozens of idle connections. I was also trying to replace Daphne with Gunicorn + Uvicorn and remove Django channels from the codebase, but nothing helped. I know that we can extend the number of available connections, but if old connections are not closing, then soon or later we will hit each limit. -
Creating a field thats connected with another in Django
The thing is that I'd like to create a field with a title that shows available titles depending on the artist's choice in the field above. For example, if a user selects "Drake" in the artist field, only the titles for that artist will be displayed in the title field. I'm completely stuck. Could you give me a hint how to solve the problem? I was wandering if I have to change my models.py by adding some kind of One-To-Many relationship or is there diffrent method? Webpage: enter image description here My models.py file: from django.db import models class SpotifyData(models.Model): title = models.CharField(max_length=60) rank = models.IntegerField() date = models.DateField() artist = models.CharField(max_length=60) region = models.CharField(max_length=20) chart = models.CharField(max_length=8) streams = models.IntegerField() class Meta: indexes = [ models.Index(fields=['title']), models.Index(fields=['rank']), models.Index(fields=['date']), models.Index(fields=['artist']), models.Index(fields=['region']), models.Index(fields=['chart']), ] My view.py file: import plotly.express as px import plotly.graph_objects as go from django.shortcuts import render from spotify_data.models import SpotifyData from spotify_data.charts import (make_song_rank_changes_chart, ) from typing import Any, Dict from django.views.generic import TemplateView from django.views.generic.list import ListView class HomeView(ListView): model = SpotifyData context_object_name = "record" def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["records_all"] = SpotifyData.objects.all().count() return context class SongRankChangesChart(TemplateView): model = SpotifyData context_object_name = … -
Is it possible with Django to have a global view that is called on every page?
I was wondering if it is possible with Django to have a "global view" that is called on every page before all the initial views, for example to display additional information other than the user's information. All of this to avoid having to call a model on all of my views. To allow me to call it only once. -
`pytest-django` tables are emptied when used with `live_server`
I need prevent the tables from being emptied after each test, which is the default behavior when the tests are defined as below. Note: I populate the User table before running the tests, that's why the below works. class TestViews: @staticmethod def test1(django_user_model): assert django_user_model.objects.count() > 0 @staticmethod def test2(django_user_model): assert django_user_model.objects.count() > 0 result: ============================= test session starts ============================== collecting ... collected 2 items test_live_server.py::TestViews::test1 test_live_server.py::TestViews::test2 ============================== 2 passed in 7.86s =============================== Process finished with exit code 0 However, when live_server fixture is included: class TestViews: @staticmethod def test1(django_user_model, live_server): assert django_user_model.objects.count() > 0 @staticmethod def test2(django_user_model, live_server): assert django_user_model.objects.count() > 0 all model tables are emptied after each test. ============================= test session starts ============================== collecting ... collected 2 items test_live_server.py::TestViews::test1 test_live_server.py::TestViews::test2 PASSED [ 50%] FAILED [100%] tests/test_live_server.py:5 (TestViews.test2) 0 != 0 Expected :0 Actual :0 <Click to see difference> django_user_model = <class 'django.contrib.auth.models.User'> live_server = <LiveServer listening at http://localhost:61926> @staticmethod def test2(django_user_model, live_server): > assert django_user_model.objects.count() > 0 E AssertionError: assert 0 > 0 E + where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>>() E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>> = <django.contrib.auth.models.UserManager object at 0x10d83fc90>.count E + where <django.contrib.auth.models.UserManager object … -
Django AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
The problem just appeared now. When I try to ./docker-compose.sh development up my django application, and after the ./manage.py collectstatic I see the error: => ERROR [6/6] RUN EXTRA_SETTINGS_URLS=/usr/src/app/dummy_external_settings.yml ./manage.py coll 3.2s ------ > [6/6] RUN EXTRA_SETTINGS_URLS=/usr/src/app/dummy_external_settings.yml ./manage.py collectstatic: #0 2.996 Traceback (most recent call last): #0 2.996 File "/usr/src/app/./manage.py", line 15, in <module> #0 2.997 execute_from_command_line(sys.argv) #0 2.998 File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line #0 2.998 utility.execute() #0 2.998 File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute #0 2.999 django.setup() #0 2.999 File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup #0 3.000 apps.populate(settings.INSTALLED_APPS) #0 3.000 File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate #0 3.000 app_config = AppConfig.create(entry) #0 3.000 File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create #0 3.000 import_module(entry) #0 3.000 File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module #0 3.001 return _bootstrap._gcd_import(name[level:], package, level) #0 3.001 File "<frozen importlib._bootstrap>", line 1030, in _gcd_import #0 3.002 File "<frozen importlib._bootstrap>", line 1007, in _find_and_load #0 3.002 File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked #0 3.002 File "<frozen importlib._bootstrap>", line 680, in _load_unlocked #0 3.003 File "<frozen importlib._bootstrap_external>", line 850, in exec_module #0 3.003 File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed #0 3.003 File "/usr/local/lib/python3.9/site-packages/ucamwebauth/__init__.py", line 7, in <module> #0 3.004 from OpenSSL.crypto import FILETYPE_PEM, load_certificate, verify #0 3.004 …