Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin model instance is not added to the list, error : "Tweeter with ID “” doesn’t exist. Perhaps it was deleted?"
I am trying to add an instance of the model "Tweeter" through Django admin and it gives me a message that it is added, but it does not appear in the list of the model and when I click on the pop up message it says "Tweeter with ID “” doesn’t exist. Perhaps it was deleted?" Tweeter model. Tweet_df is a dataframe and tweets_df['username'] is a string: ` class Tweeter(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True) tweet_search = models.ForeignKey('TweetSearch', on_delete=models.RESTRICT, null=True) username = models.CharField(max_length=200, blank=True, null=True) followers_count = models.IntegerField(blank=True, null=True) class Meta: ordering = ['followers_count'] def save(self, *args, **kwargs): tweets_df = get_tweets(self.tweet_search.search_term) self.username = tweets_df['username'] self.followers_count = tweets_df['followers_count'] def get_absolute_url(self): return reverse('tweeter_detail', kwargs={'pk': self.pk}) ` TweetSearch model: ` class TweetSearch(models.Model): from datetime import datetime, timedelta search_term = models.CharField(max_length=200, blank=True) QUERY_CHOICES = ( ('t', 'in tweet'), ('h', 'in hashtag'), ('u', 'username'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True) query_type = models.CharField(max_length=1, choices=QUERY_CHOICES, blank=True, default='t') start_default = datetime.now() - timedelta(days=30) start_date = models.DateTimeField(default=start_default) end_date = models.DateTimeField(default=datetime.now) language = models.CharField(max_length=200, blank=True) country = models.CharField(max_length=200, blank=True) searcher = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) def get_absolute_url(self): return reverse('tweet_detail', kwargs={'pk': self.pk}) def __str__(self): return f"Tweets with the word {self.search_term} from {self.start_date} till {self.end_date} written in " \ f"{self.language} in … -
how to add conditionals in html attribute
I am using django 4.1.4 and I am new to it. In a form I want to set the correct url based on the variable 'update'. If the variable is True, then the template is used for update (in this case a different url), else save new data. I created something like this: <form action="{% if update %} {% url 'in.edit_session' session.id %} {% else %} {% url 'in.save_session' %} {% endif %}" method="POST" class="form"> but is not working. This will work... but I don't want to duplicate code: {% if update %} <form action="{% url 'in.edit_session' session.id %}" method="POST" class="form"> {% else %} <form action="{% url 'in.save_session' %}" method="POST" class="form"> {% endif %} How can I do this ? -
How Is Web Apps Like Figma and Canva are Built
So I was learning web development and had a idea of building a software like Figma and Canva But had no idea of what technologies do they use to build such web apps. I am a Django developer but is it even possible to build a project with Django , Python and Javascript. I wanna know what technology and tech stack, languages are used to build a application as such. I actually tried to build with Django and Python on the Backend and JS on the frontend for Scripting and also tried to used OpenCV. But then I am not sure about will this work and how to build a software that can edit Videos and Photos like Canva and create Artboard like Figma on the Web I also wanna know what softwares and stack these companies use if possible -
Django queryset - differing results for query and query.count()
I have a django model with three fields and I'm trying to find the duplicates. If I run: cls.objects.values('institution','person','title').annotate(records=Count('person')).filter(records__gt=1).count() I get 152 as the output. However, if I attempt to see what those records are and run the same query without the count() cls.objects.values('institution','person','title').annotate(records=Count('person')).filter(records__gt=1) I get <QuerySet []>. Any idea what's going on? If I add a .first() I get null, and a [0] gives me an out of range error, however the count continues to return 152. -
(Error) django.db.utils.IntegrityError: The row in table "" with primary key "' has an invalid foreign key
I am trying to get the primary key of my User model (which is not the default pk) by using a ForeignKey and then, with a property, get the "usertag" of the User model, but when I try migrating my changes I get the following error: django.db.utils.IntegrityError: The row in table 'user_friend' with primary key 'LOL' has an invalid foreign key: user_friend.fk_id contains a value 'fk_id' that does not have a corresponding value in user_user.id. My models.py: from django.db import models class User(models.Model): f_name = models.CharField(max_length=15) l_name = models.CharField(max_length=15) usertag = models.CharField(max_length=7, default="aabb11") level = models.IntegerField(default=1) profile_pic = models.URLField(max_length=10000) email = models.EmailField(max_length=100) password = models.CharField(max_length=25) class invites(models.Model): invite_id = models.CharField(max_length=8, primary_key=True) choices = [("P", "PENDING"), ("A", "ACCEPTED"), ("D", "DECLINED")] sent_to = models.CharField(max_length=7) from_user = models.CharField(max_length=7) invite_status = models.CharField(choices=choices, default=choices[0], max_length=9) # USE Foreign KEYS class friend(models.Model): fk = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False) friend_tag = models.CharField(max_length=7, primary_key=True) @property def my_tag(self): return self.fk.usertag -
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({ …