#StackBounty: #django #django-rest-framework #drf-yasg drf-yasg cover all responses to following implemented standard api response

Bounty: 50

I did implement the standard API response such as this article in my app. And I also implement drf-yasg for my API documentation. As we know the schema are using directly serializer to present the response. How I can cover all these below response examples by using drf-yasg schema?

1. Success Single

{
   "status": 200,                       # int : http status, can be 201, 200, etc.
   "success": true,                     # bool: boolean to identify the response is success or failed.
   "message": "The success message",    # str : string success message or null
   "result": {}                         # dict: a dict response data
}

2. Success List

{
   "status": 200,      # int : http status
   "success": true,    # bool: boolean to identify the response is success or failed.
   "message": null,    # str : string message or null.
   "results": [],      # arr : a list/array

   "count": 2,                                                   # int: all total result items
   "page_size": 5,                                               # int: maximum items per-page
   "current_page": 1,                                            # int: your current page
   "next": "http://127.0.0.1:8000/api/page/?page=2&search=a",    # str: string link or null.
   "previous": null                                              # str: string link or null.
}

3. Error or Failed

{
   "status": 400,                      # int : http status, can be 403,404,500,etc..
   "success": false,                   # bool: boolean to identify the response is success or failed.
   "message": "The failed message",    # str : string failed message or null
   "result": {}                        # dict: a dict response data
}

Currently I just did implement the general schema from drf_yasg, and still don’t know how to do that.

from django.urls import path
from django.conf import settings

from rest_framework import permissions, authentication
from rest_framework.settings import api_settings
from rest_framework.routers import SimpleRouter

from drf_yasg import openapi
from drf_yasg.views import get_schema_view

from myproject.users.api.views import UserViewSet, AuthLoginView
from myproject.storage.api.views import FileViewSet

router = SimpleRouter()
router.register('users', UserViewSet, basename='api_users')
router.register('files', FileViewSet, basename='api_files')

app_name = 'api'
urlpatterns = [
    path('auth/login/', AuthLoginView.as_view(), name='api_auth_login'),
] + router.urls

if settings.DEBUG:
    swagger_info = openapi.Info(
        title='My Project API',
        default_version=api_settings.DEFAULT_VERSION,
        description='This is documentation of My Project open API',
        terms_of_service='https://foobar.com/tos/',
        contact=openapi.Contact(email='help@foobar.com'),
        license=openapi.License(name='Proprietary and confidential'),
    )
    schema_view = get_schema_view(
        info=swagger_info,
        public=True,
        permission_classes=(permissions.IsAdminUser,),
        authentication_classes=(authentication.SessionAuthentication,)
    )
    urlpatterns += [
        path('', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'),
    ]


Get this bounty!!!

#StackBounty: #python #django How to run a function with parameters periodicaly?

Bounty: 50

I have a form(DashboardData model) on my system that each user fills out. In this form, we are asking for a username, password, and a range to update for another system. Options in this range are once a week, once a month, and once a year.

Depending on which interval the user selects, I will run a function at those intervals. In this function, I will get the username and password from the form filled by the user as parameters. For example in form username, password, once a week is selected then I have to run myFunction(username, password) once a week.

I try to use apscheduler for this. But in apps.py I can not reach request.user, so, I cannot get the data. I have to take request.user for running my function.

forms.py

class SetupForm(forms.ModelForm):
# Time
PERIOD = (
    ('168', 'Once a week'),
    ('720', 'Once a month'),
    ('8766 ', 'Once a year'),
)
    n_username = forms.CharField()
    n_password = forms.CharField(widget=forms.PasswordInput)
    period = forms.CharField(max_length=200, widget=forms.Select(choices=PERIOD)))

    class Meta:
        model = DashboardData
        fields = ('n_username', 'n_password','period')

models.py

class DashboardData(models.Model):
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user
    n_username = models.CharField(max_length=250)
    n_password = models.CharField(max_length=250)
    period = models.CharField(max_length=250)

functions.py

class myFunction():
    def __init__(self, n_user, n_password):
        self.time = datetime.now().strftime("%Y-%m-%d")
        self.location = a_url
        self.static_fields = {}
        self.index_name = "pre-" + self.zaman
        self.download_all(n_user, n_password)
        self.send_it()

apps.py

class DashboardConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'dashboard'
    def ready(self):
        start()


Get this bounty!!!

#StackBounty: #python #django #websocket #django-channels #daphne django-channels: page not found, connection failed

Bounty: 150

I am trying to set up django-channels.

I did everything according to the instructions, but when I try to connect, I get a 404 error - page not found.

I make a request from the localhost to the dev server.

