Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement all CRUD methods in a single Class Based View in Django framework
Good day everyone. After countless attempts to solve my problem, I decided to turn here for advice. I am writing a small app with two models: Departments and Employees. And I decided to rewrite all the Function-Based Views to Class-Based Views. With Django REST framework I was able to implement the following solution: That is drf-api-view.py: from django.core.cache import cache from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.exceptions import ValidationError from rest_framework.pagination import LimitOffsetPagination from django_filters.rest_framework import DjangoFilterBackend from department.models.models import Department, Employee from department.rest.serializers import DepartmentSerializer, EmployeeSerializer class DepartmentPagination(LimitOffsetPagination): default_limit = 10 max_limit = 100 class EmployeePagination(LimitOffsetPagination): default_limit = 10 max_limit = 100 class DepartmentView(ListAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView): queryset = Department.objects.all().order_by('title') serializer_class = DepartmentSerializer filter_backends = (DjangoFilterBackend,) pagination_class = DepartmentPagination lookup_field = 'id' def list(self, request, *args, **kwargs): if isinstance(request.resolver_match.kwargs.get('id', None), int): return super().retrieve(request, *args, **kwargs) return super().list(request) def create(self, request, *args, **kwargs): title = request.data.get('title') if title is None: raise ValidationError({'title': 'Must not be empty'}) return super().create(request, *args, **kwargs) def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) if response.status_code == 200: department = response.data department_id = department['id'] cache.set(f'department_data_{department_id}', { 'title': department['title'], 'slug': department['slug'], }) return response def delete(self, request, *args, **kwargs): department_id = request.data.get('id') response = super().delete(request, … -
TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f5e95756920>
first time I ask on the website. I was testing a Django Restframework app. The is to check an unauthenticated user that wants to create a review. I got this error: TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f5e95756920>. this is the class test: class ReviewTestCase(APITestCase): def setUp(self): self.user = User.objects.create_user( username="example", password="Password@123") self.token = Token.objects.get(user__username=self.user) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) self.stream = models.StreamPlatform.objects.create( name="Netflix", about="#1 Platform", website="https://www.netflix.com" ) self.watchlist = models.WatchList.objects.create( platform=self.stream, title="Example Movie", storyline="Example Movie", active=True ) self.watchlist2 = models.WatchList.objects.create(platform=self.stream, title="Example Movie", storyline="Example Movie", active=True) self.review = models.Review.objects.create(review_user=self.user, rating=5, description="Great Movie", watchlist=self.watchlist2, active=True) def test_review_create(self): data = { "review_user": self.user, "rating": 5, "description": "Great Movie!", "watchlist": self.watchlist, "active": True } response = self.client.post( reverse('reviewcreate', args=(self.watchlist.id,)), data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(models.Review.objects.count(), 2) response = self.client.post( reverse('reviewcreate', args=(self.watchlist.id,)), data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) **#The test who cause the error** def test_review_create_unauth(self): data = { "review_user": self.user, "rating": 5, "description": "Great Movie!", "watchlist": self.watchlist, "active": True } self.client.force_authenticate(user=None, token=None) response = self.client.post( reverse('reviewcreate', args=(self.watchlist.id,)), data) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_review_update(self): data = { "review_user": self.user, "rating": 4, "description": "Great Movie! - Updated", "watchlist": self.watchlist, "active": False } response = self.client.put( reverse('review-detail', args=(self.review.id,)), data) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_review_list(self): response = self.client.get( reverse('movie-review', args=(self.watchlist.id,))) … -
html iterate through dictionary python in django
i trying to use defaultlist but it is not working in my Django app views.py: Mylist = defaultdict(list) Mylist["it is a girl "].append(room_id) Mylist["it is a boy"].append(name_id) .html: {% for key, value in mylist.items %} <tr> <td> Key: {{ key }} </td> <td> Value: {{ value }} </td> </tr> {% endfor %} what is wrong? -
Convert raw sql query to django orm
I written this query in PostgreSQL and I'm confused of conversion of this query to django orm SELECT count(*), concat(date_part('month', issue_date), '/', date_part('year', issue_date) ) as date FROM affiliates_issuelog WHERE tenant_id = '{tenant_id}' GROUP BY date_part('month', issue_date), date_part('year', issue_date) ORDER BY date_part('year', issue_date) desc, date_part('month', issue_date) desc I have this model that records the insertion of new affiliates by date and by institution (tenant), only I need to receive from the query the total amount of records inserted per month in the year, and I was using the listview to make my pages until then but I don't know how to filter this data using orm. class IssueLog(): tenant = models.ForeignKey("tenants.Federation", on_delete=models.CASCADE) issue_date = models.DateField( default=date.today, verbose_name=_("date of issue") ) class Meta: abstract = True verbose_name = _("Entrada de emissão") verbose_name_plural = _("Entradas de emissão") def __str__(self): return f"{self.institution}, {self.tenant}" My pages that return a list of data I did as the example below, is it possible to pass the data as I want through get_queryset()?, I already managed to solve my problem using the raw query, but the project is being done only with orm so I wanted to keep that pattern for the sake of the team. Ex: … -
How to log Django request time?
How to display Django requests time in my console? For exemple: "GET /cities/ HTTP/1.1", I need time of this response. -
Django form for adding emails connected to models
This is a bit hard to explain but I'll try my best. I am developing a website where I want a feature where the admins can add an email notification connected to a certain model. The admin should be able to Choose a model on the website, What event it should trigger on (create, update or delete), The email body and text. For example, if the admin adds an email to a model foo on a create event, the specified email should be sent to some recipient whenever a new foo is added to the database. I am attempting to implement a new model that contains some reference to the models, using post_save() to send emails, but it's turning out more complex than I thought. I have searched far and wide to find some addon that does this, but I haven't found any. Does anyone have any tips on specific functionalities that can help with this, or if there's a good addon that I can start with? -
Adding two column values with F class in django failed
The three columns in question are num1, num2 and total. All I want is to add the value of num1 and num2 to get the total value and populate the total column with that value. I am getting no errors but nothing is updating. Simply the code is having no effect. Addbanks is the name of the model. Here is the one liner that seemed to be best suited for this purpose- Addbanks.objects.all().update(total=F('num1') + F('num2')) Update method worked like a charm for me till now. I am surprised that it is not working. I will add some pictures for you to see how simple the models and views.py is. If you have any tips or any other way to achieve what I am trying to, that would be helpful. Thnaks. Views.py- models.py- The table looks like this- -
how to fix attribute error while running python manage.py run server
[enter image description here] how to fix this error -
Django in Docker on Nginx request to self fails when in the context of another request
I have a Django application deployed inside a container on top of Nginx using Dokku. One of the view functions of the Django application includes a request: views.py def foo(request): ... response = requests.get(url) ... It is probably noteworthy that url is the url of the Django application itself, so the request is from the application to itself. The request is to one of the API endpoints (the reasons for doing this are historical). When the view is called then the request to url fails with 504 gateway timeout. I cannot reproduce this in any other context specifically: There is no error when running on localhost with the development server, where url is then the url of the development app (localhost to itself works). There is no error when running on localhost with the development server, where I manually make the url the production url (localhost to production works). There is no error when running this request on the production server but outside of the view. Specifically, I did a docker exec into the container, started the Django environment (manage.py shell), and ran the exact request that the view was making, and it worked! (production to production works) It seems … -
How to check input type Django Rest?
I am developing an endpoint with the Django rest framework. My endpoint accepts file or text. On the frontend side, users can send text or file. I am confused about how to check input is a file or text? I have tried os.path.is_file() but it does not check InMemoryUploadedFile. Can anybody help me with this issue? -
How to use NPM modules inside python?
I have a python django application. And I need to use some functions from an npm library in my django application. This is how the javascript code looks like: const { signLimitOrder } = require("@sorare/crypto"); return JSON.stringify(signLimitOrder(privateKey, limitOrder)) How do I use signLimitOrder function from my django python application? What is the standard procedure to solve this problem? Rewrite the JS library in Python Run a nodejs server and use API to pass data to Python app Is there a python package to run Js libraries inside python? Thanks -
displaying json data to django template
i am getting data from mongodb and first inserting all the data into pandas and then converting that data to json data and then print that data in table format my views.py looks like this def generate(request): a=str(request.POST.get('level')) b= request.POST.get('status') c=(request.POST.get('startdate')) g=datetime.strptime(c,"%Y-%d-%m") d=datetime.strftime(g,"%Y/%d/%m") e=request.POST.get('enddate') h=datetime.strptime(e,"%Y-%d-%m") f=datetime.strftime(h,"%Y/%d/%m") output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\intern mongo\\indicator\\work\\water.py',a,b,d,f],stdout=PIPE,text=True) client=pymongo.MongoClient("mongodb://localhost:27017") db = client["water"] colle= db["waterlevel"] df3=pd.DataFrame() df4=pd.DataFrame() data_from_db = colle.find({},{"_id":0,"time":1,"status":1,"level":1}) for datta in data_from_db: df=pd.DataFrame(datta) df4=pd.concat([df4, df], ignore_index=True,axis=0) json_records = df4.reset_index().to_json(orient='records',date_format='epoch') data = [] data = json.loads(json_records) context = {'d': data} return render(request,'result.html',context) and my html template is this <!DOCTYPE html> <html lang="en"> <head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2 class="text-center"><u>water table</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>time</th> <th>status</th> <th>level</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% now "U" %} {% for i in d %} <tr> <td>{{i.time|date:'U'}}</td> <td>{{i.status}}</td> <td>{{i.level}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </div> </body> </html> the problem is I am getting DateTime in UNIX format I want it in readable date type format can someone suggest a better way to display pandas dataframe in Django template as a table other than … -
form rendering 'None' in production
When I use the password reset in development it works fine. However in production after the user opens the reset email the password reset form is not displayed however other forms on the site via crispy forms are working fine. Nothing has been changed from dev to production besides the url in the view. The server and dev are running the same version of crispy forms. I did it based off this tutorial and it seems I have made all the required changes for production When checking the urls of the email between production and dev i do not see an issue http://127.0.0.1:8000/reset/MQ/***hm*-e00d**b30b635b358be1573e********/ https://domain.co/reset/MQ/***ht*-71ff80c**580c6cecc3ffd44********/ If I try and render the form like {{ form }} it only renders None leading me to believe the context is not being passed view: def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)|Q(username=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" plaintext = template.loader.get_template('users/password_reset_email.txt') htmltemp = template.loader.get_template('users/password_reset_email.html') c = { "email":user.email, 'domain':'domain.com', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'https', } text_content = plaintext.render(c) html_content = htmltemp.render(c) try: msg = EmailMultiAlternatives(subject, text_content, 'myemail@email.com', [user.email], headers = {'Reply-To': 'myemail@email.com'}) msg.attach_alternative(html_content, "text/html") msg.send() … -
How to select one object each from django distinct queryset
Suppose class SavedPosts(models.Model): user = models.ForiegnKey(...) post = models.ForiegnKey(...) collection_name = models.CharField(...) I am getting colection names using SavedPosts.objects.filter(user_id=request.user.id).values("collection_name").distinct().order_by('collection_name') How do i get image of post from that collection? Just like instagram do. Can it be done without creating seperate model for collection? -
Django Breadcrumb error: Reverse for 'projectnotes_list' with no arguments not found
I am trying to use django-views-breadcrumbs to add breadcrumbs to a site. I can get it to work with some views but I am getting an error with a particular listview. When I attempt to visit this listview page I see the error. The error appears to be related to a need for the correct context. So far I have not been able to figure this out. The error: NoReverseMatch at /projects/project/1/notes/ Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z'] Request Method: GET Request URL: http://co1.localhost:8000/projects/project/1/notes/ Django Version: 3.1.14 Exception Type: NoReverseMatch Exception Value: Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z'] Exception Location: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages/django/urls/resolvers.py, line 689, in _reverse_with_prefix Python Executable: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/bin/python Python Version: 3.9.6 Python Path: ['/Users/user/Desktop/otools', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages'] Server time: Sun, 20 Feb 2022 15:52:17 +0000 The list view: class ProjectNotesList(ListBreadcrumbMixin,ListView): model = ProjectNotes template_name = 'company_accounts/project_notes.html' comments = ProjectNotes.comments def related_project(self, **kwargs): project = get_object_or_404(Project, id=self.kwargs.get('pk')) notes = ProjectNotes.objects.all return notes def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments')) The urls.py from django.urls import path, include from .views import CompanyProjects, … -
Calling view via ajax with submit button works, but hitting enter key just displays ajax dictionary
I have a todo list app adds a Task object to the database and appends it to the page, it is working without a problem. However, it only works when I click the submit button, if I hit the enter key, I just see the ajax data in my browser as such: {"task": {"id": 1, "title": "example task", "completed": false}} and I am curious as to why this is and if there is a way to change this functionality? The tutorial I'm following mentioned that on my form I must use <button type="button"> and not <input type = "submit"> because the ladder will "send the forms data directly to the TaskList view, but we want to use another way of sending requests so we need to disable this behavior." I imagine that is what is happening when I hit the enter key? Code: html: <form id = "createTaskForm" method="post" data-url = "{% url 'task_list_url' %}"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <button id = "createButton" type="button">Sumbit</button> </form> <div id = "taskList"> {% for task in tasks %} {{task.title}} {% endfor %} </div> JavaScript/jQuery: $(document).ready(function(){ $('#createButton').click(function() { // Get form data let … -
Like/Dislike Counter is not adding/removing after Click in Django project
This is a social media type project (Django/Python) and when I click on the Like/Dislike Button it does not register a Like or a Dislike.. Not getting an error simply nothing is happening. Code Below - thank you in advance! This is the entire code in my views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import PostForm from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.views import View from main_app.models import Post class PostList(ListView): def get(self, request, *args, **kwargs): posts = Post.objects.all() form = PostForm() return render(request, 'main_app/post_list.html', {'post_list': posts}) def post(self, request, *args, **kwargs): posts = Post.objects.all() form = PostForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() return render(request, 'main_app/post_list.html', {'post_list': posts}) class PostCreate(CreateView): model = Post fields = '__all__' success_url = '/posts/' class PostUpdate(UpdateView): model = Post fields = ['text'] success_url = '/posts/' class PostDelete(DeleteView): model = Post success_url = '/posts/' def show(request, post_id): post = Post.objects.get(id=post_id) return render(request, 'show.html', {'post': post}) class AddLike(View): def post(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) is_dislike = False for dislike in post.dislike.all(): if dislike == request.user.id: is_dislike = True break if is_dislike: post.dislike.remove(request.user) is_like = False for like in post.like.all(): if like == request.user: is_like … -
How I can remove the unwanted data and save only required results from Django form?
Submit I want to send form data to the backend without having unwanted data here fname I only want email. I am trying to build a function which will first validated by js so a bot protection. How can i made my django form completion to occur. <form id="regForm" name="myForm"> <div class="tab"> <h4 id="jsa" >Validation</h4> <p> <input placeholder="First name..." oninput="this.className = ''" name="fname" /> </p> </div> <h3 id="valid_error"></h3> <div class="tab"> Contact Info: <p> <input placeholder="E-mail..." oninput="this.className = ''" name="email" /> </p> </div> <div style="overflow: auto"> <div> <button type="button" id="prevBtn" onclick="nextPrev(-1)" > </button> {% csrf_token %} <button type="submit" id="nextBtn" onclick="nextPrev(1)" > Join </button> </div> </div> </form> So I want to submit my data with js validation -
Problem with filtering data via custom function in Python (Django)
I want to get 4 random objects from Product I'm trying to filter it by check_existing_id function and random.randint and I use while loop to get 4 objects from the database. However this piece of code in some cases returns only 3 objects. There is a bug hidden in the code and I have no idea where I need this to return exacly 4 elements every single time. I'm pasting the code below it's just a simple function: def check_existing_id(list,number): for i in range(len(list)): if list[i] == number: return False return True class GetRecommendedProducts(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): product_id = self.kwargs['product_id'] products_length = len(Product.objects.all()) id_list = [] while len(id_list) < 4: id = random.randint(0, products_length) if check_existing_id(id_list, id) and id != product_id: id_list.append(id) return Product.objects.filter(id__in=id_list) -
How to modify save function for model in Django
I have a problem. In my Department model I override save function. The logic is next: every Department can have one superior department, and one department can have many subsidiary dep's. My first if works correctly, if I choose superior dep's, when save existing instance, this superior in result have self as subsidiary. But my second if doesn't work. Do you have any idea what I am doing wrong? class Department(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) description = models.CharField(max_length=300, blank=True, verbose_name='description') subsidiary = models.ManyToManyField( 'self', blank=True, symmetrical=False, related_name='subsidiary_name') superior = models.ForeignKey( 'self', null=True, blank=True, related_name='superior_name', on_delete = models.SET_NULL) manager = models.ForeignKey( Manager, related_name='manager_name', null=True, on_delete = models.SET_NULL) status = models.BooleanField(default=True) proxy = models.ForeignKey( Manager, on_delete = models.SET_NULL, blank=True, verbose_name='Proxy', null=True, related_name='proxy_name') # TODO history = HistoricalRecords() def get_subsidiary(self): return "\n".join([p.title for p in self.subsidiary.all()]) def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) # override superior instance by adding subsidiary instance automatically if self.superior: superior_department = Department.objects.get(title=self.superior.title) superior_department.subsidiary.add(self) if self.subsidiary: subsidiary_dep = Department.objects.filter(title__in=self.subsidiary.values('title')) for dep in subsidiary_dep: dep.superior.add(self) -
How to add data to my table searching by user in html with Django
I am working on a project that needs to get attendance from students. The system has a page with a field to input student id or email and a submit button. And when inputting the Data into the form and clicking on the button it has to search for the student in the database and add +1 for their attendance. I have searched everywhere, but no idea how to do that. Could anyone help me ? -
Join Queries in Django
SELECT * FROM reservation LEFT JOIN auth_user ON reservation.personel_id_id = auth_user.id WHERE reservation.id='pk' AND auth_user.id='pk' Hello , I am trying to fetch result of this sql query in django. How can I do this Query using Django ORM's ? -
Will my django web app also work on linux?
So I am building a simple crud webapp using django on frontend I am using typescript no frontend frameworks or libraries whatsoever. And currently I am doing this on windows 10 but if I switch to linux Ubuntu completely and continue building this on linux, Will it have any problems when building it even if I use the same version of django and python that was on windows 10. I am asking this because of problems in past that it works on one machine but not on different so then vm's and container technologies came out. Appreciate any help. -
use of property decorator in Django to calculate Sum
I have two moldes in which one model consists of file field. I have to calculate total size of the files in the parent model within the property decorator. I think this could also be done inside the serializer class using the serializer method but I want within the property decorator. class Package(models.Model): name = models.CharField(max_length=50,blank=True) />....................other fields.........../ **/.........problem is here..../** @property def folder_size(self): all = self.details.all() all.annotate() return total Here I need help to calculate the sum of all files sizes of a single package. Class Details(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,null=True, related_name='details') notes = models.FileField(blank=True, null=True) @property def file_size(self): return self.file.size -
Performing a Subquery, Sum and Join in django ORM
I have 2 django models which aren't linked by ForeignKey due to legacy system. class Parent(model): name -> CharField() class Child(model) parent_name -> CharField() cost -> IntegerField() I want to achieve a left join which gives me all parent columns along with sum of cost column from children. SQL in postgres translates to select parent.name, sum(child.cost) as cost from parent join child on parent.name = child.parent_name group by parent.name; Is there any way to achieve this with django ORM I have tried a lot of things but https://code.djangoproject.com/ticket/28296 might be what is blocking.