Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read list in django template
Could someone shed a light to help me to solve this nested list problem in Django template. I come across a list as such summary = [['Summary 1 CODE018'], [['Directory/File Name', 'Result']], [[['dir/var1/file1.txt', 'pass'], ['dir/var2/file2.txt', 'pass'], ['dir/var1/file3', 'pass'], [[['null']]]] How do I loop the above list so that I can get a table such as the first index is the table title, index1 is the table title and the rest (except when is it null) is the table body? Please take note that the last item could be [[['null']]] or [[['null', 'Info on directory CODEA18']]] which should be skip when null is detected. Expected: Summary 1 CODE018 Directory/File Name Result dir/var1/file1.txt pass dir/var2/file2.txt pass dir/var3/file3.txt pass My faulty code as below <table id="myTable"> {% for list in summary %} <tr> <td> {{ list.0 }} </td> <tbody> <td> {{ list.0.0 }} </td> <td> {{ list.0.0.0 }} </td> </tbody> </tr> </table> -
Django - How to change the column name after do query (objects.filter)?
I got this query: flight_list = FlightScheduleV2.objects.filter(departure_airport = departure_airport, arrival_airport = arrival_airport, departure_scheduledtime__gte = CURRENT_TIMESTAMP ).values("key", "flightnumber", "departure_scheduledtime") Obviously, it would return something like this: {'key': ......., 'flightnumber': ....., 'departure_scheduledtime':....} However, the front-end expects to receive something like this {'flight_id' : ....., 'flight_number': ...., 'departure_time': ....} Literally, I need to change the key name of the result, however, I did not know which Django function could do so. -
Implement Ajax in a Django Project not working properly
I am trying to implement a like button to my blog post using Ajax, I am facing an error which I am unable to fix so I started from scratch more than once with the following steps: Created Post model and Like model Added the views which is currently working perfectly fine when I click like and unlike I took the like section from the post_detail.html and added it in a separate html like_section.html added the ajax with the correct values Now my problem is that when I press the like button a new page is opened with ajax output {"form": "....(html and ajax codes repeated)......"} How do I fix this error so that I can submit a like without refreshing the page? Here are the models for Posts.py class Post(models.Model): ---------other attributed like: title, content, author, date_posted, slug----- likes = models.IntegerField(default=0) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Here are the views: def like_post(request): user = request.user if request.method == 'POST': post = request.POST.get('post_id') post_obj = Post.objects.get(id=post) current_likes = post_obj.likes if user in post_obj.liked.all(): post_obj.liked.remove(user) current_likes = current_likes - 1 else: post_obj.liked.add(user) current_likes = current_likes + 1 post_obj.likes=current_likes post_obj.save() like, created = Like.objects.get_or_create(user=user, post_id=post) if not … -
H18 error occurs when a POST request is sent from django to a server hosted by Heroku
I made an API for writing posts including image using django rest frameworks. We then hosted this server in heroku and used the cloudinary to store the image. But whenever I send a POST request to this API, the following error is sent from heroku. sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/feed/post" host=coatcode.herokuapp.com request_id=c39478d9-b8e3-4b25-9b5f-2a9a04bc87b0 fwd="221.168.22.204" dyno=web.1 connect=1ms service=398ms status=503 bytes=484 protocol=https When I searched, I realized that this error was a matter of speed or image capacity. Then how can I improve my django code to speed up and solve this error? Here's my code. views.py class CreatePostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(owner=self.request.user) def create (self, request, *args, **kwargs) : super().create(request, *args, **kwargs) return Response({'success': '게시물이 저장 되었습니다.'}, status=201) serializers.py class PostSerializer (serializers.ModelSerializer) : owner = userProfileSerializer(read_only=True) like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() images = ImageSerializer(read_only=True, many=True) liked_people = LikeSerializer(many=True, read_only=True) tag = serializers.ListField(child=serializers.CharField(), allow_null=True, required=False) comments = CommentSerializer(many=True, read_only=True) class Meta : model = Post fields = ('id', 'owner', 'title', 'content', 'view_count', 'images', 'like_count', 'comment_count', 'liked_people', 'tag', 'created_at', 'comments') def create (self, validated_data) : images_data = self.context['request'].FILES post = Post.objects.create(**validated_data, created_at=str(datetime.now().astimezone().replace(microsecond=0).isoformat())) for i in range(1, 6) … -
Creating a Bootstrap Carousel in Django project, Can click on prev
I am trying to create a carousel in my django project using bootstrap. I am trying to the carousel with captions. I am using a for loop t go through my data. I can click next, but I cannot click on previous. Any help? thanks **<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleCaptions" data-slide-to="1" ></li> <li data-target="#carouselExampleCaptions" data-slide-to="2" ></li> </ol> {% for post in slider_posts %} <div class="carousel-inner"> <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ post.image.url }}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> {% for tag in post.tag.all %} <button class="btn btn-info"><a class="cat" href="{% url 'tag_detail' tag.slug %}">{{ tag.title }}</a></button> {% endfor %} <a href="{% url 'detail' pk=post.pk slug=post.slug %}"><h4>{{ post.title }}</h4></a> <p>{{ post.content | truncatechars:150 }}</p> <div class="date"> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> {{ post.publishing_date}}</a> <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 05</a> </div> </div> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div>** -
django-ckeditor: How can I limit TextColor and BGColor choices in toolbar?
This is my CKEDITOR_CONFIGS in settings.py: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Italic', 'Underline'], {'name': 'colors', 'items': ['TextColor', 'BGColor']}, ] }, } That's all I need for now. However, I'm getting a whole lot of color choices for TextColor and BGColor, and I want to limit them to a very specific set of colors. Is there a way in which I can choose the colors that I want to be available? I can't find how to customize that. -
Editing is_staff permissions for Djnago admin panel
I want to edit the is_staff role permissions so that they are only capable of viewing the data on the admin panel and not making any changes, I want to give the support staff this role. I understand the is_staff has edit, add, delete and view permissions. How would I create a group so that I can add any new staff members to this group I am really new to django, so please explain in the simplest of manner -
Add Prometheus metrics outside manage.py - docker related
My manage.py looks like this: import os import sys from prometheus_client import start_http_server, Summary import random import time if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") s = Summary('request_latency_seconds', 'Description of summary') s.observe(4.7) # Observe 4.7 (seconds in this case) try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) If I run my django app using docker, I am able to see added Summary metrics. However, if I try to run Django management command, created metric object will be not added to Prometheus. I am basically trying to add many metrics the same way I did it with Summary, but I dont want my exposed port to be stopped (if I run loop inside manage.py, it will stop)... ideally, if I would be able to run management command (I will exec to running container, and run command like "python … -
AttributeError: 'str' object has no attribute 'likes'
I am trying to get the count of likes related to post so I created the following in the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.IntegerField(default=0) I am already able to get the no. of likes but I am trying a different method, I am just trying to know how the method works. Here is the views where I try to add to it when a like is made def like_post(request): user = request.user post = request.POST.get('post_id') current_likes = post.likes <------------Error coming from here if request.method == 'POST': post_obj = Post.objects.get(id=post) if user in post_obj.liked.all(): post_obj.liked.remove(user) current_likes = current_likes - 1 else: post_obj.liked.add(user) current_likes = current_likes + 1 post.likes=current_likes post.save() like, created = Like.objects.get_or_create(user=user, post_id=post) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post': post, } return redirect('blog:post-detail', slug=post_obj.slug) The issue now is that I am receiving AttributeError at /blogs/like 'str' object has no attribute 'likes' I have tried to fix it but I don't know how. The source of error is highlighted here: current_likes = post.likes -
Should I rewrite my code to make use of through fields?
I built the models in my Django projects before learning about through fields, and now I realize I could have made use of them. I'm wondering what the benefits of using through fields are, and if I am missing out on them with my model structure: models.py (non-relevant fields removed) class Language(models.Model): name = models.CharField(max_length=255) class Collaborator(models.Model): name = models.CharField(max_length=255, blank=True) language = models.ManyToManyField(Language, verbose_name="languages", related_name='language_collaborator_languages', blank=True) class Item(models.Model): name = models.CharField(max_length=255, unique=True) language = models.ManyToManyField(Language, verbose_name="list of languages", related_name='language_item_language', blank=True) class Document(models.Model): name = models.CharField(max_length=255) language = models.ManyToManyField(Language, verbose_name="list of languages", related_name='language_document_language', blank=True) class Dialect(models.Model): document = models.ForeignKey('Document', related_name='document_dialect_document', on_delete=models.CASCADE, null=True, blank=True) item = models.ForeignKey('Item', related_name='item_dialect_item', on_delete=models.CASCADE, null=True, blank=True) collaborator = models.ForeignKey('Collaborator', related_name='collaborator_dialect_collaborator', on_delete=models.CASCADE, null=True, blank=True) language = models.ForeignKey('Language', related_name='language_dialect_language', on_delete=models.CASCADE) name = models.CharField(max_length=255) To describe the conceptual data model: each instance of Items, Documents, and Collaborators, can all have multiple languages, and for each instance of these relationships I specify a dialect with the Dialect model. I use get_or_create() in views.py to generate instances of Dialect, in which I define the language field and one of the item/document/collaborator fields. (Note: If you are familiar with languages/linguistics, you might point out that I could rename the Language model as … -
Weblate Permission denied. Unable to stat ... 403 Forbidden
https://docs.weblate.org/en/latest/admin/install.html#uwsgi I have been following the installation procedure to install Weblate on Ubuntu 18.04.04 LTS. I have installed all the dependencies, python 3.6, and also had to setup a system unit called `celery-weblate.service': [Unit] Description=Celery Service (Weblate) After=network.target [Service] Type=forking User=weblate Group=weblate EnvironmentFile=/etc/default/celery-weblate WorkingDirectory=/home/weblate-env RuntimeDirectory=celery RuntimeDirectoryPreserve=restart LogsDirectory=celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target I also had to setup a weblate file in /etc/default for variables that are used in the daemon: # Name of nodes to start CELERYD_NODES="celery notify memory backup translate" # Absolute or relative path to the 'celery' command: CELERY_BIN="/root/weblate-env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="weblate.utils" # Extra command-line arguments to the worker, # increase concurency if you get weblate.E019 CELERYD_OPTS="--beat:celery --queues:celery=celery --prefetch-multiplier:celery=4 \ --queues:notify=notify --prefetch-multiplier:notify=10 \ --queues:memory=memory --prefetch-multiplier:memory=10 \ --queues:translate=translate --prefetch-multiplier:translate=4 \ --concurrency:backup=1 --queues:backup=backup --prefetch-multiplier:backup=2" # Logging configuration # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # … -
how to pass the address.pk as a parameter after the form has been successfully submitted in a django form?
I created an address form in a Django project and I have also created an AddressDetailView in views.py. When a user successfully submits the address form, I want to redirect the user into the address_details.html by passing the address.pk as the parameter. But I don't know how to pass that parameter. I keep getting an error as shown belong and I don't know how to fix it. this is the models.py for the address model route_name = models.ForeignKey(Route, on_delete=models.CASCADE) name = models.CharField(max_length=30) city = models.ForeignKey(City, on_delete=models.SET_NULL, blank=True, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, blank=True, null=True) location = models.CharField(max_length=30, choices=LOCATION_CHOICES, default='NULL') username = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) make_initial_location = models.BooleanField() def __str__(self): return self.name def get_absolute_url(self): return reverse('address-detail', kwargs={'pk': self.pk}) this is the Address form in forms.py: class Meta: model = Address fields = ['route_name','name', 'city','area','location','make_initial_location'] def form_valid(self, form): form.instance.username = self.request.user return super().form_valid(form) this is the Address creation view in views.py, this is where i wrote the code for redirecting to address-detail, it shows me that the error is in return redirect('address-detail') : @login_required def AddressCreateVeiw(request): form = AddressCreationForm() if request.method == 'POST': form = AddressCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your address has been successfully created!') return redirect('address-detail') return render(request, 'blog/address_form.html', {'form': … -
Editing comments from a post: NoReverseMatch while trying to edit comment of a post
I am quite new to Django and I am trying to edit the comments for a specific post. However, I am getting an error while running the code. My guess is that it has to do with the url path or the post_detail html file(I tried multiple ways on fixing it, but could not get it to work). NoReverseMatch at /post/3c6f50b5-195a-4868-8704-b50c7b127813/ Reverse for 'edit_comment' with arguments '(33,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/comment/edit/$'] Models.py: class Post(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) ... class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', ) comment = RichTextField() ... urls.py: urlpatterns = [ ... path('post/<uuid:pk>/comment/', AddCommentView.as_view(), name='add_comment'), path('post/<uuid:pk>/comment/edit/', EditCommentView.as_view(), name='edit_comment'), path('post/<uuid:pk>/comment/delete/',DeleteCommentView.as_view(), name='delete_comment'), ... ] views.py: class EditCommentView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment form_class = EditCommentForm template_name='blog/edit_comment.html' login_url = 'account_login' def test_func(self): obj = self.get_object() return obj.author ==self.request.user class DeleteCommentView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/delete_comment.html' fields= '__all__' success_url = reverse_lazy('blog_home') login_url = 'account_login' def test_func(self): obj = self.get_object() return obj.author == self.request.user def form_valid(self,form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) forms.py: class EditCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) widgets = { 'comment': forms.Textarea(attrs={'class': 'form-control'}), } post_detail.html: {% if not post.comments.all … -
Remove file from S3 Bucket django-storages
I have a Django app that I am hosting on Heroku and the media files are served from AWS. I have a model that looks like this: class MyModel(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to="images/") def __str__(self): return self.name And I use a function inside views.py to delete the instance of the image from the model AND the image from the server. def delete_single_image(image): if image.image: image.image.delete() image.delete() This was working when I run it locally, but it doesn't delete the image from the S3 bucket when I host it on heroku. What can I do to remove it from there also? -
Django: dynamically append query results to context inside of view
I need to access models' data associated with one particular model (let's say model1). What is frustrating is that my database structure does not contain foreign keys or things to easily relate to model1. The underlying issue is that I can't figure away to manually replace the append method to add value:key pairs into the context dictionary. Here is what I have so far: @method_decorator(login_required, name='dispatch') class PostDetailalerte_trend2(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): queryset = trend2.objects.all().values('reference') queryset2 = {} queryset3 = {} print(queryset) for object in queryset: queryset2.append(old_year2.objects.filter(Id = object['reference']).values('Qm3', 'Qm2', 'Qm1')) queryset3.append(demand_planning2.objects.filter(Id= object['reference']).values('ltplus1')) return render(request, 'detailstocktrend2.html', {'queryset': queryset, 'queryset2': queryset2, 'queryset3':queryset3}) ##how to replace the not working APPEND method?/ I have seen several example recommanding to manuall create the keys, however this is not an option because I cannot know in advance how big the dict will be. Any help or any alternative way to do that is welcome -
Run a function in Django after loading views
I want to run a python function when the user clicks a button, but I don't wanna run it before loading the template. For example in views.py def index(request): return render(request, "some_html.html") in some_html.html <form method="post"> <input type="button" id="run-button" value="RUN" name="run-button"> </form> And then when the users clicks the button "RUN", I wanna run a function, let's say doSomethingCool, how would it be? I'm wondering if it'd be like this on views.py def index(request): return render(request, "some_html.html") def doSomethingCool(request): if request.method == "POST" and "run-button" in request.POST: print("Some cool stuff") doSometingCool(request) Any ideas? -
TemplateDoesNotExit post_list.html
I have stumbled upon a problem where it tries to look for a template I did not even indented it to. My html files name is home.html but it looks for post_list.html. Here are the few of the files: urls.py: from django.urls import path from . import views from .views import HomeView urlpatterns = [ #path('', views.home, name = "home") path('', HomeView.as_view(), name = "home"), ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post # Create your views here. #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_score = 'home.html' ] Here is the directory. The commented lines are the ones that works, but when I try the class HomeView it gives me error. Exception Type: TemplateDoesNotExist Exception Value: myblog/post_list.html -
Deny an access to edit/delete a post, if the currently logged in user is not the author of the post. Django REST + simpleJWT
How can i change my postDetails view, in order to allow only the author of the post (currently logged in user) the option of PUT and DELETE a post made by him? views.py @api_view(['GET', 'PUT', 'DELETE']) def postDetails(request, pk): try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: return Response({'message': 'The post does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PostSerializer(post) return Response(serializer.data) elif request.method == 'PUT': postData = JSONParser().parse(request) serializer = PostSerializer(post, data=postData) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': post.delete() return Response({'message': 'post was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' models.py class Post(models.Model): post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') post_title = models.CharField(max_length=200) post_body = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.post_title -
What is the best way to exclude object instances from a QuerySet in Django (filter() not an option in this case)?
Right now the best solution I can think of is to individually use queryset.exclude(pk=instance.pk) on specific instances. The scenario is that I need to filter a model queryset for a few fields but then also check to see if a date field matches a given value. Normally I would just filter for date=mydate but in my case I need to calculate the date first using a stored timezone in a different model (which is why it seems like I can't simply use a filter) Right now my code looks something like this: user_tracks = HabitTrack.objects.filter(user=user) filtered_user_tracks = user_tracks for t in user_tracks: if not HabitEvent.objects.filter(user=user, track=t, date_expected=t.get_timezone_corrected_datetime_now().date(), post__isnull=True).exists(): print("Excluding ", t.track_name, " with track specific time of ", t.get_timezone_corrected_datetime_now(), "from the list of options") filtered_user_tracks = filtered_user_tracks.exclude(pk=t.pk) else: print("Including ", t.track_name, " with track specific time of ", t.get_timezone_corrected_datetime_now(), "in the list of options") For context, this is a snippet from my ModelForm so that I can limit form choices to only options available to the user "today" where "today" is calculated based on the user's timezone. (This is also my first time asking a question on SO, so I will do my best to clean up my question if … -
Why does Django default password hashing algorithm use 216000 iterations?
Why does Django password hashing algorithm pbkdf2_sha256 use exactly 216000 iterations? Why no 200000 or 256000? Those numbers seem to be much more natural. -
How to show multiple fields within a row? (Django Admin)
I've been struggling with a situation in Django/Mysql. There is this column in a table that has a primary key and foreign key at the same time. This column has a one to many relation with an intermediary table. It's a list of states linked to plant species. Some species can be found in more than one state. Species (table 1) Columns: Species_id | specie_name Species_to_states (table 2) Columns: Species_id | State_id States (table 3) Columns: States_id, State_name Models.py (code below) class Listaflor(models.Model): especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True) class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) nome_abbr = models.CharField(max_length=2, blank=True, null=True) criadoem = models.DateTimeField(db_column='criadoEm') # Field name made lowercase. class Meta: managed = False db_table = 'estados' verbose_name = "Estados" verbose_name_plural = "Estado" def str(self): return self.estado_nome+ " (" + self.nome_abbr+")" The point is that only one object is being displayin django admin (check the image below). So i would like to show multiple fields within a row. Can someone help me with that? Thank you so much -
Django Counting related object with a certain condition
I have this model classes in my django app: class Ad(models.Model): ... class Click: time = models.DateTimeField(auto_now_add=True) ip = models.GenericIPAddressField() ad = models.ForeignKey( to=Ad, related_name='views', on_delete=CASCADE ) class View: time = models.DateTimeField(auto_now_add=True) ip = models.GenericIPAddressField() ad = models.ForeignKey( to=Ad, related_name='views', on_delete=CASCADE ) Assume I have a queryset of Ad objects. I want to annotate the count of clicks for each add that happened in hour 12 to 13 (We could use range look-up). First I did it like this: query.filter(clicks__time__hour__range=[12, 13]).annotate(views_count=Count('views',distinct=True), clicks_count=Count('clicks', distinct=True)) but those ads which don't have any clicks in that range will be omitted from the query this way but I need them to be present in the final query. Is there any proper way to do so maybe with Django Conditional Expressions? -
django how to use exists()
The django docs have the following: entry = Entry.objects.get(pk=123) if some_queryset.filter(pk=entry.pk).exists(): print("Entry contained in queryset") could someone explain how this works? does the first line have to be executed? can we just do: if some_queryset.filter(pk=123).exists(): print("Entry contained in queryset") I'm confused by what some_queryset is. -
django catching all URLS under a specific name
I'd like to have one entry under urls.py that'll catch all sub-folders in a URL starting with a particular folder, example in this instance: example: /business /business/one /business/one/two /business/one/two/three /business/one/two/three/four I want all those URLS to go a single view, where I can later determine how many levels of folders there are after /business/ and their names. -
Using django, how to send messages from the view.py to the page prior to the postback
In django, when the user submits, how do you send messages to display on the page prior to the postback return? I believe those messages will need to be sent to a separate page using iframe, since the initial page is waiting for a page return. view.py def post_info(): from django.contrib import messages messages.success(request, "Starting processes...") ... ... messages.success(request, "In progress...") ... ... messages.success(request, "Completed.") return HttpResponseRedirect(self.request.path_info) template1.html {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li> {% endfor %} </ul> {% endif %}