config/base.py

INSTALLED_APPS = [
    "grappelli",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "adminsortable2",
    "channels",
    "corsheaders",
    "django_filters",
    "django_multilanguage_content",
    "django_otp",
    "django_otp.plugins.otp_totp",
    "drf_yasg",
    "notifications",
    "rest_framework",
    "rest_registration",
    "storages",

    "vv.announcements.apps.AnnouncementsConfig",
    "vv.core.apps.CoreConfig",
    "vv.discussions.apps.DiscussionsConfig",
    "vv.manage_categories.apps.ManageCategoriesConfig",
    "vv.messaging.apps.MessagingConfig",
    "vv.users.apps.UsersConfig",
    "vv.vital_notif.apps.VitalNotifConfig",
]


ASGI_APPLICATION = "config.asgi.application"

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [(env("REDIS_HOST"), 6379)],
        },
    },
}

config/asgi.py

import os
import sys

import django
from django.core.asgi import get_asgi_application


app_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir))
sys.path.append(os.path.join(app_path, "vv"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.base")
django.setup()
django_asgi_app = get_asgi_application()


from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter

from config.routing import websocket_urlpatterns


application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": URLRouter(websocket_urlpatterns),
})

routing.py

from django.urls import path

from vv.messaging.consumers import MarkAsReadConsumer

websocket_urlpatterns = (
    path("ws/mark/", MarkAsReadConsumer.as_asgi()),
)

runner.sh

#!/bin/sh
daphne -b 0.0.0.0 -p 8000 config.asgi:application  -v2
python manage.py runworker -v2

client.js

let socket = new WebSocket("ws://<ip>/ws/mark/");

docker-compose.yml

version: "3.7"

x-env_file: &env_file
  env_file:
    - ./.env

services:
  nginx:
    build: ./nginx
    container_name: vv-fix-nginx
    ports:
     - "5555:80"
    depends_on:
     - backend
    networks:
     - vv-fix-network

  redis-vv:
    image: redis:alpine
    container_name: vv-fix-redis
    volumes:
      - vv_fix_redis_volume:/var/lib/redis/data/
    ports:
      - "6300:6379"
    networks:
      - vv-fix-network

  backend:
    <<: *env_file
    container_name: vv-fix-backend
    build:
      context: .
    depends_on:
      - db
      - redis-vv
    command: /bin/sh -c "/boot.sh"
    volumes:
      - .:/app
    networks:
      - vv-fix-network

volumes:
  vv_fix_db_volume:
  vv_fix_redis_volume:

networks:
  vv-fix-network

In .env file I have REDIS_HOST=redis-vv

nginx.conf

events {}

http {
    client_max_body_size 25M;

    server {
        listen 80;
        listen [::]:80;

        access_log /var/log/nginx/reverse-access.log;
        error_log /var/log/nginx/reverse-error.log;
    
        location /ws/ {
              proxy_pass http://vv-fix-backend:8000;
          proxy_http_version  1.1;
          proxy_set_header    Upgrade $http_upgrade;
          proxy_set_header    Connection $connection_upgrade;
          proxy_set_header    Host $http_host;
          proxy_set_header    X-Real-IP $remote_addr;
         }  

        location / {
            proxy_pass http://vv-fix-backend:8000;
        }

    }
}

logs.txt

vv-fix-backend | 2021-09-14 16:17:13,228 DEBUG    Read environment variables from: .env
vv-fix-backend | 2021-09-14 16:17:13,229 DEBUG    get 'SECRET_KEY' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,229 DEBUG    get 'DEBUG' casted as '<class 'bool'>' with default 'False'
vv-fix-backend | 2021-09-14 16:17:13,229 DEBUG    get 'ALLOWED_HOSTS' casted as '<class 'list'>' with default '[]'
vv-fix-backend | 2021-09-14 16:17:13,229 DEBUG    get 'REDIS_HOST' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,229 DEBUG    get 'POSTGRES_DB' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,230 DEBUG    get 'POSTGRES_USER' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,230 DEBUG    get 'POSTGRES_PASSWORD' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,230 DEBUG    get 'POSTGRES_HOST' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,230 DEBUG    get 'POSTGRES_PORT' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,230 DEBUG    get 'CACHE_LOCATION' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,231 DEBUG    get 'BACKEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,231 DEBUG    get 'AWS_ENABLED' casted as 'None' with default 'False'
vv-fix-backend | 2021-09-14 16:17:13,231 DEBUG    get 'CELERY_BROKER_URL' casted as 'None' with default 'redis://redis:6379/1'
vv-fix-backend | 2021-09-14 16:17:13,231 DEBUG    get 'CELERY_TASK_DEFAULT_QUEUE' casted as 'None' with default 'default_queue'
vv-fix-backend | 2021-09-14 16:17:13,231 DEBUG    get 'AWS_REGION' casted as 'None' with default 'eu-central-1'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'EMAIL_HOST' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'EMAIL_USE_TLS' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'EMAIL_PORT' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'EMAIL_HOST_USER' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'EMAIL_HOST_PASSWORD' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'EMAIL_FROM_USER' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,232 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,233 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,233 DEBUG    get 'BACKEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,233 DEBUG    get 'DISCUSSION_ATTACHMENT_MAX_SIZE' casted as 'None' with default '5000000'
vv-fix-backend | 2021-09-14 16:17:13,233 DEBUG    get 'LOGGED_BEFORE_SECONDS' casted as 'None' with default '15'
vv-fix-backend | 2021-09-14 16:17:13,234 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,234 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,234 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,234 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,234 DEBUG    get 'FRONTEND_URL' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,234 DEBUG    get 'TWILIO_ACCOUNT_SID' casted as 'None' with default '<NoValue>'
vv-fix-backend | 2021-09-14 16:17:13,235 DEBUG    get 'TWILIO_AUTH_TOKEN' casted as 'None' with default '<NoValue>'

