#StackBounty: #django #azure #azure-web-app-service #django-staticfiles Django app on Azure not getting static files

Bounty: 50

Got my Django project on a Azure webapp, but when I call on SSH terminal:

Python manage.py collectstatic

It says 252 files copied but my static files are not visible on my templates and static folder in wwwroot its empty…Here’s my wwwroot structure:

|---static //always empty
├── myapp
│   ├── migrations
│   ├── __pycache__
│   ├── static
|   |   |---Images
|   |   |   |--myimage.png
|   |   |   |--myimage2.png
│   └── templates

And this is my settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
   ('myapp', os.path.join(BASE_DIR, 'myapp', 'static')),

Any idea why or what am I doing wrong ?, does Azure collect different ?

EDIT> When I go to my website my images don´t show…Im calling them like this on template:

{% load static %}
<img src="{% static 'Images/myimage.png' %}" /><br>

EDIT 2 /////

In wwwroot creates indeed a folder with all my statics, but when I load my template they don´t show, in wen console I get this error for myimage.png and myimage2.png :

Failed to load resource: the server responded with a status of 404 (Not Found)

Get this bounty!!!

#StackBounty: #python #python-3.x #django #django-views #django-templates Django Python – Itertools is not aligning products with sum o…

Bounty: 50

I generate a list of Products based on two criterias Entity and Period.
The list retrieved contains all Products and the sum of all auctions sales for each. The example below shows a list of 4 products for Company XZY in November. Out of all the products listed only one product (sku 30) had two auction sales $180 and $220. The problem is the rest of products had no sales so the null value is not aligning properly with the product. I will need to still list those products and show $0 in sales.


class Entity(models.Model):
    entity = models.CharField(max_length=40)

class Period(models.Model):
    period = models.CharField(max_length=7)

class Product(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE, default=None, blank=True, null=True)
    period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True)
    sku = models.CharField(max_length=40)
    projectedsales = models.DecimalField(max_digits=11, decimal_places=2)

class Post(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None, blank=True, null=True)
    auctionsale = models.DecimalField(max_digits=11, decimal_places=2)


def get(self, request):
        form = ProductsViewForm()
        return render(request, "products_list.html", {'form': form})

    def post(self, request):
        products = None
        posts = None
        entities = None
        periods = None
        mylist = None
        form = ProductsViewForm(request.POST)
        if request.method == 'POST':
            if form.is_valid():
                entityquery = form.cleaned_data['entity']
                periodquery = form.cleaned_data['period']
                entities = Entity.objects.get(entity=entityquery)
                periods = Period.objects.get(period=periodquery)
                products = Product.objects.filter(entity=entityquery, period=periodquery).values('id', 'period', 'entity', 'sku', 'projectedsales')
                posts = Post.objects.filter(product__sku__in=products.values('sku'), product__entity=entityquery, product__period=periodquery).annotate(total=Sum('auctionsale'))
                mylist = list(itertools.zip_longest(products, posts, fillvalue='0'))
            args = {'form': form, 'periods': periods, 'entities': entities, 'mylist': mylist}
        return render(request, "products_list.html.html", args)


<div class="row">
    <div class="col-12">
        <form method="POST">
            {% csrf_token %}
            <div class="form-row">
                <div class="form-group col-md-4">
                    {{ form.entity|add_class:"custom-select" }}
                <div class="form-group col-md-4">
                    <input type="text" name="period" id="id_period" class="form-control" placeholder="mm/yyyyy" maxlength="7" minlength="7" required> 
                <div class="form-group col-md-4">
                    <input type="submit" value="Run Balance Sheet" class="btn btn-primary btn-block">

<div class="row">
    <div class="col-12">
        {% if entities %}
            <center><h4>Auction Sales</h4></center>
            <center><h5>Entity : {{entities.entity}}</h5></center>  
        {% endif %}

        {% if periods %}
            <center><h5>Period : {{periods.period}}</h5> </center>
        {% endif %}
        {% if mylist %}
            <table class="table table-striped">
                        <th scope="col">Product</th>
                        <th scope="col">Projected Sales</th>
                        <th scope="col">Total Auction Sales</th>
                    {% for product, post in mylist %}
                    {% endfor %}
        {% endif %}


Entity: Company XZY 
Period: 11/2020

Expected results

Product -- Projected Auction Sales -- Total Auction Sales
sku 10  -- $100                    -- $0
sku 20  -- $200                    -- $0
sku 30  -- $600                    -- $400
sku 40  -- $500                    -- $0

