Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
context must be a dict rather than module
When I am filtering for my search bar I am getting this error. I am not sure what I am doing wrong here Watching this tutorial: https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s views.py class pplList(LoginRequiredMixin,ListView): model = People context_object_name = 'people' def get_context_data(self, **kwargs): search_input = self.get.GET.get('search-area') or '' if search_input: context['people'] = context['people'].filter(name__icontains=search_input) return context people_list.html {%if request.user.is_authenticated %} <p>{{request.user}}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} <hr> <h1>Interviewee Dashboard {{color}}</h1> <a href="{% url 'pplCre' %}"> Add Candidates</a> <form method="get"> <input type = 'text' name = 'search-are'> <input type = 'submit' value = 'Search'> </form> <table> <tr> <th> Item</th> <th> </th> </tr> {% for people in people %} <tr> <td>{{people.name}}</td> <td><a href="{% url 'pplDet' people.id %}">View</a></td> <td><a href="{% url 'pplUpd' people.id %}">Edit</a></td> <td><a href="{% url 'pplDel' people.id %}">Delete</a></td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> -
Additional queryset in DetailView (using self)
I am creating application to manage home budget. I've got a few models - Date, Expense, Category, Income. It looks like this class Date(models.Model): name = models.CharField(max_length = 15) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='date') class Category(models.Model): name = models.CharField(max_length=100) budget = models.DecimalField(max_digits=8, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='category') date = models.ForeignKey(Date, on_delete=models.CASCADE, related_name='date', default='Styczeń 2022') class Expense(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='expense') date = models.ForeignKey(Date, on_delete=models.CASCADE, default='Styczeń 2022') class Income(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account_income") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='income') First of all user should choose a "Date", next it goes to DateDetailView. And on this DetailView I want to display Expense only for this Date. I tried wit objects.filter, but I don't know how I should write it properly. I wrote something like this class DateDetailView(DetailView): model = Date template_name = 'expense/date_detail.html' context_object_name = 'date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['expense'] = Expense.objects.filter(date=F('pk')) return context I also tried this class DateDetailView(DetailView): model = Date template_name = 'expense/date_detail.html' context_object_name = 'date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['expense'] = Expense.objects.filter(date=self.date) return context Have you got any … -
How to filter highest amount for each single date in Django
Modles: #Customer Table class Customer(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=30) phone = models.CharField(max_length=12) def __str__(self): return f"Customer : {self.name}" #Order Table class Orders(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_date = models.DateTimeField(auto_now_add=True) total_amount = models.PositiveIntegerField() def __str__(self): return f"Customer: {self.customer.name} | Total Amount: {self.total_amount}" Query I am using: order = Orders.objects.values('customer__id', 'customer__name', 'customer__email', 'customer__phone').annotate(Sum('total_amount')).order_by('order_date') This is the result that I am receiving from the whole record:result data Result that I needed should be One highest total amount from each date/day. Means it should return one highest total amount per date/day and each day may contain different number of records. For example if we need 5 days record and each day have 10 enteries(assume), then it should give us only five highest total amount order from five days(one record per day of highest total amount order). hope you got my question( i tried my best to explain). -
How to display list of products that were filtered and fetched in js in Django?
I am trying to make a filter on my website. So, I am getting the value of users choice and fetching it and sending to view. In my view funtion I filtered the products. I can see the result on the console, but I can not display it on the webpage. So, can someone help me to display filtered products on my webpage. html <div class="table__menu"> <div class="swiper table__filter-top-menu"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> {% for productT in product_types %} <div class="swiper-slide"> <a href="#" class="table__btn" data-type="ocean" data-product="{{productT.id}}" >{{productT}}</a><!--{% url 'category_detail' productT.slug %}--> </div> {% endfor %} </div> </div> <a id="filter-icon" href="#" class="table__filter-icon table__filter-icon--hidden"> <picture><source srcset="{% static 'img/Filter.svg'%}" type="image/webp"><img src="{% static 'img/Filter.svg'%}" alt=""></picture> </a> </div> <div id="filter-menu" class="table__filter"> <div class="table__col"> <span> Виды: </span> <ul class="table__filter-menu table__filter-menu--types"> {% for category in categories %} <li class="table__filter-item "><a href="#" data-product = "{{category.id}}" class="table__filter-btn vid-product">{{category.title}}</a></li> <li class="table__filter-item "><a href="#" data-product = "{{category.id}}" class="table__filter-btn vid-product">{{category.title}}</a></li> {% endfor %} </ul> </div> <div class="table__col"> <span> Пол: </span> <ul class="table__filter-menu"> {% for i in gender %} <li class="table__filter-item"><a href="#" class="table__filter-btn gender" data-product="{{i.id}}">{{i}}</a></li> {% endfor %} </ul> </div> </div> js function Filter(productTId,productVId,genderId){ var gender = document.querySelector('.table__filter-btn--active') console.log(gender) var productV = document.querySelector('.table__filter-btn--active-1') var productT = document.querySelector('.table__btn--active') … -
why I'm automatically redirected to url?
I'm trying to make a to-do list with django. Urls.py ` urlpatterns = [ path('', views.index, name='tasks'), path('add', views.add, name='add') ] views.py ` class NewForm(forms.Form): task=forms.CharField(label='Add new task') tasks = [] # Create your views here. def index(request): return render(request, "tasks.html", { 'tasks':tasks }) def add(request): if request.method == "POST": form = NewForm(request.POST) if form.is_valid(): task=form.cleaned_data["task"] tasks.append(task) else: return render(request, "add.html", { 'form': form }) return render(request, "add.html", { 'form': NewForm() }) tasks.html ` {% extends "layout.html" %} {% block body %} <body> <h1> TASKS </h1> <ul>{% for task in tasks %} <li> {{ task }}</li> {% endfor%}</ul> <a href="{% url 'add' %}"> go to add </a> </body> {% endblock %} `` add.html ` {% extends "layout.html" %} {% block body %} <body> <h1> add task </h1> <form action="{% url 'tasks' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit"> </form> <a href="{% url 'tasks' %}"> go to tasks</a> </body> {%endblock%} I've created an empty list in which the task should be added. expectation - When user fills the form and click on submit it should be added to the list and now I should view the form by visiting that url. instead of above I'm redirected to tasks … -
Linking VueJS (using Vite) and Django backend in a CRUD project where Fetch API is used
I am creating a CRUD project. Using vite I have decided to have VueJS to deal with frontend. I will use Django for backend. I have a form inside a vue component. How do I use data entered into this form to produce a json file and consequently create an object in my sqllite3 default django database? -
How do i rewrite Django function based views code in a class based view?
i have the following code for a function based view: fav = bool if post.favourites.filter(id=request.user.id).exists(): fav=True but i want to put that in the below class based view: class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['productobj'] = Post.objects.get(id = self.kwargs['pk']) return context i am fairly new to Django, so i don't know all that much about functions inside class based views and how to pass parameters from them. can anyone help to add the code to the above class based view? -
how to upload images on cloudinary
I am trying to build a deployable app and I am messing around with cloudinary. I am using Django, React, Postgres and Cloudinary. My question is: should you let the client (React) upload the images directly to cloudinary? Does this introduce some security concerns? On the cloudinary documentation it is written that this approach can be quite nice as you do not burden the server. And in case I had to go through my server(Django), how would I go about it. I am reading the python sdk docs on the cloudinary website but can't really grasp what to do if I want to use the server as medium. Thank you for your attention -
I am unable to save data from UserForm ( is form name) to database
i Create a model name Details and using this cerate a UserForm . and if i save form then it show 'UserForm' object has no attribute 'cleaned_data' can anyone help me to fix this error , thank you! -
how to store filtered data from database in temp model(based on user who filtered) and based on fetched it display random until its length end Django
Here I,m facing problem, i wrote a code where user search data based on given filter. i store in variable. now let have instance, i get back 5 record based on search now i want to display these record randomly until he have seen all records with a button to show next record. if he have seen record it must be deleted from DB. he is able to new search not before until he sees all fetched data. please help any python Django master. my goal is to make a randomizer to keep transparency. here is code. here is view.py it stores fetched data in query variable now i want to display this data one by one with button to user until its finished all fetched data. @login_required def database(request): if request.method=="POST": codename=request.POST['codeName'] To=request.POST['endDate'] From=request.POST['startDate'] #StartTime # print("date time ",To) logid=request.POST['avaya'] print("code from frnt end",codename) time=request.POST['time'] if time == "Less than 1 Minute": work_code = work_codes.objects.all() query = agents_performance.objects.filter(Q(StartTime__contains=f'{From,To}') | Q(Talktime__lt=60) & Q( Wrapupcodelist__contains=f'{codename}') & Q(LoginId=logid)).values() print("total fetch data",query.count()) random=query.order_by('?').first() context={'work_code':work_code,'upload':upload,'uploadcode':uploadcode,'random':random} return render(request, 'tables.html',context) elif time == "One to Three Minute": work_code = work_codes.objects.all() query = agents_performance.objects.filter(Q(StartTime__contains=f'{From,To}') | Q(Talktime__range=(60,180)) & Q( Wrapupcodelist__contains=f'{codename}') & Q(LoginId=logid)).values() print("total fetch data",query.count()) random=query.order_by('?').first() print("random",random) context={'random':random,'work_code':work_code,' … -
Power BI Dashboard Embed Code Using Django?
I am working on a Django web application which is supposed to use Power BI Embedded as a reporting . I also know that we can use to embede power bi dashboard with out code or less code in our website. But I need to embed power bi report via python code? If any one worked or faced this issue please help me? I get for other web frame works but I am supposed to use django. I tried the iframe way and it works but unfortunatly we are not comfortable with that? I want to know how I can embed using my power bi informations or API's in to django web frame work? -
500 Internal Server Error trying to fetch data with Django Rest Framework through Javascript
I'm trying to get the post data from the backend using fetch. However i am getting a 500 server error when trying to fetch the data. I have tried using .serialize() in the backend to pass the data. as well as trying to return the jsonResponse by serializing the query object which would give me this error: Object of type User is not JSON serializable. I tried it by sending an object and without an object. Any suggestions? code models.py class Post(models.Model): user = models.ForeignKey(User,on_delete=models.PROTECT, default='',null=True) message = models.TextField() date = models.DateTimeField() likes = models.ManyToManyField(User,blank=True,null=True,related_name="posts") def serialize(self): return { "id": self.id, "user": self.user, "likes": [user for user in self.likes.all()], "message": self.message, "date": self.date.strftime("%b %d %Y") } code urls.py path("post/<int:id>",views.post, name="post") code views.py @csrf_exempt def post(request,id): post = Post.objects.get(id=id) if request.method == "GET": return JsonResponse({"post":post.serialize()}) code script.js (post.getAttribute('name') is the post id) posts.forEach(post => { fetch(`post/${post.getAttribute('name')}`) .then(response => response.json()) .then(data => { console.log(data) }) )} -
How can I populate a model with non-form data?
I have Student, Class and StudentClass models. I would like a student to be able to join a new class by inputting the class_code into a form. To join a class the user's student_id and the class_code is saved to the StudentClass model. The student_id isn't a form field so should be obtained by querying the Student model with the logged-in user's username and returning the student_id. models.py: class StudentClass(models.Model): class Meta: unique_together = (('class_code', 'student_id'),) class_code = models.ForeignKey(Class, on_delete=models.CASCADE) student_id = models.ForeignKey(Student, on_delete=models.CASCADE) forms.py: class JoinClassForm(forms.ModelForm): class Meta: model = StudentClass fields = ['class_code'] views.py @login_required def join_class(request): if request.method == "POST": joinclass_form = JoinClassForm(request.POST or None) if joinclass_form.is_valid(): formclass_code = joinclass_form.data.get('class_code') if Class.objects.filter(class_code=formclass_code).exists(): joinclass_form.save(commit=False) joinclass_form.student_id = Student.objects.filter(username=request.user.username).values_list('student_id', flat=True) joinclass_form.save() return redirect('assignments') else: messages.success(request, ("This class doesn't exist!")) else: joinclass_form = JoinClassForm return render(request, 'join_class.html', {'joinclass_form': joinclass_form}) I've tried using a hidden_field for student_id, excluding student_id from the form fields and saving as commit=False, and I've gotten the same error: IntegrityError Not NULL constraint failed. Is there an error in my code that I have missed or am I using the wrong method? Thanks in advance Edit: Forgive me but copy-paste went kinda awry on the last set of … -
RotatingFileHandler set to 10MB but the size is much smaller
I just noticed that logs on the server are very small: api/logs$ ls -lah -rw-r--r-- 1 master www-data 7.5K Oct 29 14:50 root.log -rw-r--r-- 1 master www-data 15K Oct 29 14:50 root.log.1 -rw-r--r-- 1 master www-data 17K Oct 29 14:50 root.log.2 This is settings.LOGGING, as you can see, the root handler should rotate logs after they reach 10MB os.makedirs(BASE_DIR / "logs", exist_ok=True) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}", "style": "{", }, "simple": { "format": "{levelname} {message}", "style": "{", }, }, "handlers": { "console": { "class": "logging.StreamHandler", }, "root": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": BASE_DIR / "logs" / "root.log", "maxBytes": 1024 * 1024 * 10, # 1024 * 1024 * 10 = 10MB "backupCount": 2, "formatter": "verbose", }, "sendpulse": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": BASE_DIR / "logs" / "sendpulse.log", "maxBytes": 1024 * 1024, # 1024 * 1024 = 1MB "backupCount": 2, "formatter": "verbose", }, "slack__sendpulse": { "level": "INFO", "class": "external_sources.slack.SlackSendpulseHandler", "formatter": "verbose", }, }, "loggers": { "": { "handlers": ["console", "root"], "level": "INFO", }, "sendpulse": { "handlers": ["sendpulse", "console", "slack__sendpulse"], "level": "INFO", }, }, } Do you know where is the problem? -
Djnago Database Working Fine but Unable To Fetct Data on Template
In database data is adding sucessfully but when i want render it on template it shows nothing Here is my view file here is template file I treid to retype my code and check for errors everything is workig fine even i have created another project just to test there also working fine but i try to run this project it show empty -
shoping cart in django rest freamwork
I save the shopping cart in the Redis database. The codes I wrote in such a way that the user must be logged in to add the product to the shopping cart. I want to do something without getting the user ID and without the user having logged in to create the shopping cart for the users. What should I do to create a shopping cart instead of the user ID in the code I wrote? import redis r = redis.Redis(host='localhost', port=6379, db=0) class Cart: @classmethod def add_cart(cls, **kwargs): user_id = kwargs.get('user_id') product_id = kwargs.get('product_id') cart_name = f'{user_id}_{product_id}' if r.exists(cart_name): r.hincrby(cart_name, 'quantity', kwargs['quantity']) else: for field, value in kwargs.items(): r.hset(cart_name, field, value) return cart_name @classmethod def get_cart(cls, user_id): cart = [] for user_carts in r.scan_iter(f'{user_id}_*'): data = {key.decode('utf-8'): value.decode('utf-8') for key, value in r.hgetall(user_carts).items()} cart.append(data) return cart -
The problem of not displaying validation messages in allauth after overriding allauth templates
I use the allauth package to validate forms. The problem I have in this case is that I want to change the default templates of the allauth package and add my own styles and css classes to them. And I have done this, but my problem is that when the user enters incomplete or incorrect login information, no validation message is displayed to the user. I want to change the default allauth templates, such as login.html, signup.html, etc. and also I want to display my own authentication messages. Please guide step by step I because am learning Django, Thanks. This is login.html {% extends "base.html" %} {% load i18n %} {% load account socialaccount %} {% block head_title %}{% trans "Sign In" %}{% endblock %} {% block content %} <h1 class="head-line">{% trans "Sign In" %}</h1> {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} <div class="container"> <p class="text-center">{% blocktrans with site.name as site_name %}Please sign in with one of your existing third party accounts. Or, <a href="{{ signup_url }}">sign up</a> for a {{ site_name }} account and sign in below:{% endblocktrans %} </p> </div> <div class="socialaccount_ballot container"> <ul class="socialaccount_providers text-center border"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or … -
Django form still shows errors even after successful submission if I press back button
I made a Django form. If the user tries to submit the form when entering wrong data then error is showed in the form and it is not submitted but when the user enters correct data and submit the form it gets submitted. The problem is that when the user presses the back button, he can still see that error in the form. What can I do about it? -
ImportError: attempted relative import beyond top-level package?
MY Structure here: https://i.stack.imgur.com/HcQxb.png https://i.stack.imgur.com/rP3j5.png When I import model from accounts app to to_do app: #in to_do/models.py from ..accounts.models import Account I have this error: File "/home/ghost/projects/django_projects/To_Do_App/to_do_list/to_do/models.py", line 2, in <module> from ..accounts.models import Account ImportError: attempted relative import beyond top-level package How to fix it? -
Django Date calculation
Model: class JobCycle(models.Model): dateReceived = models.DateField(blank=True, null=True) dueDate = models.DateField(blank=True, null=True) dateOut = models.DateField(blank=True, null=True) fee = models.IntegerField(blank=True, null=True) def __str__(self): return "Job Cycle" + str(self.id) I want to make a calculation, the due date will never exceed the received date. i Want to do this in the model -
Django Admin Panel Filtering - Apply Changes on Specific Items
I have used django-admin-sortable2 for sorting items. Items model have a field of category. I wanted to sort items that have the same category. class Ordering(models.Model): item = models.OneToOneField( "Item", on_delete=models.CASCADE ) main_order = models.PositiveIntegerField( default=0, blank=False, null=False, ) class Meta: ordering = ("main_order", ) def __str__(self): return self.item.title def reorder(self): ordered_list = [] for order, item in enumerate(Ordering.objects.all(), 1): item.main_order = order ordered_list.append(item) MainPageCoupons.objects.bulk_update( objs=ordered_list, fields=["main_order", "coupon"] ) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.reorder() Is it possible in Django Admin Panel to change a field values for items that have the same value for specific field like category? -
Keep the aspect ratio by sorl-thumbnail in Django
i'm using sorl thumbnail library and i have a problme i cannot Keep the aspect ratio of my images . {% thumbnail product.image "268x250" quality=85 crop='center' as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} This is my code but it makes my pictures very Unclear cause it crops the picture very badly is there any solution, not crop the pictures and only make them smaller with keeping aspect ratio ??? i want keeping aspect ratio of my pictures -
Obtain DJango Authorization token using https only
I am not a web developer and hence my understanding of web development technology is limited. Hence please bear with me. I am trying to retrieve result from a Rest API using VBA. The rest API requires authentication using django framework. I initially tried to use HTTPRequest.Send "Get", URL, async, username, password I am getting {"detail":"Authentication credentials were not provided."} back. I gather that as the REST API I am working with uses django framework, I probably would need to authenticate using django. Hence my question is if I could submit username/password to django and retrieve authorisation token, by making https requests only - without having to reference various django objects (which would have entailed developing it outside VBA). Am I asking for the impossible? Thanks in advance -
What is the best way to separate two applications on a same Django Project?
I have two separate applications with different features but with the same back-end code base that runs on Django. These applications also have separate databases. But some Django apps (like custom user or an app for managing locations or custom authentication) are used in both projects; and developing, maintaining, and adding new features are getting harder beacause the project is growing large What is the best way to separate code bases for these projects? Should I migrate to microservices with Django (or something else)? Or is there a better way to -
How to compare in same model (Django) two specific fields
How to compare in same model (Django) two specific fields (which one is higher) and save result in third field(Boolean for example)?