In the Nginx access.log I see

[17/Sep/2021:11:54:54 +0000] "GET /ws/mark-as-read/ HTTP/1.1" 404 1100 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"

I tried this with uvicorn. Not effect…

I’m use

Python 3.8

Django 2.2

channels-redis 3.3.0

channels 3.0.4

redis 3.5.3


Get this bounty!!!

#StackBounty: #django #django-filter #django-pagination Paginate a filter

Bounty: 50

I have a filter with a dependent drop down for cars makes and models. Since I don’t want to display all of them on one page I added a paginator. The issue is the filter works correctly but it does not carry over in the pages

when the filter is active the url looks like

/cars/?manufacture=2&model=2
If i go to the next page all I get is /cars/?page=2

I want something like /cars/?manufacture=2&model=2?page=2

If I print {{ posts|length }} it does return the proper number of items that are being filtered so there is not issue there

I believe the issue is with the next and previous buttons in the template as they don’t pass any parameters in them other then next page. How do i carry the filter into the paginator.

view

def allCarsView(request):

    model = Post
    
    myFilter = carFilter(request.GET, queryset=Post.objects.all())
    posts = myFilter.qs
    
    page = request.GET.get('page', 1)
    paginator = Paginator(posts.order_by('date_posted'), 2)
    page_obj = paginator.get_page(page)
    page_range = paginator.get_elided_page_range(number=page)
    
    context = {
        'posts':posts, 'myFilter':myFilter, 'page_range': page_range, 
        'page': page, 'paginator': paginator, 'page_obj': page_obj
    }
    return render(request, 'blog/cars.html', context)    

Paginator html

<nav aria-label="Page navigation example " class="paginator">
<nav aria-label="Page navigation example " class="paginator">
    <ul class="pagination justify-content-center">
        <li class="page-item">
            {% if page_obj.has_previous %}
            <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
            {% else %}
        </li>

        <li class="page-item disabled">
            <a class="page-link" href="#" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
        {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %}
        <li class="page-item active" aria-current="page">
            <a class="page-link" href="#">{{ i }}</a>
        </li>
        {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %}
        <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
        {% endif %} {% endfor %}

        <li class="page-item">
            {% if page_obj.has_next %}
            <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Previous">
                <span aria-hidden="true">&raquo;</span>
            </a>
            {% else %}
        </li>

        <li class="page-item disabled">
            <a class="page-link" href="#" aria-label="Previous">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
        {% endif %}
    </ul>
</nav>

Update:
From doing more research it does seem that my issue is with the urls in the paginator as they do not carry any parameters. There does not seem to be a best way to do this and the solutions I have tried have yielded nothing.

Update:
Attempting to use this post as the solution

view (added under previous code)
from django import template
register = template.Library()

@register.simple_tag
def url_replace(request, field, value):

    dict_ = request.GET.copy()

    dict_[field] = value

    return dict_.urlencode()

template:

<a class="page-link" href="?{% url_replace request 'page' page_obj.next_page_number %}" aria-label="Previous">

I then get the error

Invalid block tag on line 88: 'url_replace', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?

so at the top if I add

{% load url_replace %}

throws the error

'url_replace' is not a registered tag library


Get this bounty!!!

#StackBounty: #django #django-models Set attribute based on another attribute

Bounty: 50

How to set hostel choices based on gender?

