Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The view shopping_mall.views.add_comment didn't return an HttpResponse object. It returned None instead
How can i fix it? ERROR MESSAGE The view shopping_mall.views.add_comment didn't return an HttpResponse object. It returned None instead. My Views.py def add_comment(request, pk): post = ProductList.objects.get(pk=pk) if request.method == "POST": form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.product = post comment.save() return redirect('index', pk=post.pk) else: form = CommentFrom() return render(request, 'shopping_mall/add_comment.html', {'form':form}) My urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment/', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] -
Django's `date_hierarchy` not showing the correct date in filters
I have date_hierarchy on a date field in my ModelAdmin. The day filters at the top don't match the actual dates in the list. For example, when I click "May 16", it doesn't show any results (the dates only go up to May 15). Is this the expected behavior? My guess is there's something going on with UTC time vs timezone, but I'm not sure why. -
Django Application verify user can only see items relevant to them
My issue is that I can list all the clients in the database and these occur on all account managers detail pages. What I want to achieve is to list only those clients that appear for a specific account manager but to date everything I have tried does not work. This is the Client Model: class Client(models.Model): client_name = models.CharField(max_length=255) account_manager = models.ForeignKey( AccountManager, on_delete=models.CASCADE, related_name="clients", ) My views.py currently looks like this: class AccountManagerDetailView(LoginRequiredMixin, DetailView): model = AccountManager template_name = "accountmanagers/dashboard.html" context_object_name = "ams" def get_object(self, *args, **kwargs): return self.request.user def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context["clients"] = Client.objects.all() return context And my urls.py urlpatterns = [ path("detail", views.AccountManagerDetailView.as_view(), name="detail"), ] -
access form from another funcion
Question is.. I have static page profil.py: def profil(request, pk): context = {} person = User.objects.get(id=pk) try: person.profesor except Profesor.DoesNotExist: context['ucenik'] = Ucenik.objects.get(id=person.ucenik.id) else: context['profesor'] = Profesor.objects.get(id=person.profesor.id) return render(request, "profil.html", context) and this: def profesor(request): profesor = request.user.profesor forma = ProfesorFormaSlika(instance=profesor) context = {'forma':forma} return render(request, 'pocetna_profesor.html', context) question is, how can i access {{ forma }} in HTML page from def profesor in def profil? -
What does reset password token protect against?
This is more of a concept question than a specific code one. I am building a web app in Django which almost entirely handles the password reset process. And it had me thinking what does the token do, I'm aware that it checks whether the same email that requested the reset is the one changing the password. But why is this needed If someone tried to send a reset email to someone elses email they would need that emails password to actually change it. Is the token just another layer of protection? Is it necessary? I also do not understand the way django handles it: path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), How does passing the token in here, which is the page you access when the reset email is sent to YOU, make it secure. The latter question isnt as important. -
How to fill 'initial value' in Django forms with current user data?
I went ahead and created a Form to update the user database entry. class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ("username", "first_name", "last_name", "email") But when I render the form all input fields are empty. How do I populate them with the user's data like current username and email? I use Bootstrap 5 to style it, but that should matter: <div class="mb-3"> <label for="{{ form.first_name.id_for_label }}" class="form-label">{{ form.first_name.label }}</label> {{ form.first_name|addcss:"form-control"}} </div> Problem is, I render the input field with the Django template engine and don't specifiy it myself. My idea was to chain template filters: <div class="mb-3"> <label for="{{ form.username.id_for_label }}" class="form-label">{{ form.username.label }}</label> {{ form.username|addcss:"form-control"|addplaceholder:user.username}} </div> But that didn't work because the first filter converts it to a widget: @register.filter(name="addcss") def addcss(field, css): return field.as_widget(attrs={"class": css}) Maybe you can recommend me a way on how to modify that filter or tell me a complety different approach. -
How can i change a field based on another m2m field?
So, what i'm tryna do here is set the status of an object based on the length of m2m field. Here's how it looks from django.db import models class Dependency(models.Model): dependency = models.SlugField('Шаблон') class Seo(models.Model): statuses = ( (1, 'Дефолтный'), (2, 'Дополнительный') ) dependencies = models.ManyToManyField( Dependency, verbose_name='Зависимости', blank=True, help_text='Оставьте пустым, если это дефолтный шаблон' ) h1 = models.CharField('Заголовок(h1)', max_length=200) title = models.CharField('Заголовок(title)', max_length=200) description = models.CharField('Описание', max_length=200) keywords = models.TextField('Ключевые слова') status = models.IntegerField('Статус', choices=statuses, blank=True, editable=False) def save(self, *args, **kwargs): if len(self.dependencies) == 0: self.status = 1 else: self.status = 2 # self.status = 1 # # print(len(self.dependencies)) super().save(*args, **kwargs) class Page(models.Model): pass But it throws me an error that goes like ValueError: "<Seo: Seo object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. And what it want to achieve is whenever the dependency field is empty then status should be 1 and otherwise it should be 2. But i couldn't find a way to do it. -
How to query the existence of related objects that are successive in time?
My Blog model has a has two types of comments, blue ones and red ones. I would like to find all blogs that have posts that are blue directly followed by posts that are red. Here, "followed by" is meant in terms of a timestamp field "created_at". How can I filter my blogs by this property? class Comment(Model): color = Charfield(max_length=100) created_at = DateTimeField() blog = ForeignKey(Blog, related_name="comments") class Blog(Model): ... My attempt is: blue_comments = Comment.objects.filter(blog=OuterRef("pk"), color="blue") red_comments = Comment.objects.filter(blog=OuterRef("pk"), color="red") blogs = Blog.objects.filter(Exists(blue_comments), Exists(red_comments)).all() I don't know how to filter for the condition that the "created_at" fields must be successive. -
Add properties to a model from a different app in django? (extend model from different app)
I've got an app (named essence) that I use in multiple projects (it's a shared app with just a User model and a Location model that get used in multiple projects I have) The Location model looks something like this: class Location(models.Model): name = models.CharField(max_length=50) alternate_location_id = models.IntegerField() class Meta(object): ordering = ["name"] def __str__(self): return self.name Currently I have a function that takes a queryset of locations, iterates across it and creates a dictionary for each location with the needed data. But that is causing a lot of extra queries I'd like to avoid. So I'm trying to see if I can dynamically add properties to the Location model from the positions app. The function returns a dictionary that looks like this: { "location_id": location.id, "location_name": location.name, "alternate_location_id": location.alternate_location_id, "location_current_position_count": position_count, "location_current_position_average": position_average, "location_change": location_position_change, } The three variables listed in that dictionary (position_count, position_average and location_position_change) are figured out using various queries of other related models in the function (which are not using aggregate/annotate, but could/should be - hence my refactoring now) I would like to get rid of that function and just make those other variables attributes/properties on the Location model itself so I'm not having to … -
SQL - How to get rows within a date period that are within another date period?
I have the following table in the DDBB: On the other side, i have an interface with an start and end filter parameters. So i want to understand how to query the table to only get the data from the table which period are within the values introduces by the user. i.e If the users only defines start = 03/01/2021, then the expected output should be rows with id 3,5 and 6. if the users only defines end = 03/01/2021, then the expected output shoud be rows with id 1 and 2. if the users defines start =03/01/2021 and end=05/01/2021 then the expected output should be rows with id 3 and 5. Hope that makes sense. Thanks -
Use different models for user and superuser in django
I have a Student model and I will also be creating another model called Teacher. But I want a single model called Admin to be the superuser for both of these models in their respective managers. How do I achieve this? Here's the code I have so far: class StudentManager(BaseUserManager): def create_user(self, usn, email, first_name, last_name, initials, branch, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) user = self.model( usn=usn, email=email, first_name=first_name, last_name=last_name, initials=initials, branch=branch, **extra_fields) user.set_password('password') user.save() return user def create_superuser(self, name, email, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) admin = self.model( # but self.model refers to Student, not Admin email=email, name=name, **extra_fields) admin.set_password('password') admin.save() return admin class Student(AbstractBaseUser, PermissionsMixin): usn = models.CharField(max_length=10, primary_key=True, unique=True, editable=False) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=50, null=False) last_name = models.CharField(max_length=50, null=False) initials = models.CharField(max_length=10, null=True) branch = models.CharField(max_length=5, null=False, editable=False) objects = StudentManager() USERNAME_FIELD = 'usn' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'branch'] class Admin(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=100, null=False) # objects = StudentManager() USERNAME_FIELD = 'name' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email', 'name'] And here's the error I get: api.Admin.groups: (fields.E304) … -
Sorting and filtering django model objects by foreign key values
so i was given a test for an interview and trying to figure out the best way to implement this: Lets say we have a django project. With models: Rental name Reservation rental_id checkin(date) checkout(date) Add the view with the table of Reservations with "previous reservation ID". Previous reservation is a reservation that is before the current one into same rental. so i tried implementing something that actually works, but i just feel i have ignored alot of good practices just to get the work done, I will appreciate some insights/tips on how i can improve my code, thanks guys. Ps: i really need the job :( Here is a sample of my code: ##### models from django.db import models # Create your models here. class Rental(models.Model): name = models.CharField(max_length=100) def __str__(self) -> str: return self.name class Reservations(models.Model): rental_id = models.ForeignKey(Rental, related_name="rental_id", on_delete=models.CASCADE) checkin = models.DateField() checkout = models.DateField() def __str__(self) -> str: return f"{self.rental_id.name}, {self.id}" #### The views implementation from django.shortcuts import render from .models import Rental, Reservations def All_Reservation(request): reservations = Reservations.objects.all() rental_names = Rental.objects.values_list('name') ValueSet = [] for i in sort_by_rental_name(rental_names): ValueSet += i mapped = zip(ValueSet,reservations) print(dict(mapped)) context = { 'reservations': reservations, 'values': ValueSet } return … -
Number of occurrences in django
How to calculate and save in database the number of occurrences per day of the number of participants lower than the maximum number of participants in a space of radius R=50km. # models.py class Even(models.Model): name = models.CharField(max_length=200, null=True, blank=True) date = models.DateField(null=True, blank=True) time = models.TimeField(null=True, blank=True) participant = models.PositiveIntegerField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) geom = models.PointField(srid=4326, null=True, blank=True,) @property def longitude(self): return self.geom.x @property def latitude(self): return self.geom.y def __str__(self): return self.name # views.py def even_nb_jour(request): labels = [] data = [] today = date.today() even_max_today = Even.objects.filter(date=today).aggregate(Max('particpant')) pnt = Even.objects.filter(date=today).filter(geom_magnitude=even_max_today) queryset = Even.objects.filter(date=today).values('time').filter(geom__distance_lte=(pnt, Distance(km=50))).annotate(time_name=Count('name')).order_by('time') for rm in queryset: labels.append(rm['time']) data.append(rm['time_name']) return JsonResponse(data={ 'labels': labels, 'data': data, }) -
How to nest Some of the UserModel fields into another Serializer
I have a model name Comment as follows. class Comment(models.Model): message = models.CharField(max_length=1000) time = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='usercomment') def __str__(self): return self.sender.name For this model, I have a serializer class CommentSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) time = serializers.DateTimeField(read_only=True) message = serializers.CharField(read_only=True) sender = serializers.PrimaryKeyRelatedField(read_only=True, many=False) name = serializers.StringRelatedField( source='sender', read_only=True, many=False) I have another serializer for the sender information that is linked with Forignkey to AUTH_USER_MODEL, and for that Part, I have another serializer to nest some of the fields from the User model. class SenderInformation(serializers.Serializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(read_only=True) avatar = serializers.ImageField(read_only=True) And the main objective is to Nest this SenderInformation into CommentSerializer. How can I achieve this? -
How to pass unique objects from a second model in ListView function to the template django
I am creating a blog app in django. For that, I have made a page where all available blogs are listed. I am using generic.ListView view to achieve this. But, I also want to create a writer's section where I can list some details about the writers that have written those blogs. For this, I need to get all the users that have written a blog and then find distinct users from that and list out their username. I have an author field in my Blog model that keeps track of the writer user. How can I get the distinct usernames of these writers and pass it into my template? Models.py: class Blog(models.Model): blog_head = models.CharField(max_length=100) blog_header_image = models.ImageField(upload_to="photos/blogs/", null=True, blank=True) #blog_content = models.TextField() blog_content = RichTextField(blank=True, null=True) #blog_summary = models.TextField(max_length=355) blog_summary = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) blog_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='blog_post_likes', blank=True) def __str__(self): return self.blog_head def get_absolute_url(self): return reverse('blog-full', args=[str(self.id)]) def blog_likes_count(self): return self.likes.count() Views.py: class blogs_getting_Listview(ListView): model = Blog template_name = 'blogs.html' ordering = ["-blog_date"] def get_context_data(self, *args, **kwargs): context = super(blogs_getting_Listview, self).get_context_data() authors_id_list = Blog.objects.get(id=id).author authors_list = "" for author_in in authors_id_list: author_obj = User.objects.get(id=author_id) authors_list = authors_list + author_obj context.update({ "authors_list": authors_list … -
Send full image url in DRF
I am trying to get the full image URL in the API in DRF i am trying to use build_absolute_uri but i keep receiving the error The 'image' attribute has no file associated with it. the serializer.py: class VesselInfoSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, Vessel): request = self.context.get('request') image_url = Vessel.image.url return request.build_absolute_uri(image_url) vessel_component_count = serializers.IntegerField( source='vessel_components.count', read_only=True ) vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) class Meta: model = Vessel fields = '__all__' models.py: class Vessel(models.Model): name = models.CharField(max_length=255) imo = models.CharField(max_length=255) image = models.ImageField(blank=True, upload_to='vessel_image') def __str__(self): return self.name the view: @api_view(['GET']) def getVesselInfo(request): vessels = Vessel.objects.all() vSerializer = VesselInfoSerializer( vessels, many=True, context={"request": request}) return Response(vSerializer.data) -
The CSV script in Django does not see the d path of the file - [Errno 2] No such file or directory
Why is my Pytnon/Django script unable to read the file path and retur. How to correctly set the path from a saved file? [Errno 2] No such file or directory: '/media/file_hll8NoJ.csv Views.py if form.is_valid(): cd = form.cleaned_data if cd['file']: obj = FileUpload() obj.file = cd['file'] obj.save() with open(obj.file.url) as f: reader = csv.reader(f) for row in reader: _, created = UserEmail.objects.get_or_create( owner=obj_instance, email=row[0], middle_name=row[2], ) Path is correct and if I open http://127.0.0.1:8000/'/media/file_hll8NoJ.csv loacal all works fine (I can see my csv file) -
How to list overdue objects?
I want to create a query that shows which user has how many overdue (out of date) missions. query_overdue = Case.objects.select_related('last_changed_by').values('due_date').order_by('assigned_to').annotate( name=F('assigned'), due=F('due_date'), ) This query shows every object but I want to filter it with not none value and overdue. How can I do it? -
İ can't pull data with JavaScript
I want to pull data using JavaScript and show it in console. I don't know what I did wrong. main.js // ADD TO CART $("#addToCartBtn").on('click',function(){ var _qty=$("#productQty").val(); var _productId=$(".product-id").val(); var _productName=$(".product-name").val(); console.log(_productId,_productName,_qty); }); I am using django framework to write backend detail.html <div class="product-btns"> <div class="qty-input"> <span class="text-uppercase">Ədəd: </span> <input class="input" type="number" value="1" id="productQty"> </div> <input type="hidden" class="product-id" value="{{product.id}}"> <input type="hidden" class="product-name" value="{{product.name}}"> <button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart" id="addToCartBtn"></i> Səbətə at</button> </div> -
Session information is not stored in the database(django-session table)-I have used a custom model and backend
i use multiple backend and model for user authentication the default django auth system and m I use multiple backend and models for user authentication Default Django's model and a customized one . Default django authentication for admin-users and customized model and backend for customer-users Now The problem is when customer-users login their session information does not stored in the database(django-session table),so Because their sessions are not saved, they need to re-login each time the page is refreshed or changed -
Please help me fixing out my django chained dropdown
I am having issues with chained dropdown can someone help me fixing it out.I have created both category and sub category model, product model, html pages, views and everything neccessary to make this code work but it's not working now.it was working when before but now the same code is not working i have no idea what happened to it.I took this code from a youtube tutorials i guess that's the reason i am having trouble fixing it out. forms.py ``` class AdminProductForm(forms.ModelForm): user = forms.ModelChoiceField(label="", queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) image = forms.FileField(label='Thumbnail', widget=forms.FileInput( attrs={'class': 'form-control'}), required=False) class Meta: model = AdminProduct fields = ['user', 'title', 'details', 'image', 'sp', 'dp', 'download_link', 'preview_link','category', 'subcategory', 'tags'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = AdminSubCategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields['subcategory'].queryset = AdminSubCategory.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.category.subcategory_set.order_by('name') models.py class AdminCategory(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class AdminSubCategory(models.Model): category = models.ForeignKey(AdminCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class AdminProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150) details = RichTextField() image = models.ImageField(upload_to="AdminProduct_Images/") download_link = … -
Add custom formatter tags in papertrail Logger in django
settings Page: "formatters": { "simple": { "format": "%(name)s %(asctime)s %(message)s", "datefmt": "%Y-%m-%dT%H:%M:%S", }, }, If I write here code like this: "formatters": { "simple": { "format": "%(name)s %(ip)s %(user)s %(client)s %(asctime)s %(message)s", "datefmt": "%Y-%m-%dT%H:%M:%S", }, }, It is showing following Error: --- Logging error --- Traceback (most recent call last): File "C:\Program Files\Python10\lib\logging\__init__.py", line 440, in format return self._format(record) File "C:\Program Files\Python10\lib\logging\__init__.py", line 436, in _format return self._fmt % values KeyError: 'ip' -
How to use Django with Docker and have no problems with migrations?
During working with docker where I dockerised Django PostgreSQL, I've entered in such problems as when I change some model and migrate it, after entering to the page, it says there is no such relationship in the database. After some research, I found that problem can be due to creating every time new migration and deleting the old. How can I fix this problem? Below you can see my configurations docker-compose-prod.yml services: app: volumes: - static_data:/app/staticfiles - media_data:/app/mediafiles env_file: - django.env - words_az.env - words_en.env build: context: . ports: - "8000:8000" entrypoint: /app/script/entrypoint.sh command: sh -c "python manage.py collectstatic --no-input && gunicorn --workers=3 --bind 0.0.0.0:8000 django.wsgi:application" depends_on: - db nginx: build: ./nginx volumes: - static_data:/app/staticfiles - media_data:/app/mediafiles ports: - "80:80" - "443:443" depends_on: - app - flower db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - db.env ports: - "5432:5432" redis: image: redis:alpine ports: - "6379:6379" worker: build: context: . command: celery -A django worker -l info env_file: - django.env depends_on: - db - redis - app flower: build: ./ command: celery -A django flower --basic_auth=$user:$password --address=0.0.0.0 --port=5555 --url-prefix=flower env_file: - django.env ports: - "5555:5555" depends_on: - redis - worker volumes: postgres_data: static_data: media_data: Dockerfile FROM python:3.9-alpine ENV PATH = "/script:${PATH}" … -
Is it possible to add more than one field to Meta in Model?
I´m trying to add a unique together to my model, in which I have assigned permissions for backend roles. My model is like this: class Detail(models.Model): order=models.ForeignKey('Order',related_name='orders',on_delete=models.CASCADE,verbose_name='Order') component=models.ForeignKey('Component', related_name='order_component',on_delete=models.RESTRICT,verbose_name='Component') class Meta: unique_together = ('order', 'component') permissions = (("detail_list", "detail_list"),) When I try to save, it just keep me saying this: IndentationError: unindent does not match any outer indentation level I guess I could add permissions in a latter Model, but just for curiosity, anybody please could tell me if that´s the best approach, or if there is somethig I am missing? Cheers -
Filter Django ForeignKey Dropdown based on Current User
I am using django ClassBasedViews where I have a Project and Task Models. Each task is assigned to a project and both models register who created a recording in the created_by field. class Project(models.Model): name = models.CharField(max_length=100) ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) and then for the Tasks, I have class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=200) ... created_by = models.ForeignKey(User, on_delete=models.CASCADE) So the ClassBasedView to create the new task is like so, class CreateTask(LoginRequiredMixin, CreateView): template_name = 'project/new _task.html' form_class = TaskCreationForm success_message = "New Task Created" I need the dropdown in the form to Only show projects for the current logged-in user. I have gone through this post but the author did not implement my use case for *the current logged-in user. What can I do and how can I implement this?