The results i am getting

Product -- Projected Auction Sales -- Total Auction Sales
sku 10  -- $100                    -- $400
sku 20  -- $200                
sku 30  -- $600
sku 40  -- $500

Get this bounty!!!

#StackBounty: #python #django #django-rest-framework Django – add context to request to be used by the view

Bounty: 50

Using Django I want to implement some middleware that will calculate some context that is to be used by the view itself.

For example, I have a middleware that looks at the request, and adds the user’s permissions to the request, or some user configuration. The view looks at these permissions and decides how to handle the request using it.

This saves the need for multiple views (and multiple parts within the view) to query for this information.

I’m wondering what is the correct way to do that. One option is to just add request.user_permissions=... directly on the request. But is there some documented and expected way to do that?

Get this bounty!!!

#StackBounty: #django #postgresql #django-models #django-views #django-admin Approaches for adding multiple image on a post Django

Bounty: 50

I am working on a platform where I need to allow users to upload multiple images in one post.

  • I want to keep it as simple as possible, so that a person wouldn’t have to refresh the page to upload each image, or create and save a post before adding images.
  • If a user could delete or reorder images it would be nice

Can you give me advice on how to do it properly?

I am using django , postgres and here’s what I have done so far .

On my models.py –

class ImagePost(models.Model):
    user = models.ForeignKey("profiles.HNUsers", on_delete=models.DO_NOTHING)
    image = OptimizedImageField("Post Image", blank=True, null=True)
    timestamp = models.DateTimeField("Timestamp", blank=True, null=True, auto_now_add=True)
    text = models.TextField("Description text", blank=True)

    class Meta:
        verbose_name_plural = "Image Posts"

It can take one image just fine . what should I change to make it multi upload post

On my views.py this is what I have done so far –

def image_post(request):
    if request.method == 'POST':
        data = request.data
        serializer = ImagePostSerializer(data=data)
        if serializer.is_valid():
            print("image object saved")

                image_post_object = ImagePost.objects.filter(user__id=data['user']).order_by('-timestamp')[0]
                    post = Posts()

                    post.user = HNUsers.objects.get(id=data['user'])
                    post.image_url = image_post_object.image.url
                    post.type = 'I'
                    post.category = data['category']
                    post.created_on = image_post_object.timestamp
                    post.text = image_post_object.text
                    save_post = post.save()
                    post_id = post.pk

                        user = HNUsers.objects.get(pk=data['user'])
                        if user.user_type == 'HN':
                            payload = {
                                "user_name": user.full_name,
                                "image_url": user.profile_img_url,
                                "post_id": post_id,
                                "notification_type": "hn"
                            broadcast_notification('all', payload, 1)
                    except HNUsers.DoesNotExist:

                    print("post object created")

                except Posts.DoesNotExist:
                    print("Failed - post creation failed")

                except HNUsers.DoesNotExist:
                    print("Failed - user object not found")

            except ImagePost.DoesNotExist:
                print("Failed - image object not found")

    return Response(serializer.data, status=status.HTTP_200_OK)

Any advice is really appreciated.

Get this bounty!!!

#StackBounty: #django why in django wizard form values do not get saved in storage when I change steps?

Bounty: 100

It’s been days I am trying to split up a simple django form with some charfield and dropdowns to sub forms using django-formtools. In the first step form I left 2 dropdowns field and in the second step form, 2 char fields and one image file. Once I change dropdowns and go to the second form then after step back, the values and image of the second step disappear so I need to refill the second step of form before submitting(and values of dropdown in the first step saved in the storage after changing the step):

Here is the view.py code:

 FORMS = [('step_first', step_first_form),
     ('step_second', step_second_form)]

 TEMPLATES = {'step_first': 'myapp/step_first.html',
        'step_second': 'myapp/step_second.html'}

class NewWizard(NamedUrlSessionWizardView):
      file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos'))

      def done(self, form_list, **kwargs):

      def get_form(self, step=None, data=None, files=None):
           # maintaining the files in session when changing steps
           if self.steps.current == 'step_first':
              step_files = self.storage.get_step_files(self.steps.current)
             step_files = self.storage.current_step_files

          if step_files and files:
            for key, value in step_files.items():
                if files in key and files[key] is not None:
                    step_files[key] = files[key]
          elif files:
              step_files = files

         return super(NewWizard, self).get_form(step, data,step_files)

      def get_template_names(self):
           return [TEMPLATES[self.steps.current]]

and my second template:

<form id="dropdownForm" method="POST" action="" enctype="multipart/form-data">{% csrf_token %}
      {{ wizard.management_form }}
      {% if wizard.form.forms %}
            {{ wizard.form.management_form }}
            {% for form in wizard.form.forms %}
                 {{ form }}
            {% endfor %}
      {% else %}
          <div class="content-section mt-4 text-center">
                    <div class="row justify-content-center">

                        {% if wizard.steps.prev %}
                            <button class="btn btn-sm btn-outline-primary" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}" formnovalidate>{% trans "prev step" %}</button>
                        {% endif %}
                        <div class="form-group ml-2">
                            <input class="btn btn-sm btn-outline-primary"  type="submit" value="{% trans 'submit' %}"/>

      {% endif %}