Global variables

BOYS_HOSTEL_CHOICES = (…)

GIRLS_HOSTEL_CHOICES = (…)

class Student(models.Model):

    MALE = 'M'
    FEMALE = 'F'
    
    #...
    GENDER_CHOICES = (
        (MALE, 'Male'),
        (FEMALE, 'Female')
    )

    gender = models.CharField(
        max_length = 10,
        choices = GENDER_CHOICES,
        verbose_name="gender",
    )


    hostel = models.CharField(
        max_length=40,
        choices = BOYS_HOSTEL_CHOICES if gender == 'M' # <---
                            else GIRLS_HOSTEL_CHOICES,
        default = 'some hostel'
    )


Get this bounty!!!

#StackBounty: #django Filter + Paginator not working as expected

Bounty: 50

I have a filter with a dependent dropdown as well as a paginator. The paginator and filter are working as expected except if the category has a page 2 it no longer filters the results and just displays everything in the db(paginated). How do I go about carrying the filter request into the paginator.

view

model = Post

myFilter = carFilter(request.GET, queryset=Post.objects.all())
posts = myFilter.qs

page = request.GET.get('page', 1)
paginator = Paginator(posts, 2)
page_obj = paginator.get_page(page)
page_range = paginator.get_elided_page_range(number=page)

context = {
    'posts':posts, 'myFilter':myFilter, 'page_range': page_range, 'page': page, 'paginator': paginator, 'page_obj': page_obj
}

template

{% for post in page_obj %}
<article>

    <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.year }}</a>
    <a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.manufacture }}</a>

</article>
{% endfor %}


<nav aria-label="Page navigation example " class="paginator">
    <ul class="pagination justify-content-center">
        <li class="page-item">
            {% if page_obj.has_previous %}
            <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
            {% else %}
        </li>

        <li class="page-item disabled">
            <a class="page-link" href="#" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
        {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %}
        <li class="page-item active" aria-current="page">
            <a class="page-link" href="#">{{ i }}</a>
        </li>
        {% elif i > page_obj.number|add:'-3' and i < page_obj.number|add:'3' %}
        <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
        {% endif %} {% endfor %}

        <li class="page-item">
            {% if page_obj.has_next %}
            <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Previous">
                <span aria-hidden="true">&raquo;</span>
            </a>
            {% else %}
        </li>

        <li class="page-item disabled">
            <a class="page-link" href="#" aria-label="Previous">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
        {% endif %}
    </ul>
</nav>

After doing some more research I believe the issue is with the next and previous button as they don’t pass any parameters in them other then next page


Get this bounty!!!

#StackBounty: #django #django-models Django and a Database with write-Instance + Multiple Read Replicas — running Celery jobs

Bounty: 500

I have a django app running in production. Its database has main write instance and a few read replicas. I use DATABASE_ROUTERS to route between the write instance and the read replicas based on whether I need to read or write.

I encountered a situation where I have to do some async processing on an object due to a user request. The order of actions is:

  1. User submits a request via HTTPS/REST.
  2. The view creates an Object and saves it to the DB.
  3. Trigger a celery job to process the object outside of the request-response cycle and passing the object ID to it.
  4. Sending an OK response to the request.

Now, the celery job may kick in in 10 ms or 10 minutes depending on the queue. When it finally tuns, the celery job first tries to load the object based on the ID provided. Initially I had issues doing a my_obj = MyModel.objects.get(pk=given_id) because the read replica would be used at this point, if the queue is empty and the celery job runs immediately after being triggered, the object may have not propagated to the read-replicas yet.

I resolved that issue by replacing my_obj = MyModel.objects.get(pk=given_id) with my_obj = MyModel.objects.using('default').get(pk=given_id) — this ensures the object is read from my write-db-instance and is always available.

however, now I have another issue I did not anticipate.

calling my_obj.certain_many_to_many_objects.all() triggers another call to the database as the ORM is lazy. That call IS being done on the read-replica. I was hoping it would stick to the database I defined with using but that’s not the case. Is there a way to force all sub-element objects to use the same write-db-instance?


Get this bounty!!!

#StackBounty: #django #django-models #django-queryset Filter GenericForeignKey by list of different model objects

Bounty: 50

I am trying to build activity logs by a User or any other model object, to which a user can follow or subscribe to.

These are the models related with logging the activities:

