Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Web App as Django with Azure SQL
I've got django rest application connected with Azure SQL. Connection with DB works on local pc (Win 10), each of the methods like get, post etc. BUT when I created app using 'Web app' on Azure Portal, connected it with Azure SQL got an error 'Can't open lib 'ODBC Driver 13 for SQL Server'. Tried to change ODBC Driver 13 to 17 but still doesnt work, got django, django-rest, pyodbc, pyodbc-azure in requirements.txt too. What can I do? :( -
Django and apache rewriterule
I have problem that I can't figure out. I have django in on server and browse connection is redirected from second server. The problem is that I want to django have "subfolder" address like: www.example.com/myapp. I have .htaccess in www/myapp folder with this commands: <Limit GET POST PUT DELETE> Allow from all </limit> RewriteEngine On DirectoryIndex disabled RewriteCond %{REQUEST_URI} ^/myapp(.*)$ RewriteBase /myapp/ RewriteRule ^(.*)$ http://example.com:69/$1 [P] Options -Indexes I can get the main page to loaded, but it can't load any static files, because it tries to load them from https://example.com/static/js.js. When I try to load page it works. https://example.com/myapp/static/js.js When I try to go other page with this address: www.example.com/myapp/second it leads me to this address: www.example.com/second. But if I try to go my "api" address: http://example.com/myapp/api/data/12/ it works fine, and I get my json data. If I move the .htaccess file to "root" then everything works fine. I tried to sett in myapp setting STATIC_URL = 'myapp/static/', but it didn't help. So I'm confused is the problem in django or in apache rewrite file. -
Web application similar to google forms in Django
I have worked on python and newbie to Django. I am planning to build a web application that takes numeric input and save it in local storage as csv file. Also no duplicate number to be stored. I am looking for reference how to start with. -
How to implement own field in django administration?
I am creating custom user model in django administration. I would like to implement field of id in window where you can add a new users. I use "add_fieldsets" in order to adding new additional fields to it . But it is possible inserting for example 'email', 'username', 'password1'. How can I implement own field ? Is it possible ? Here is my code : python : admin.py class CustomUserAdmin(UserAdmin): list_display = ('username', 'email', 'first_name', 'last_name', 'id') list_select_related = ('profile', ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username', 'password1','is_staff', 'is_active','last_login','first_name','date_joined') }), ) def get_inline_instances(self, request, obj = None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) -
Example uses queryset instead of model attribute for a DetailView extending class
On the django docs page the method get_object is explained for the DetailView class. They are using this code snippet as an example: from django.utils import timezone from django.views.generic import DetailView from books.models import Author class AuthorDetailView(DetailView): queryset = Author.objects.all() def get_object(self): obj = super().get_object() # Record the last accessed date obj.last_accessed = timezone.now() obj.save() return obj Here's the link. What I don't understand is why queryset attribute is used and why they are loading all objects of the Author from the database. Shouldn't the code be model = Author.objects.get(pk=self.pk) ? Considering it's not a ListView but a detail view -
django: how to annotate queryset with count of foreignkey reverse after Trunc?
models: class A(models.Model): created_on = models.DateTimeField() class B(models.Model): a = models.ForeignKey('A', verbose_name='bs') class C(models.Model): a = models.ForeignKey('A', verbose_name='cs') I want to count the number of B and C by A and group them. Here is my attempt, but the result is not correct. from django.db.models import Count, Q from django.db.models.functions import Trunc a_qs = A.objects.filter(Q(created_on__gte=start_date, created_on__lte=end_date)) g = a_qs.objects.annotate(time=Trunc('created_on', 'month')).values('time').order_by('time') result = g.annotate(a_total=Count('id'), b_total=Count('bs'), c_total=Count('cs')) Although this will not report an error, the result will be incorrect. I don't want to loop queryset. I have an idea that can meet my needs, but in the end I need to merge queryset. a_qs = A.objects.filter(Q(created_on__gte=start_date, created_on__lte=end_date)) a_g = a_qs.annotate(time=Trunc('created_on', 'month')).values('time').order_by('time') a_result = a_g.annotate(a_total=Count('id')) b_g = B.objects.filter(a__in=a_qs).annotate(time=Trunc('a__created_on', 'month')).values('time').order_by('time') b_result = b_g.annotate(b_total=Count('id')) c_g = ... c_result = ... -
Dividing posts in dynamic categories based on likes and comments in django ORM
I have two tables in django which are Post and Comment such as class Post(models.Model): title = models.CharField() desc = models.TextField() likes = models.ManyToManyField(User, on_delete=models.CASCADE) class Comment(models.Model): comment = models.CharField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Now on home page I want to show posts divided based on no of likes and comments. For example: Category 1 will have posts which have likes and comments between 0-5 Category 2 will have posts which have likes and comments between 6-10 Category 3 will have posts which have likes and comments between 10-15 Category 4 will have posts which have likes and comments between 15 and above. I wrote following query for Category 1 posts= Post.objects.annotate(total_likes=Count('likes')).filter(total_likes__lte=5) \ .annotate(total_comments=Count('comment__comment')).filter(total_comments__lte=5) But problem is that it is only returning data when when both are under limit, if likes are 6 but comment are less than 5 then i want it to be in Category 1, Unless both conditions satisfy, Same for other categories, I did not found any helpful solutions so far. How can we implement this dynamic categorization in Django ORM? -
Post data from Angular8 contains empty QueryDict but data in request.body in Django
Here's my code in Angular8 which is accessing a view built in Django: this.http.post('/api/insert', {'csv':this.csvContent}, httpOptions).subscribe(); I want the post data to contain a string which has contents in the form of csv Here is my corresponding view in Django: @csrf_exempt def insert_table(request): logging.debug(request.body) logging.debug(request.POST) with open(settings.MEDIA_ROOT + 'data/table.csv', 'w') as file: file.write(request.POST.get('csv', 'a,b,c')) return JsonResponse({'csv': request.POST.get('csv', 'a,b,c')}) request.POST contains < QueryDict: {} > while request.body contains b'{"csv":"a,b,c\\r\\n1,2,1\\r\\n4,5,6\\r\\n1,7,1\\r\\n"}' when I actually do a POST request from Angular How do I use this? -
Updating a like on a post in DRF
I'm trying to write a view in django (DRF) that allows users to add a like on a post, update the like state (like/dislike) on the post and delete the like on a post. The post ID is sent in the paramters and the user ID is extracted from the auth token. I figured out how to do the first two but I can't figure out how to do the update. Here's what I have so far in my view: class LikeView(generics.CreateAPIView, UpdateModelMixin, DestroyModelMixin): serializer_class = LikeSerializer queryset = Like.objects.all() lookup_field = 'post' permission_classes = [IsAuthenticated] def get_object(self): post = self.request.query_params.get('post') user = self.request.user.id return self.get_queryset().filter(post=post, user=user) # retrieve user ID from token, validate data and save the like on post (working) def post(self, request, *args, **kwargs): data = self.get_data(request) serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response('Like has been saved') def put(self, request, *args, **kwargs): data = self.get_data(request) serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() # working def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) # add the data from param and token to a copy of the request body # to use with the serializers def get_data(self, request): data = request.data.copy() data['post'] = self.request.query_params.get('post') data['user'] = request.user.id return data What … -
Unable to lookup 'Time_From' on SubjectRoomSchedule or SubjectRoomSchedule
This is my first time encountered this error, idont know how to fix this, please help me... my models.py class SubjectRoomSchedule(models.Model): Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) Classroom =models.ForeignKey(Room, related_name='+', on_delete=models.CASCADE,null=True) Day_Name= models.ForeignKey(DayName, related_name='+', on_delete=models.CASCADE,null=True) Time_From= models.ForeignKey(TimeName, on_delete=models.CASCADE,null=True,blank=True) Time_To= models.ForeignKey(TimeName, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Remarks = models.TextField(max_length=500,null=True) class TimeName(models.Model): Display_Sequence = models.IntegerField() Description = models.CharField(max_length=500,blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) this is the traceback -
Are POST requests cached in Django?
I want to get some view cached depending on the POST data sent to it. Does the django.views.decorators.cache.cache_page decorator do that automatically or do I need to tweak it somehow? In the latter case, how should I do that? -
how to pass three searching parameters only and one of them is selected from options in for loop using Django as a frame work
I have a form that has to pass three searching parameters. These parameters are “post city”, “ post category”, and “ post subcategories” respectively. I am using Django for the backend, Thus, the from is populated using Django variables. I used for loop to fill out the selection list of “subcategories” from the database. The “post city” is preselected as well as “ post category”. Therefore, I put them as hidden inputs. However, there is only one city as well as post category within the for loop but they will be repeated while for loop is iterating over the items but I could not keep them out of for loop because I need for loop to select with category we are in. I want to pass only three inputs “ with no repeated input to the search form and I want when user click on the “ post subcategories” all three parameters are passed. “The question is “ how can I let the user click on the “subcategory” as “an anchor link” then only three inputs “post city”, “ post category”, and “ post subcategories” are passed. In addition, how can the form know which selection among the “subcategories” list … -
Is it best practice to validate fields in ModelSerializer for the fields that already have validators in Django model by accessing the the database?
for example I have a django model as class User(models.Model): email = models.EmailField(required=True, unique=True) Isnt it redundant and against DRY principle to validate again in the ModelSerializer as following? class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def validate_email(self, email): try: User.objects.get(email=email) raise serializers.ValidationError("Email address already used") except User.DoesNotExist: return email The validate_email method feels kind of against the DRY PRINCIPLE and wrong in this context since we have to access Database to validate in this method. please correct me. -
Django Rest Framework - Customize LimitOffsetPagination
I tried to include Pagination in my Django Rest Framework to limit the number of outputs the query provides. For that I used LimitOffsetPagination. Here is my output: { "count": 59, "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3", "previous": null, "results": [ { "id": 1, "contactName": "Mr.Important" }, { "id": 2, "contactName": "Mrs.VeryImportant" }, { "id": 3, "contactName": "Mr.NotSoImportant" } ] } My question is: Is it possible to customize the output so that the next & previous links appear within the results JSON object? What I want is something like : { "count": 59, "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3", "previous": null, "results": [ { "id": 1, "contactName": "Mr.Important", "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3", "previous": null, }, { "id": 2, "contactName": "Mrs.VeryImportant" "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3", "previous": null, }, { "id": 3, "contactName": "Mr.NotSoImportant", "next": "http://127.0.0.1:8000/contacts/getContacts/?limit=3&offset=3", "previous": null, } ] } -
Django: keep log after deleting a foreignkey
My question is simple: I have a Folder model, and I have a Log model. Here are the simplified examples: class Folder(models.Model): name = models.CharField(max_length=100) class Log(models.Model): folder = models.ForeignKey(Folder, on_delete="I NEED HELP HERE") What this means is, A folder is created by a User, and each action done on the folder, is logged by using the Log model (user edited folder, user did this with folder, etc...) What I want to do is simple: if some admin deletes the folder completely, I want to still keep the name of the folder. All actions in the on_delete attribute, do not let me do that. Any ideas? Thank's! PS: those are not the real models, just an illustration of what I want to do. The real ones are 100+ lines of code :P -
Jaeger traceID for request
I'm playing with JaegerTracing in Django using tutorial https://github.com/contino/jaeger-django-docker-tutorial. Now I don't know how to take out traceId from response headers because it's not there. When finding traces in Jaeger UI it returns response with data (see also screenshot below): { "data": [{ "traceID": "885bef8bbc18649c", "spans": [{ "traceID": "885bef8bbc18649c", "spanID": "cc4a59c2161aa05d", "flags": 1, "operationName": "test", "references": [], "startTime": 1576579367614065, "duration": 430, "tags": [{ "key": "sampler.type", "type": "string", "value": "const" }, { "key": "sampler.param", "type": "bool", "value": true }, { "key": "component", "type": "string", "value": "django" }, { "key": "span.kind", "type": "string", "value": "server" }, { "key": "http.method", "type": "string", "value": "GET" }, { "key": "http.url", "type": "string", "value": "/polls/test/" }, { "key": "path", "type": "string", "value": "/polls/test/" }, { "key": "method", "type": "string", "value": "GET" }, { "key": "http.status_code", "type": "int64", "value": 200 }], "logs": [], "processID": "p1", "warnings": null }], "processes": { "p1": { "serviceName": "polls_app", "tags": [{ "key": "hostname", "type": "string", "value": "12625857e878" }, { "key": "ip", "type": "string", "value": "172.23.0.3" }, { "key": "jaeger.version", "type": "string", "value": "Python-3.13.1.dev0" }] } }, "warnings": null }], "total": 0, "limit": 0, "offset": 0, "errors": null } I suspected it in response headers but it is not. How can I do … -
How to use get_template_name()?
I have two class ListView and I want to use two different templates in the same view. How to combine into one class? I don't know how to use get_template_name. This is my two views look like: class HomeListView(ListView): model = Home paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["name_home"] = Home.objects.all() context["name_fer"] = Home.objects.all().order_by("?")[:4] return context class HomeFerListView(ListView): template_name = "homes/homefer_list.html" model = Home paginate_by = 12 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["fer_long"] = Home.objects.all().order_by("?")[:6] return context Can Anybody help me out on this? Thanks a lot. -
Django channels 2.X profiling
I am have Django Channels 2 application with many database queries. I am try use https://silk.readthedocs.io/en/latest/ but it not working without middleware. Django channels don't tach django middleware -
Django Template Filter With Respect to Boolean Variable
My Html {% for category in categories %} <div class="row"> <h3 style="padding-left: 15px; padding-bottom: 15px">{% filter upper %}{{ category.name }}{% endfilter %}</h3> </div> <div class="row"> {% with products=category.product.all|is_available:True %} {% for product in products|slice:":4" %} <div class="product-width col-xl-3 col-lg-3 col-md-3 col-sm-6 col-12 mb-30"> <div class="product-wrapper"> <div class="product-img"> <a href="{% url 'shop:product' category.name product.id %}"> <img alt="" src="{{product.image.all.0.image.url }}"> </a> <div class="product-action"> <a class="action-wishlist" href="#" title="Wishlist"> <i class="ion-android-favorite-outline"></i> </a> <a class="action-cart" href="#" title="Add To Cart"> <i class="ion-android-add"></i> </a> </div> </div> <div class="product-content text-left"> <div class="product-title"> <h4> <a href="{% url 'shop:product' category.name product.id %}">{{ product.name|title }}</a> </h4> </div> <div class="product-price-wrapper"> <span>{{product.price}} TL</span> </div> </div> </div> </div> {% endfor %} {% endwith %} </div> <div class="row justify-content-end"> <a href="{% url 'shop:category' category.name %}">Daha Fazla...</a> </div> {% endfor %} My Model Each product has a many-to-many relation with categories and products also have an is_available variable. class ProductCategories(models.Model): name = models.CharField(max_length = 60) image = models.ImageField(upload_to = 'ProductCategories') publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) is_available = models.BooleanField() class Product(models.Model): category = models.ManyToManyField(ProductCategories, related_name="product") name = models.CharField(max_length = 60) price = models.DecimalField(max_digits=65, decimal_places=2) description = models.TextField() publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) stock_number = models.IntegerField() is_available = models.BooleanField() My View categories = ProductCategories.objects.all() return render(request, 'shop/shopping.html', {'categories' : categories}) … -
Hide critical data in template based on user access level
Suppose I have a Item model, where Item objects can either be public (accessible to all users) or private (accessible only to authenticated users): class Item(models.Model): title = models.CharField(max_length=100) is_public = models.BoleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) #... secret_key = ... class Meta: # I need to keep items in order: ordering = ('-created_at',) What I need is to list all items using a generic.ListView - keeping the order - but hide the secret_key of those items with is_public=False for anonymous users. So in the template, I hide the secret_key if the user is not authenticated, like: {% if request.user.is_authenticated %} <p>{{ item.title }} - {{ item.secret_key }}</p> {% else %} <p>{{ item.title }} - This item is private. Sign up to see the secret_key!</p> {% endif %} and the ListView is like: class ItemListView(ListView): model = Item paginate_by = 10 I'm aware that I can send two separate querysets for non logged-in users to the template, one for public items and the other for private ones; but I'm not sure how can I keep the order ('-created_at') in this approach. The question is: Is it safe to send all the secret_keys to the template and hide them for non logged-in users … -
Pagination of Django generic ListView does not work
I am new to Django and currently I am trying to integrate a webscraping backend code to a django project. While displaying my results from the webscraping, I am unable to paginate my results page which is a Django ListView. Setting paginate_by under my ListView is not working. Any help is appreciated. Thank you. Below are some of my code: views.py (paginate_by = 5 is not working) class PostListView(ListView): model = ResultsTable template_name = 'app/results.html' paginate_by = 5 def get_queryset(self): return ResultsTable.objects.all() def post(self, request, *args, **kwargs): self.queryset = self.get_queryset() global name name = request.POST.get('input') for i in range(len(singaporews)): t = threading.Thread(target=Webscraper, args=[singaporews[i], name, webdriver.Chrome('/Users/angyangcheng/chromedriver')]) allthreads.append(t) t.start() for i in allthreads: i.join() return super(PostListView, self).get(request, *args, **kwargs) def get(self, request, *args, **kwargs): return self.self.response_class( request=self.request, template=self.get_template_names()) def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) global name context = { 'links' : ResultsTable.objects.all, 'name' : name, 'count' : ResultsTable.objects.all().count() } return context The code under my post method is mainly my webscraping logic. results.html (pagination code) {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/cars?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/cars?page={{ … -
Unable to filter Elements of Foreign Key Model using Django-Rest
models.py class ViewType(models.Model): title = models.CharField(unique=True, max_length=128, db_column='view_name') viewType = models.CharField(max_length=64, choices=VIEW_TYPES, db_column='view_type') bannerImage = models.CharField(max_length=1024, db_column='banner_image', blank=True) status = models.CharField(max_length=16, db_column='status', choices=ITEM_STATUS, default = 'active') position = models.IntegerField(db_column='position', default=0) def __str__(self): return self.title class Meta: ordering = ['position'] # List Item class List(models.Model): position = models.IntegerField(db_column='postion', default=0) associatedView = models.ForeignKey(ViewType, db_column='associated_view', on_delete=models.DO_NOTHING, related_name='list') bannerImage = models.CharField(max_length=1024, db_column='banner_image', blank=True) listingPrice = models.CharField(max_length=32, db_column='listing_price', blank=True) listingCurrency = models.CharField(max_length=32, db_column='listing_currency', blank=True) status = models.CharField(max_length=16, db_column='status', choices=ITEM_STATUS, default = 'preview') expireAt = models.DateTimeField(null=False, blank=False, db_column='expire_at') createdAt = models.DateTimeField(auto_now_add=True, null=True, blank=True, db_column='created_at') updatedAt = models.DateTimeField(auto_now=True, null=True, blank=True, db_column='updated_at') def __str__(self): return self.position class Meta: verbose_name = 'List Items' verbose_name_plural = 'List Items' class ViewAll(models.Model): isEnabled = models.BooleanField(db_column='is_enabled') associatedView = models.OneToOneField(ViewType, db_column='associated_view', on_delete=models.DO_NOTHING, related_name='viewAll') class Meta: verbose_name = 'View Widget' verbose_name_plural = 'View All Widgets' serializer.py class ViewAllSerializer (serializers.ModelSerializer): class Meta: model = ViewAll fields = '__all__' def to_representation(self, instance): data = super(ViewAllSerializer, self).to_representation(instance) data['redirection'] = RedirectionSerializer(instance.redirection).data return data class ListSerializer(serializers.ModelSerializer): class Meta: model = List fields = '__all__' def to_representation(self, instance): data = super(ListSerializer, self).to_representation(instance) data['redirection'] = RedirectionSerializer(instance.redirection).data return data class ViewTypeSerializer(serializers.ModelSerializer): list = ListSerializer(many=True, read_only=True) viewAll = ViewAllSerializer(read_only=True, many=False) class Meta: model = ViewType fields = '__all__' views.py class ViewAllViewset(viewsets.ModelViewSet): queryset = ViewAll.objects.all() … -
Django Rest Framwrok - schedule action [closed]
I am making an API gateway with Django with the goal of collecting data from various sources via POST. The data is the logged to a database. It would be ideal for this data to be elaborated every n minutes. How can I do this in Django Rest Framework? -
All equal values created by Faker using Factory Boy
Using Factory Boy and Faker in a Django project, I notice that objects created using Factory Boy, and using Faker to create names (company names in this example) doesn't create a unique name for new objects. Main question: are we using Faker wrong when using it as a separate library (first example), or is there just something inherent about Factory Boy that prevents Faker from working correctly as a separate library, when used with Factory Boy? import factory ... from faker import Faker from faker.providers import company ... fake = Faker('nl_NL') fake.add_provider(company) class PolicyBrandFactory(factory.django.DjangoModelFactory): class Meta: model = PolicyBrand name = fake.company() Results in (Pycharm debugger screenshot): (the point being non-unique company names) In the Factory Boy documentation I read that they have a wrapper around Faker, and using that I do get unique results: import factory ... class PolicyBrandFactory(factory.django.DjangoModelFactory): class Meta: model = PolicyBrand name = factory.Faker('company', locale='nl_NL') And the result: -
ModelSerializer and ModelViewSet in django rest framework
In DRF, we can use create/retrieve/update/destroy/list methods in ModelViewSet to handle GET, POST, DELETE, PUT request. and there is another set of methods in ModelSerializer namely create and update methods. Under what condition should I faver methods in ModelSerializer over those in ModelViewSet and viceversa?