Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django wrong count after exclude
I am having trouble getting a correct count after excluding users on a queryset. I am using Django==2.2.24. Please consider below scenario: Model A: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, related_name="modelA_user", on_delete=models.CASCADE) Model B: user = models.ForeignKey(CustomUserModel, on_delete=models.CASCADE) CustomUserModel: has FK on User model When I count() on said querysets on these models I get correct results for the objects I filter for. Queryset on Model A: usersFromModelA = apps.get_model("models.ModelA").objects.filter( status=2 ).distinct().order_by().values_list("user_id", flat=True) print(usersFromModelA.count()) # returns correct result, total count = 37 Queryset on Model B: modelb_objects = apps.get_model("models.ModelB").objects.filter( boolField=False ) print(modelb_objects.count()) # returns correct result, total count = 2396 When I try to exclude users from modelA on modelB queryset I get a wrong result; I expect to get a total of 2396 - 37 = 2359 but I get 2386 instead. All records in both models have values, no nulls. modelb_objects = modelb_objects.exclude(user__user_id__in=usersFromModelA).distinct() # returns wrong result, total count = 2386 Any ideas how to fix this? -
django rest framework set_cookie is not working
I am creating a login api for my app, I want to set_cookie for the response is httponly = True, secure = True, samesite = 'strict', I did it but this is not working, does someone help me to solve this ? class LoginView(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] try: user = User.objects.get(username = username, password = password) except: raise ValidationError('user not found') try: user_token = user.auth_token.key except: token = Token.objects.create(user = user) user_token = token.key res = Response() res.set_cookie(key = 'key', value = user_token, httponly = True, secure = True, samesite = 'strict') res.data = { 'key': user_token } return res -
how to make dynamic color change in table heading in django
Table heading color not working after 3 class name in CSS, I want to change color when if new data will be added in database after 3 heading how to make it dynamic color change in CSS. <style>.demo1{ background-color: #F4CCCC; } .demo2{ background-color: #D0E0E3; } .demo3{ background-color: #EAD1DC; } </style> {% for i in trades %} <th class="demo{{forloop.counter}}">Capicity</th> <th class="demo{{forloop.counter}}">Total</th> <th class="demo{{forloop.counter}}">Training completed</th> {% endfor %} -
how to properly show "similar products" using the carousel in the Django template?
I want to display similar products with the help of the carousel. But I can only display 4 products per "carousel item". If in the loop {% for item in related_products %} there are more than 4, it doesn't display correctly. I've made 'context' slices of 4 items and it even works, but I'm sure there's a better way. How can I solve this problem and carry the following products to the next "carousel item"? Also, can you please tell me how not to display a 'carousel item' if there are no products for it? The {% if related_products_1 is not null %} construct failed. my views: class ProductDetail(FormView): template_name = 'retail/single_product.html' context_object_name = 'product' form_class = CartAddProductRetailForm def get_queryset(self): return Product.objects.filter(category__slug=self.kwargs['slug']) def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get(slug=self.kwargs['slug']) # slices: context['related_products_1'] = Product.objects.select_related('tag').all()[:4] context['related_products_2'] = Product.objects.select_related('tag').all()[4:8] context['related_products_3'] = Product.objects.select_related('tag').all()[9:12] return context Template: <div id="carouselFourColumn" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselFourColumn" data-slide-to="0" class="active"></li> <li data-target="#carouselFourColumn" data-slide-to="1"></li> <li data-target="#carouselFourColumn" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% if related_products_1 is not null %} <div class="carousel-item active"> <div class="row"> {% for item in related_products_1 %} <div class="col-xl-3 p-1" > <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <a href="{% … -
How to stop django-python3-ldap package from storing user passwords in the database?
I am developing a django web application where I am using django-python3-ldap package for LDAP authentication. I am successfully able to authenticate users using LDAP. Once a user is successfully authenticated, its profile gets created in the default django user model (By fetching firstname, lastname and email from Active Directory) However, it is also storing user's password in the user model(in encrypted format). I do not want this to happen. I simply wish to authneticate users using AD and fetch firstname, lastname and email of the user but not the password. Is it possible? If yes, kindly tell me how. Any help would be highly appreciated. -
I can't find out my mistake in displaying database data in django template
I am working on a Django project. I have to display database data in the Django template but I can't find out my mistake in my code that is not allowing me to display data on the HTML page. views.py def viewposts(request): posts = NewPost.objects.all() return render(request,"network/index.html",{ "posts" : posts, }) Here is my model: models.py class NewPost(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) post = models.TextField() timestamp = models.DateTimeField(auto_now_add = True) def __str__(self): return f"post : {post} || user: {user} || timestamp: {timestamp} " HTML template <div id="posts"> {% for posts in posts %} <ul> <li> <h4>{{ posts.user }} || {{ posts.timestamp }}</h4> <h3>{{ posts.post }}</h3> </li> </ul> {% empty %} <h6>No post availabel 😔</h6> {% endfor %} </div> urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("index/",views.NewPostMaker,name="post"), path("index/",views.viewposts,name="posts") ] I know I have done a silly mistake on any part of my code but I can hardly find it out. When I fill-up the form, data is stored in the database but I can't display them on the HTML page. -
Django: how to test for concurrency issues when using cron jobs
I have a Django application hosted on a remote server which runs some cron jobs at relatively short intervals. One of these cron jobs executes a command that fetches a queryset from the database, calls an external API and changes the models based on the response from the API. If I don't take care, the cron job will execute multiple times before the API responds, thus leading to concurrency issues and multiple instances of the same models being updated at the same time. I have different strategies to avoid this issue, but I would like to write tests that I can run locally, mocking the API call and ensuring, that two cron tasks don't both try to work on an object at the same time. How do I do that? My code looks something like this (illustrative purpose to show the problem): def task(): qs = MyModel.objects.filter(task_ran=False) for model in qs: resp = api_call(model.foo) model.bar = resp model.task_ran = True model.save() So, how can I write a test, that checks that if task() is called a second time before the first call has finished, then it won't update the model again and the API won't get called again? Below is … -
Overriding Django ModelForm save method and deleting old values(files)
I have a model and a ModelForm from the model mentioned. The model has an image field among others. As I update an instance of the model using the ModelForm, if the image field has been updated, I want the old file to be deleted. So I override the save method on the ModelForm. However, I am getting an unexpected outcome. When the image field is updated, if there NO was a file previously, the new one is saved perfectly. But when there WAS a file previously, it does get stored in the file system but it's not saved to the instance. Thus the image field becomes empty. The model example class Article(models.Model): title = models.CharField(max_length=200) cover_image = model.ImageField() The Form from django.core.files.uploadedfile import InMemoryUploadedFile from django.db.models.fields.files import ImageFieldFile, FileField class ArticleModelForm(forms.ModelForm): class Meta: model = Article fields = '__all__' def save(self, commit=True): object = super().save(commit) # Clean out the old files for key in self.changed_data: new_value = self.cleaned_data.get(key) if new_value and isinstance(new_value, InMemoryUploadedFile): old_value = self.initial.get(key) if old_value and (isinstance(old_value, FileField) or isinstance(old_value, ImageFieldFile)): old_value.delete() return object On the override save method what I did is loop through all changed data and do the following; Get the new value … -
How to migrate models when I django test with parallel option?
When I tried to test with parrallel option(--parallel=3), all models migrated in only one database. (I expected that models migrated in all databases. How can I fix it? I tried to run: python manage.py test --settings=server.settings.test --parallel=3 I got Error: django.db.utils.ProgrammingError: (1146, "Table 'test_xxx_1.company' doesn't exist") -
Migrating Bcrypt from PHP to Django
I am migrating a PHP backend to Django and I don't wanna make users change their passwords. In PHP I'm using Bcrypt, which uses version 2y, while Django uses 2b, making it incompatible. I've read other solutions where people write a whole new hasher, but that seems too difficult. My solution was to override the check_password() function of my User model: def check_password(self, raw_password): def setter(): pass alg_prefix = 'bcrypt_php' if self.password.startswith(alg_prefix): return bcrypt.checkpw(bytes(raw_password, 'utf-8'), bytes(self.password[len(alg_prefix):], 'utf-8')) else: return super().check_password(raw_password) And to save old passwords adding bcrypt_php in the beginning. The question is: Is it dangerous to do this? Am I putting my passwords or my system in danger? -
Create a lookup in django
I Have an accounts table with account number and account name in a model called accounts how do I create a lookup such that whenever I enter an account number in django template, account name get populated automatically -
Django not deleting session id in mongoDB database when logging out
I have integrated the MongoDB database with CVAT. I get "Could not login" Error when I try to login second time into CVAT portal. I get below error in browser console (full error screenshot attached) "FAILED SQL: INSERT INTO "auth_user_groups" ("user_id", "group_id") VALUES (%(0)s, %(1)s)" I know that this is because django has not deleted the session id in database in auth_user_groups collection for first time login-logout. How can I fix this issue and make sure I will be able login-logout multiple times without having to manually delete session id in mongoDB ,auth_user_groups collection. [ -
Modifying the path of an already uploaded file to S3 using the Django ORM
My goal is to change the path (not the base one) in which our file history is located in S3, for example from a script. They are files that are referenced by models of a Django application through FileField fields. And I don't know how to do it consistently. More in detail: now all the file history is in the media directory of the bucket, and we want to reorganize this directory by user and other fields to keep the file system in order. For new files, I have read that you can easily specify a custom path through the upload_to parameter, but I don't know how to do it with old files. How can I move an already uploaded file to S3 using the Django ORM? Thank you! -
Getting NOT NULL constraint failed: locations_location.city_id in DRF
When I try to create an object through DRF serailizers in my api, I get the error NOT NULL constraint failed: locations_location.city_id. I looked at a similar here and the solution provided seems to be exactly what I had to begin with. My models: class City(models.Model): code = models.CharField(max_length=4, default="", blank=False, unique=True) name = models.CharField(max_length=40, default="", blank=False, unique=True) time_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}, ({self.code})" class Meta: verbose_name = "City" verbose_name_plural = "Cities" class Location(models.Model): status_choice = ( ("Available", "Available"), ("Unavailable", "Unavailable"), ("Active", "Active"), ) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="locations") name = models.CharField(max_length=256, default="", blank=True) rent = models.DecimalField(max_digits=7, decimal_places=2) email = models.EmailField(max_length=64) phone = models.CharField(max_length=20, default="", blank=True) lon = models.DecimalField(max_digits=7, decimal_places=5, blank=True, null=True) lat = models.DecimalField(max_digits=7, decimal_places=5, blank=True, null=True) street_number = models.CharField(max_length=50, null=True) street_name = models.CharField(max_length=50, null=True) postal_code = models.CharField(max_length=50, null=True) status = models.CharField(max_length=50, choices=status_choice, default="Available") time_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name} {self.status}" My serailizers: class CitySerializer(serializers.ModelSerializer): locations = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = City fields = "__all__" def create(self, validated_data): return City.objects.create(**validated_data) class LocationSerializer(serializers.ModelSerializer): location_events = serializers.PrimaryKeyRelatedField(many=True, read_only=True) booked_days = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Location fields = "__all__" depth = 1 def create(self, validated_data): city = serializers.PrimaryKeyRelatedField( # noqa many=False, queryset=City.objects.all() ) return Location.objects.create(**validated_data) … -
Preload a yolo model in AppConfig Django (Attemped to use a closed Session)
So i have a model for object detection using YOLO3 , and im trying to optimize it , it takes 10 seconds to load the model and then he start the object detection, so i tried to preload the model in apps.py , and pass it to the function that need the model , but im getting Attemped to use a closed Session from tensorflow , is there is a way to close a session in another place from where the model is loaded ? actually thats waht im doing . apps.py from django.apps import AppConfig import snakeimage.classification_codes.classification_codes.pre_loading as pre import tensorflow init_tf = None class SnakeimageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'snakeimage' def ready(self): with tensorflow.compat.v1.Session(): print("im ready !!") global init_tf init_tf = pre.loading_model() and im using the global variable in this function : import snakeimage.apps as si import tensorflow def detection_task(image_path): obj_det_res = snake_obj_detection(image_path , si.init_tf) print(obj_det_res) return obj_det_res maybe their is another way to do it in a cleaner way , so told me if im wrong . -
Why Python Anywhere // Django does not allow over 100 entries into a model?
I am currently hosting a Django// Python App on PythonAnywhere and this app contains list-like forms where the user can enter electricity and water readings for complexes. One of these forms has 264 lines (forms) on the page however when the user reaches 100 entries, the page does not allow for any more. Does anyone know why this happens or how to fix it? We are using a SQLite3 database for this date -
is there any way to import "timedelta_seconds" from "celery.utils.timeutils" or any other library in Django==3.1.13?
enter image description here I am migrating (upgrading) the code to newer version of python==3.8.10 and django==3.1.13 there is a import startment and the erorr I am facing, I am not able to import the 'timedelta_seconds' from "celery.utils.timeutils", I need to solve this as,I have some dependencies on my older version of the code. thanks. -
How to apply two models to one view?
I have 2 models Goods and Number models and I need to apply those models to IndexView. I would be pleased to know how this can be done in my code sorry for english. this is code of views.py from django.views import generic from django.utils import timezone from .models import Question from .models import Goods from .models import Number class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def description(self): return self.description_text def price(self): return self.price_text class NumbersView(generic.ListView): template_name = 'Homepage/index.html' model = Number context_object_name = 'numbers' def number1(self): return self.number1_text def number2(self): return self.number2_text this is code of models.py class Goods(models.Model): description_text = models.CharField(max_length=200) price_text = models.CharField(max_length=200) image_sale = models.ImageField() def __str__(self): return self.image_sale def __str__(self): return self.description_text def __str__(self): return self.price_text class Number(models.Model): number1_text = models.CharField(max_length=200) number2_text = models.CharField(max_length=200) def __str__(self): return self.number1_text def __str__(self): return self.number2_text -
How to pass conditional attributes to template in Django ListView
I'm trying to make a list of employees that each day contains information ("today_note") if they are present at work or are sick. I had no problem to do this in Flask, I simply rendered a template as below: def employees_list(): all_employees = Employee.query.order_by(Employee.name).all() today = date.today() for employee in all_employees: today_sick = db.session.query(SickLeave).filter(SickLeave.start_date <= today).filter( SickLeave.end_date >= today).filter(SickLeave.person_id == employee.id).all() if len(today_sick) != 0: employee.today_note = "C" else: employee.today_note = "✓" return render_template("employees_list.html", all_employees=all_employees) and could access today_note for each employee in the template: {% for employee in all_employees %} {{ employee.today_note }} {% endfor %} Now I need to do the same in django. I can't figure out how to pass today_note to each instance of User model to be able to display it in the template. class AllEmployeesList(ListView): template_name = "users/all_employees.html" model = User context_object_name = 'employees' def get_context_data(self, **kwargs): context = super(AllEmployeesList, self).get_context_data(**kwargs) all_employees = User.objects.all() today = date.today() for employee in all_employees: today_sick = Sickleave.objects.filter(Q(start_date__lte=today)&Q(end_date__gte= today)&Q(employee__id=employee.id)).all() if len(today_sick) != 0: employee.today_note = "C" else: employee.today_note = "✓" return context I'm aware that here I completely miss reference to context -
Get number of objects in serializer where foreign key field is x
Suppose class ABC(models.Models): ... id = models.SlugField(...) user = models.ForeignKey(settings.AUTH_USER_MODEL) ... Now i want something like [{id: adfsdd, no_of_user_objects: 5}, {id: gdfvsdf, no_of_user_objects: 0}, {id: ergthf, no_of_user_objects: 2}] How do i achieve this? -
DJANGO: How to stop the first function when the second function is called?
I have called the first "a1" function and it's starts running in the loop and when I called the second "a2" function, the first "a1" function supposed to stop and second function has to start running, but the two functions are running parallelly. I need to stop the first function when the second function is called. Please help def a1(request): if request.method == "POST": add = request.POST['addition'] while True: add = add + 1 print(add) time.sleep(2) return render(request, blog/finished.html) def a2(request): if request.method == "POST": check = request.POST['checking'] while True: print(check) print("second function: ",check) time.sleep(2) return render(request, blog/finished.html) -
What is the difference between using django signals and calling a method?
I am trying to implement a function which sends a notification to all employee records whenever a new document record is published. In the models, I still needed to import the receiver function because my sender model lives in a different project: receiver function (lives in a different app in project): def new_document_version_published(sender, instance, **kwargs): print("New version of document published!") print(sender) print(instance) # Get all employees employees = [] # Send notifications to employees buttons = [NotificationButton(button_text="New version of document", value="Ok", style="primary")] notifyUsers("A new version of the document has been published", buttons, employees, []) sender (lives in a different app in project): from django.db.models.signals import post_save from api.views import new_document_version_published class DocumentVersion: ... def save(self, *args, **kw): if self.pk is not None: orig = DocumentVersion.objects.get(pk=self.pk) if orig.date_published != self.date_published: print('date_published changed') notify_employees() if orig.date_approved != self.date_approved: print('date_approved changed') super(DocumentVersion, self).save(*args, **kw) def notify_employees(): post_save.connect(new_document_version_published, sender=DocumentVersion) I know there is something wrong with my implementation because I don't understand what is the difference between using the signal and just importing and calling the receiver function. All help appreciated! -
Nested one-to-many relationship sqlalchemy filtering
I'm trying to filter nested one-to-many relationship in sqlalchemy, but it gives the filter only in the inner join ( second one), how Can I specify the filter in the outer join not the internal one? I have one-to-many school -->classes one-to-many class -> student I'm trying to get all the students in specific school, in specific class Models.py class School(Base): __tablename__ = 'schools' id = Column(Integer, primary_key=True) name = Column(String) # # Relationship for one-many - parent of classes classes = relationship("Class") def __repr__(self): return "<School(name='%s')>" % self.name class Class(Base): __tablename__ = 'classes' id = Column(Integer, primary_key=True) name = Column(String) # foreign Key for the parent - child of school school_id = Column(Integer, ForeignKey('schools.id')) # Relationship for one-many - parent of students students = relationship("Student") def __repr__(self): return "<Class(name='%s')>" % self.name class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) # foreign Key for the parent - child of school class_id = Column(Integer, ForeignKey('classes.id')) def __repr__(self): return "<Student(name='%s', fullname='%s', nickname='%s')>" % ( self.name, self.fullname, self.nickname) the query is info = session.query(SchoolModel). \ options(subqueryload(SchoolModel.classes).subqueryload(ClassModel.students)). \ filter(SchoolModel.id == parent_lookup_class__student). \ filter(ClassModel.id == parent_lookup_class). \ filter(StudentModel.id == pk). \ first() The output is … -
ValueError at /polls/add/ The view polls.views.addQuestion didn't return an HttpResponse object. It returned None instead
I am trying to pass data from html template to django addQuestion view in my polls app.I want to make an add quetion along their vote options template and I am using django==3.2 Here my html code <form action="{% url 'polls:add' %}" method="post"> {% csrf_token %} <label for="your_queston">Question: </label> <input id="question" type="text"> <br> <label for="choices">Choice 1</label> <input id="choice1" type="text"><br> <label for="choices">Choice 2</label> <input id="choice2" type="text"> <br> <label for="choices">Choice 3</label> <input id="choice3" type="text"> <br> <input type="submit" value="add"> </form> and here my addQuestion function in view.py def addQuestion(request): if(request.POST): try: if(request.POST['question']): qtext = request.POST.get('question') q = Question(question_text=qtext, pub_date=timezone.now()) q.save() if(request.POST['choice1']): q.choice_set.create( choice_text=request.POST.get('choice1'), votes=0) if(request.POST['choice2']): q.choice_set.create( choice_text=request.POST.get('choice2'), votes=0) if(request.POST['choice3']): q.choice_set.create( choice_text=request.POST.get('choice3'), votes=0) q.save() return HttpResponseRedirect(reverse('polls:index')) except: pass else: return render(request, 'polls/addQuestion.html') -
No able to save data in django model without any error
below mentioned are code complete details I have tried everything and also applied methods available on the internet but the problem still continues. I did not get any errors while submitting the form. Model: class Subscriber(models.Model): id = models.BigAutoField(primary_key=True) email = models.EmailField(null=False, default=1) date = models.DateTimeField(auto_now_add=True) View: from .models import Subscriber def subscriber_view(request): if request.method == 'POST': email = request.POST.get('email') subscriber = Subscriber(email=email) subscriber.save() return render(request, 'homepage') urls.py path('', views.subscriber_view, name='subscriber'), base.html {% load static %} <div class="footer-newsletter"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-6"> <h4>Join Our Newsletter</h4> <p>Tamen quem nulla quae legam multos aute sint culpa legam noster magna</p> <form method="POST" action="{% url 'subscriber' %}" id="subscriber" role="form" novalidate="novalidate" > {% csrf_token %} <input class="form-control" id="email" placeholder="Email Address" type="email" name="email"> <input type="submit" value="Subscribe"> </form> </div> </div> </div> </div>