class Activity(models.Model):
    """
    An activity log : Actor acts on target
    Actor can be a User or a model Object
    """
    actor_content_type = models.ForeignKey(
        ContentType, on_delete=models.CASCADE, related_name="actor_type")
    actor_object_id = models.PositiveIntegerField()
    actor = GenericForeignKey('actor_content_type', 'actor_object_id')
    description = models.TextField()
    target_content_type = models.ForeignKey(
        ContentType, on_delete=models.CASCADE, related_name="target_type")
    target_object_id = models.PositiveIntegerField()
    target = GenericForeignKey('target_content_type', 'target_object_id')


class Follow(models.Model):
    """
    A user can follow any User or model objects.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    follow_object = GenericForeignKey('content_type', 'object_id')

Suppose:

  • Thor follows user Loki // User follows User
  • Thor follows user Stark // User follows User
  • Thor follows project Avenger // User follows Project

And suppose these are activities:

  • Nick Fury Created a project "Shield"
  • Nick Fury Created a project "Avengers"
  • Stark created a project "Mark II"
  • Avengers added Vision
  • Dr Strange created a project Dormammu

I can get the user Thor:

thor = User.objects.get(email="thor@gmail.com")

And get the list of users/objects followed by Thor:

thor.follow_set.all()
<QuerySet [<Follow: thor@gmail.com follows loki@gmail.com>, <Follow: thor@gmail.com follows Stark@gmail.com>, <Follow: thor@gmail.com follows Avengers>]>

Now to get the list of activities followed by the user Thor, I tried this:

q = (Q(actor__in=thor.follow_set.all())| Q(target__in=thor.follow_set.all())

Activity.objects.filter(q)

But its throwing an error:

FieldError: Field ‘actor’ does not generate an automatic reverse
relation and therefore cannot be used for reverse querying. If it is a
GenericForeignKey, consider adding a GenericRelation.

I can get all the activities for a single object followed by user Thor:

followed_last = thor.follow_set.last().follow_object

q = (Q(actor_content_type=ContentType.objects.get_for_model(followed_last), actor_object_id=followed_last.id)| Q(target_content_type=ContentType.objects.get_for_model(followed_last), target_object_id=followed_last.id))

Activity.objects.filter(q)
<QuerySet [<Activity: Avengers Added vision@gmail.com>, <Activity: nickfury@gmail.om Created Avengers>]>

But how can I get all the activities Thor is following from the above activities:

  • Nick Fury Created a project "Avengers"
  • Stark created a project "Mark II"
  • Avengers added Vision

Update

Added User model as requested:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    fullname = models.CharField(max_length=255, validators=[validate_fullname])
    is_active = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["fullname"]

    def __str__(self):
        return self.email


Get this bounty!!!

#StackBounty: #python #django #xlsxwriter Why I'm unable to download my document with django? and how to do it?

Bounty: 50

I’m new to django and still learning, and I got here, in my own infinite loop, if I do how I sholud it be but i have an errors and it won’t work, but if I do it like this there are no errors but it won’t work. I want to user to be able to create excel template as he wish, this is simplified version that I want to work, just input few information and on base of that to be able to create excel template.

This is views.py

from django.http import HttpResponse
from django.shortcuts import render
import xlsxwriter
from xlsxwriter import workbook
from django.forms import Form, CharField, ChoiceField, IntegerField
from django.core.validators import MaxValueValidator, MinValueValidator

def home(request):
    return render(request, 'my_app/home.html')

class TemplateForm(Form):
    doc_name = CharField(label='Document name')
    sheetnames = CharField(label='Sheetnames')
    choices = []
    for year in range (1900, 2050):
        choices.append( (year, year) )
    year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices)
    year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices)    
    row_names = CharField(label='Column names')

def create_template(request):
    if request.method == 'GET':
        form = TemplateForm()
        return render(request, 'my_app/create_template.html', {'form':form})
    else:
        form = TemplateForm(request.POST)

def create_form(doc_name, sheetnames, years, row_names):
    workbook = xlsxwriter.Workbook(doc_name + '_template.xlsx')
    worksheet_introduction = workbook.add_worksheet( "introduction" )
    for i in sheetnames:
        worksheet_data = workbook.add_worksheet(i)
        worksheet_data.write_row(0, 1, years)
        worksheet_data.write_column(1, 0, row_names)
    workbook.close()
    return workbook

This is my_app/templates/my_app/create_template.html

{% extends "my_app/base.html" %}
{% block content %}

<form action="create_template" method="GET">
  {% csrf_token %}
  <h1>Create your template</h1>
  <div class="item">
    <table>
      {{ form.as_table }}
    </table>
  </div>
  <div class="btn-block">
    <input type="button" type="submit" value="Create and Download!"/>
  </div>
</form>
{% endblock content %}

This is my_app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='my-home'),
    path('create-template/', views.create_template, name='my-create-template'),
]


Get this bounty!!!