in url.py:

create_wizard = login_required(NewWizard.as_view(FORMS, url_name='step_first', done_step_name='finished'))
urlpatterns = [
re_path('myapp/new/create-(?P<step>.+)', create_wizard, name='step_first'),

I guess the prev step does not submit the form!

Any assistance you can provide would be greatly appreciated.

Get this bounty!!!

#StackBounty: #django #ssl #redis #django-cache #aws-elasticache django-cacheops with aws redis Encryption

Bounty: 50

I have set up redis with Encyption in transit and rest. I have come across https://dev.to/yuki0417/easy-way-to-connect-to-amazon-elasticache-redis-with-password-from-django-app-40il and Connect to AWS ElastiCache with In-Transit Encryption. As I am using https://github.com/Suor/django-cacheops shows nothing regarding ssl how can I implement ssl to use the aws redis with encryption?

I have tried

        'host': "redis://{}".format(os.environ.get("REDIS_LOCATION")),
        'socket_timeout': 3,
        'ssl': True,

After reading the following https://github.com/jazzband/django-redis/issues/353 I have tried, but it still does not work

        'host': "rediss://{}/0".format(os.environ.get("REDIS_LOCATION")),
        'socket_timeout': 3,

        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "IGNORE_EXCEPTIONS": True,
                'CONNECTION_POOL_KWARGS': {
                    'skip_full_coverage_check': True,
                    "ssl_cert_reqs": None,
                    "ssl": True

Get this bounty!!!

#StackBounty: #django #django-timezone How to save and use timezones in Django

Bounty: 50

I have an important question. I understand Django saves data in "localtime", that is, UTC for my international app. So, if a user creates an "Event" with startdate (datetime object) 18:00, it will be 18:00 UTC. However, the user lives in Spain (UTC+1), so I store the timezone ("Europe/Madrid") in a different field. When I render it in the html, it will show the UTC time (but the user lives in UTC+1). Then, if I want to convert the time to a visiting user from Spain, I use the timezone tag to convert the datetime to Spain … and now it will show 19:00.

    {% if logged_user_profile.timezone %}
        {% timezone logged_user_profile.timezone  %}
        <p class="text-muted font-weight-bold">
            {{ event.date_start|date:"h:i A" }} ({{ logged_user_profile.timezone }}
        {% endtimezone %}
    {% else %}
        <p class="text-muted font-weight-bold">
         {{ event.date_start|date:"h:i A" }} ({{ owner_profile.timezone }})
    {% endif %}

The Spain case is only an example. I guess my question is broad, which is the best way to deal with timezones in django. I need to store the datetime of an event and show it to visiting users in their localtime, if the stored datetime is in UTC, it will not reflect the datetime the user that created the event had in mind when I add a timezone to it.

Get this bounty!!!

#StackBounty: #django #django-activity-stream django-activity-stream with aggregation

Bounty: 50

I’m using django-activity-stream to create a feed of goals. A simplified version of Goal object is as follows:

class Goal(models.Model):
    user = models.ForeignKey(User, related_name="goals", on_delete=models.CASCADE)
    liked_by = models.ManyToManyField(User, related_name="goals_cheered")
    title = models.CharField(_("title"), max_length=80)

There are 2 actions in place: the goal should appear in the feed once it’s created and once it has been completed. Then users can like the goal, and here’s where I’m stuck: adding the ‘likes’ count on the feed.

This was the (failed) attempt that made the most sense to me so far:

from django.db.models import Prefetch

goal_qs = Goal.objects.annotate(likes=Count("liked_by"))
prefetch = [Prefetch("action_object", queryset=goal_qs)]

# in a `group` feed:
qs = group.target_actions.all().prefetch_related("actor__profile").prefetch_related(*prefetch)

This gives me a ValueError: "Custom queryset can’t be used for this lookup."
Maybe it’s because django-activity-stream uses GFKs?

How can I get a count of likes? Can I limit the content_type somehow?


Managed to get is work by using the {{ goal.liked_by.all|length }} on the template. Not really comfortable with that solution, especially in a ListView. It felt super unoptimized.

Get this bounty!!!

#StackBounty: #django #django-formwizard Why django wizard form does not go back before filling the form?

Bounty: 50

I am trying to split one django form to two forms with two different templates. So after googling I found that the solution is using wizard form. Here is my code:

in view.py:

FORMS = [("0", postform_1stpage),
     ("1", postform_2ndpage)]

TEMPLATES = {"0": "myapp/postform_1stpage.html",
         "1": "myapp/postform_2ndpage.html"}

class ExampleWizard(SessionWizardView):
    instance = None
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'images_folder'))

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def get_form_instance( self, step ):
        if self.instance is None:
            self.instance = Post() #model instance
        return self.instance

    def done(self, form_list, **kwargs):

        self.instance.author = self.request.user
        return redirect('home')

    def get_form_step_files(self, form):
        return form.files

    def process_step_files(self, form):
        return self.get_form_step_files(form)

and in url.py:

`path('create/post/new', login_required(ExampleWizard.as_view(FORMS)), name='new-post')`

and for second template in the form step 2:

{% block content %}
   <form method="POST" action="" enctype="multipart/form-data">
      <fieldset class="form-group">
        {% csrf_token %}
        {{ wizard.form.management_form }}
        <div class="row justify-content-center">
              <div class="card-body">
                   {{ wizard.form.name }}

              <div class="card-body">
                   {{ wizard.form.lastname }}
             <div class="card-body">
                   {{ wizard.form.bio }}

             <div class="form-input mt-10">
                    <div class="image_preview">
                       <img id="file-preview" src="{{ wizard.form.image.url }}" alt="....">
                    <label for="file-ip">Add picture</label>
                    <input type="file" id="file-ip" name ="image" id="image.id" accept="images_forlder/*" onchange="showPreview(event);">

      <div class="py-auto px-auto">
          # the bug is related to this part
          <button type="submit" class="btn btn-sm btn-outline-info" style="font-weight: 700;" name="wizard_goto_step"value="{{ wizard.steps.first }}" >Back</button>
      <input type="submit" value="Submit" />

{{ wizard.form.media }}
{% endblock content %}

my question:

Once I press Back button in the second page, second page form validation asks me to fill the form first before letting back, I don’t know why!!

Get this bounty!!!

#StackBounty: #python-3.x #django #csv django-import-export how to skip import some rows based on current user login?

Bounty: 50

Actually started using django-import-export latest version.
Wanted to know where exactly we can override to skip certain rows of the csv from being imported based on current user or the domains from a list of domains he can import data from the csv. How exactly to customize which of the methods to override and how?

In my ModelResource, I have created the list of domains for the current user, and which method of the import-export do I check this and skip the rows from being imported?

class MailboxResource(resources.ModelResource):
mdomain_list = []

def import_data(self, *args, **kwargs):
    # make changes to csv
    super(MailboxResource, self).before_import(*args, **kwargs)
    muser_id = kwargs['user'].id
    muser = kwargs['user']

    # import for all domains
    if muser.is_superuser:
    # import for domains belonging to the hierarchy
    elif muser is not None:
        exist = muser.groups.filter(name='customers').exists() 

def skip_row(self, instance, original):
    mdomain = instance.email.partition('@')[2]
    #print(original, 'original',instance,'email', instance.email, self.mdomain_list)
    print(self.mdomain_list, 'llll', mdomain)
    if str(mdomain) in self.mdomain_list:
         print('will add', mdomain, instance.email)
         return False
         return True

Hence customer should be able to import data from the CSV only for domains that belong to him and skip all other rows from the CSV, which don’t exist in the list.

1,ABC pvt.ltd,abc@zinn.com,zinn.com,

If customer doesn’t own ggg.com domain, only 1st and 3rd row should get added to the table via import. How can this be achieved?

Using python 3.

Checked the document here: https://django-import-export.readthedocs.io/en/stable/api_resources.html#import_export.resources.Resource.skip_row but couldn’t make out much for my use-case.

Get this bounty!!!