#StackBounty: #django #apache #mod-wsgi #django-wsgi Django Apache2 VirtualEnv – no response from server

Bounty: 100

So I am trying to migrate my app to a new production server. I’m not getting a reply from the server Apache server when I access it. The server is on AWS and it’s a standard Apache config with just one site enabled:

<VirtualHost *:80>
    Alias /static/ /home/ubuntu/myapp/myapp/myapp/static
    Alias /media/ /home/ubuntu/myapp/myapp/myapp/media

    <Directory /home/ubuntu/myapp/myapp/myapp/static>
        Require all granted
    </Directory>

    <Directory /home/ubuntu/myapp/myapp/myapp/media>
                Require all granted
        </Directory>

    <Directory /home/ubuntu/myapp/myapp/myapp>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    WSGIDaemonProcess myapp python-home=/home/ubuntu/myapp/myapp/myapp python-path=/home/ubuntu/myapp:/home/ubuntu/myapp/lib/python3.6/site-packages
    WSGIProcessGroup myapp
    WSGIScriptAlias / /home/ubuntu/myapp/myapp/myapp/myapp/wsgi.py

    ErrorLog /var/log/apache2/myapp_error.log
    LogLevel warn
    CustomLog /var/log/apache2/myapp_access.log combined

</VirtualHost>

I have made sure that all files are owned by the ubuntu user and that www-data has group rights.

The wsgi file is the original, but I added a print statement to see the folder it’s checking for the application:

"""
WSGI config for match2 project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os, sys

print(sys.path)

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")

application = get_wsgi_application()

Eventually, the error log will produce:

Timeout when reading response headers from daemon process 'myapp': /home/ubuntu/myapp/myapp/myapp/myapp/wsgi.py

I’d appreciate any advice.


Get this bounty!!!

#StackBounty: #python #python-3.x #django #apache #mod-wsgi Django/mod_wsgi/Apache – mod_wsgi is not using the Python version it was co…

Bounty: 100

I’m attempting to deploy a Django application with Apache2 and mod_wsgi on a Ubuntu 16.04.6 server, but I’m struggling with getting mod_wsgi to use the correct python version.

I installed mod_wsgi from source, and configured it to compile against the system python3, specifically python3.7.8

My Virtual environment for the Django app is also running python3.7.8.

My VirtualHost config file looks like this:

<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName kumberas.com
        ServerAdmin webmaster@localhost.com

        WSGIScriptAlias / /home/dan/app/kumberas/kumberas/main/wsgi.py
        Alias /static/ /home/dan/app/kumberas/kumberas/static/

        <Directory /home/dan/app/kumberas/kumberas/static>
            Require all granted
        </Directory>

        <Directory /home/dan/app/kumberas/venv>
            Require all granted
        </Directory>

        <Directory /home/dan/app/kumberas/kumberas/main>
            <Files wsgi.py>
                Require all granted
            </Files>
        </Directory>

        <Location />
            AuthType Basic
            AuthName "Restricted Content"
            AuthUserFile /etc/apache2/.htpasswd
            Require user kr
            AuthBasicProvider file
        </Location>

        WSGIDaemonProcess kumberas 
            python-home=/home/dan/app/kumberas/venv 
            python-path=/home/dan/app/kumberas
        WSGIProcessGroup kumberas

    </VirtualHost>
</IfModule>

And when I try to access the site, I get a 500 Error and the following in my Apache error log.

[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] mod_wsgi (pid=21635): Failed to exec Python script file '/home/dan/app/kumberas/kumberas/main/wsgi.py'.
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] mod_wsgi (pid=21635): Exception occurred processing WSGI script '/home/dan/app/kumberas/kumberas/main/wsgi.py'.
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] Traceback (most recent call last):
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]   File "/home/dan/app/kumberas/kumberas/main/wsgi.py", line 12, in <module>
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]     from django.core.wsgi import get_wsgi_application
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]   File "/home/dan/app/kumberas/venv/lib/python3.7/site-packages/django/__init__.py", line 1, in <module>
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]     from django.utils.version import get_version
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]   File "/home/dan/app/kumberas/venv/lib/python3.7/site-packages/django/utils/version.py", line 1, in <module>
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]     import datetime
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]   File "/usr/lib/python3.7/datetime.py", line 8, in <module>
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603]     import math as _math
[wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] ModuleNotFoundError: No module named 'math'

I did a bit of digging and found this wsgi.py file in the mod_wsgi documentation for checking the python version that mod_wsgi is using, and get the following output when I visit the site:

sys.version = '3.7.2 (default, Jan 23 2020, 09:44:10) n[GCC 5.4.0 20160609]'
sys.prefix = '/home/dan/app/kumberas/venv'

I assume the mismatching python version 3.7.8 != 3.7.2 is the issue here, but as far as I’m aware there isn’t a python3.7.2 installation on the server, and I’ve reinstalled mod_wsgi several times making certain that I configure it to use 3.7.8.

I’ve also confirmed that while in the virtual environment I’m, a) able to run the Django application with manage.py runserver, and b) can run get_wsgi_application() manually in the Django shell.

Does anyone have any knowledge on whether this version mismatch is the issue, and how it could be resolved?


Get this bounty!!!

#StackBounty: #python #django #ajax AJAX call with Django is printing the response to a blank page

Bounty: 50

What’s happening now is when I click submit ("Go!"), Django clears the entire page and then prints the correct JSON response results_matrix on a blank page. alert("success") does not appear or alert("error").
I don’t know why the post function is doing this since I’m not returning a render of anything.

Before clicking "Go!":

enter image description here

After clicking "Go!" in Chrome:

enter image description here

After clicking "Go!" in Internet Explorer:
enter image description here

The ajax call is returning a raw json file to download (which Chrome displays automatically in the browser) instead of going into the ajax success function.

Expected Behavior: Page remains the same while a pop-up appears saying, "success".

In index.js:

$(document).ready(function() {
  ......
  
  var csrftoken = Cookies.get("csrftoken");

  function csrfSafeMethod(method) {
      // these HTTP methods do not require CSRF protection
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $.ajaxSetup({
      beforeSend: function (xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
      }
  });  

  $(document).on("submit","#weather_form",function(event){
    // //Prevent default django post behaviour for a form submission.
    event.preventDefault();

    $.ajax({
      url: "/weather/",
      type: "POST",
      data: {type_of_person: $("#id_type_of_person").val(),
        exercise: $("#id_exercise").val(),
        unit: $("#id_unit").val(),
        zip_postal: $("#id_zip_postal").val()},
      dataType: "json",
      contentType: "application/json",
      success: function (data){
        alert("success");
      },
      error: function(xhr,errmsg,err) {
        alert("error");
        console.log(errmsg + "n" + xhr.status + ": " + xhr.responseText)
      }
    });

    return false;
  });
});

In index.html:

           <form action="/weather/" method="post" autocomplete="off" id="weather_form">
                {% csrf_token %}
                {{ form.non_field_errors }}
                {{ error }}
                <ul>
                    <li class="center_text">
                        <h3>Best Time to Go Out</h3>
                    </li>
                    <li>
                        <label>{{ form.type_of_person.label }}: </label>
                        {{ form.type_of_person }}
                        {{ form.type_of_person.errors }}
                    </li>
                    <li>
                        <label>{{ form.exercise.label }}: </label>
                        {{ form.exercise }}
                        {{ form.exercise.errors }}
                    </li>
                    <li>
                        <label>{{ form.unit.label }}: </label>
                        {{ form.unit }}
                        {{ form.unit.errors }}
                    </li>
                    <li>
                        <label>{{ form.zip_postal.label }}: </label>
                        {{ form.zip_postal }}
                        {{ form.zip_postal.errors }}
                    </li>
                    <li>
                        <input id="go" type="submit" value="Go!">
                    </li>
                </ul>
            </form>

In views.py:

class weather(base.TemplateView):
    ...

    @staticmethod
    def post(request, *args, **kwargs):
        ...
        if request.method == "POST":
            ...
            if form.is_valid():
                ...
                return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200)
            else:
                return http.JsonResponse({"error": form.errors}, status=400)

Edit #1:

The request made after clicking "Go!":
enter image description here

Details:
enter image description here

enter image description here

Edit #2:

Other things I tried, but to no avail:

  • Adding async: false to the ajax call.
  • Directing the ajax call to be handled by another view rather than the current view.

Edit #3:

Dependencies for this web app:

  • jquery-ui-1.12.1/jquery-ui.min.css
  • jquery-ui-1.12.1/jquery-ui.structure.min.css
  • jquery-ui-1.12.1/jquery-ui.theme.min.css
  • jquery-3.5.1.min.js
  • jquery-ui-1.12.1/jquery-ui.min.js
  • index.js
  • index.css
  • Django 3.1


Get this bounty!!!

#StackBounty: #python #django #django-models #serialization #django-rest-framework Django REST framework: get field of related model in…

Bounty: 50

I’m new to Django Rest Framework. I’m trying to get my ListAPI to show various fields of my Quiz (and related) models. It’s working fine, except for my attempt_number field. I’m getting the right queryset, but I’m not sure how to get only the relevant value for every query. Users can take every quiz as many times as they want, and I want to show the queryset for each attempt, since the score etc. will be different.

My model setup is as follows:

class Quiz(models.Model):
    title = models.CharField(max_length=15)
    slug = models.SlugField(blank=True)
    questions_count = models.IntegerField(default=0)

class Question(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    label = models.CharField(max_length=1000)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    answer = models.CharField(max_length=100)
    is_correct = models.BooleanField('Correct answer', default=False)

class QuizTaker(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    correct_answers = models.IntegerField(default=0)
    completed = models.BooleanField(default=False)
    attempt_number = models.PositiveIntegerField(default=0)

My serializer for the ListAPI looks as follows:

class MyQuizListSerializer(serializers.ModelSerializer):
    attempt = serializers.SerializerMethodField()
    # etc..
    class Meta:
        model = Quiz
        fields = "__all__"

    def get_attempt(self, obj):
        try:
            quiztaker = QuizTaker.objects.filter(user=self.context['request'].user,
                quiz=obj)
            for attempt in quiztaker:
                attempt_number = attempt.attempt_number
            return attempt_number

If I do it like this, I always get the last value for attempt_number (because the loop overwrites the value). So then I tried to append it to a list instead, like this:

a = []
for attempt in quiztaker:
    attempt_number = attempt.attempt_number
    a.append(attempt_number)
return a

But then I get the list of attempts for every query, instead of the attempt number for each query. I.e. I get the following three times (because in this case there are three attempts):

{
    "id": 4,
    "attempt": [
        1,
        2,
        3
    ]
},

But instead what I want is (and the same for attempt 2 and 3 etc.):

{
    "id": 4,
    "attempt": 1
},

So I tried doing it like this:

return a[attempt_number-1]

Hoping it would give me index zero for attempt number 1, 1 for 2, etc. But then I still just get the last attempt number (3 in this case). How can I solve this?

I also tried just using an IntegerField instead of a SerializerMethodField as follows:

attempt = serializers.IntegerField(read_only=True, source='quiztaker.attempt_number')

But it returned nothing.


Get this bounty!!!

#StackBounty: #python #django #postgresql #iis #hosting How to Host Python, Django, PostgreSQL Application on IIS 10

Bounty: 50

I am trying to host my Django application on Windows 2016 server IIS server. I had used Python, Django, pipenv as virtual environment and PostgreSQL as Database.
How to host is using a Domain Name ?

I had tried almost tried everything available on the internet but till now I am not successful.
Maybe I have not got the perfect tutorials or find the correct one to host the Django Application.

Please help me host the Django Application on IIS 10.

I will be really grateful for the help

Thanks in advance.

Error occurred while reading WSGI handler:

Traceback (most recent call last):
  File "c:userssachin kumar.virtualenvslogin-zru7l_54libsite-packageswfastcgi.py", line 791, in main
    env, handler = read_wsgi_handler(response.physical_path)
  File "c:userssachin kumar.virtualenvslogin-zru7l_54libsite-packageswfastcgi.py", line 633, in read_wsgi_handler
    handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
  File "c:userssachin kumar.virtualenvslogin-zru7l_54libsite-packageswfastcgi.py", line 586, in get_wsgi_handler
    raise Exception('WSGI_HANDLER env var must be set')
Exception: WSGI_HANDLER env var must be set

StdOut:

StdErr:


Get this bounty!!!

#StackBounty: #python-3.x #django #django-models #ffmpeg #django-rest-framework Encoded Video's path gets changed in database after…

Bounty: 50

Hey guys the I have this code to transcode video and it works well without celery. With celery, the path of the file in the database shows a different path and the video cannot be played in the browser, but it saves the file in the correct location in the pc.

If I don’t use celery, then the file path in database is media/videos/videos/<filename>.mp4 and file also gets saved here. This way the template is able to play the video. But if i use celery, the output gets saved in media/videos/videos/<filename>.mp4 but the path in database will be media/<filename>.mp4 somehow and thus template can’t play the video.

Is it because my page gets updated before the task? and not getting saved properly?

views.py

def post(self, *args, **kwargs):
    form = VideoPostForm(self.request.POST or None, self.request.FILES or None)
    if form.is_valid():
        video = form.save(commit=False)
        video.user = self.request.user
        video.save()
        form.save_m2m()
        # task_video_encoding(video.id)
        task_video_encoding.delay(video.id)
        return redirect(reverse('videos:my_video_home'))
    else:
        raise ValidationError('Check all form fields.')

encoding.py

def encode_video(video_id):
    video = VideoPost.objects.get(id = video_id)
    input_file_path = video.temp_file.path
    # print(input_file_path)
    input_file_name = video.title
    #get the filename (without extension)
    filename = os.path.basename(input_file_path)
    # print(filename)
    # path to the new file, change it according to where you want to put it
    output_file_name = os.path.join('{}.mp4'.format(filename))
    # print(output_file_name)
    # output_file_path = os.path.join(settings.MEDIA_ROOT, output_file_name)
    output_file_path = os.path.join(settings.MEDIA_ROOT, 'videos', 'videos', output_file_name)
    # print(output_file_path)

    for i in range(1):
        subprocess.call([settings.VIDEO_ENCODING_FFMPEG_PATH, '-i', input_file_path, '-codec:v', 'libx264', '-crf', '-preset', 'medium',
                    '-b:v', '3000k', '-maxrate', '-bufsize', '6000k', '-vf', 'scale=-2:720',
                    '-codec:a', 'aac', '-b:a', '128k', '-strict', '-2', output_file_path])
    # Save the new file in the database
    video.file = output_file_name
    video.save(update_fields=['file'])
    print(video.file)
    video.temp_file.delete()

models

class VideoPost(models.Model):
    user                = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    title               = models.TextField(max_length=1000)
    temp_file           = models.FileField(upload_to='videos/temp_videos/', validators=[validate_file_extension], null=True)
    file                = models.FileField(upload_to='videos/videos/', validators=[validate_file_extension], blank=True, max_length=255)
    post_date           = models.DateTimeField(auto_now_add=True, verbose_name="Date Posted")
    updated             = models.DateTimeField(auto_now_add=True, verbose_name="Date Updated")
    slug                = models.SlugField(blank=True, unique=True, max_length=255)

Can anyone help me how to change this code in a way to show the converted video properly in the template.


Get this bounty!!!

#StackBounty: #python #django #django-views Creating a Page Visitor Count for Detail View in Django

Bounty: 50

I am trying to collect data for each visitor count related to every Page View Detail.

I have implemented the function which counts the visitors for the page but everytime it is refreshed it will add one more view which is not accurate data. My question is how to add to the function IP adress to show if it does exist the disregard it from the count and the visitor count is only related to new visitors.

Here is the models.py

class Post(models.Model):
    user= models.ForeignKey(User, on_delete=models.CASCADE)
    --------------------------------------------------
    title = models.CharField(max_length=100, unique=True)
    viewCount=models.IntegerField(default=0)

    def __str__(self):
        return self.title

    def incrementViewCount(self):
        self.viewCount += 1
        self.save()

Here is the views.py

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        self.object.incrementViewCount()
        return res


Get this bounty!!!

#StackBounty: #python #django #django-views Changing in the Quantity of variants reflecting in the wrong item in Order Summary

Bounty: 100

I have a problem with the variations and the quantity related to it in the order summary page.

It was working perfectly and all of a sudden (this is an example to simplify):

when I add to the cart 2 items:

  • Item X with a size small
  • Item X with a size medium

When I change the quantity of item X size medium, this change is reflecting in item X size small which was chosen first.

In the order summary, there are a plus and minus in the template to change the quantity.

I have identified the problem but I can’t figure out why it is occurring

Here is the template:

{% block content %}
    <main>
        <div class="container">
        <div class="table-responsive text-nowrap" style="margin-top:90px">
        <h2> Order Summary</h2>
        <table class="table">
            <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Item Title</th>
                <th scope="col">Price</th>
                <th scope="col">Quantity</th>
                <th scope="col">Size</th> 
                <th scope="col">Total Item Price</th>
            </tr>
            </thead>
            <tbody>
            {% for order_item in object.items.all %}
            <tr>
                <th scope="row">{{ forloop.counter }}</th>
                <td>{{ order_item.item.title }}</td>
                <td>{{ order_item.item.price }}</td>
                <td>
                <a href="{% url 'core:remove-single-item-from-cart' order_item.item.slug %}"><i class="fas fa-minus mr-2"></a></i>
                {{ order_item.quantity }}
                <a href="{% url 'core:add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></a></i>
                </td>                
                <td>
                {% if order_item.variation.all %}
                {% for variation in order_item.variation.all %}
                {{ variation.title|capfirst }}
                {% endfor %}
                {% endif %}
                </td> 
                <td>
                {% if order_item.item.discount_price %}
                    $ {{ order_item.get_total_discount_item_price }}
                    <span class="badge badge-primary" style="margin-left:10px">Saving ${{ order_item.get_amount_saved }}</span>
                {% else %}
                    $ {{ order_item.get_total_item_price }}
                {% endif %}
                <a style="color:red" href="{% url 'core:remove-from-cart' order_item.item.slug %}">
                <i class="fas fa-trash float-right"></i>
                </a>
                </td>
            </tr>
            {% empty %}
            <tr>
                <td colspan='5'>Your Cart is Empty</td>
            </tr>
            <tr>
                <td colspan="5">
                <a class='btn btn-primary float-right ml-2'href='/'>Continue Shopping</a>
            </tr>                
            {% endfor %}
            {% if object.coupon %}
            <tr>
                <td colspan="4"><b>Coupon</b></td>
                <td><b>-${{ object.coupon.amount }}</b></td>
            </tr>            
            {% endif %}
            <tr>
                <td colspan="5"><b>Sub total</b></td>
                <td><b>${{ object.get_total }}</b></td>
            </tr>
            <tr>
                <td colspan="5">Taxes</td>
                <td>${{ object.get_taxes|floatformat:2  }}</td>
            </tr>
            {% if object.grand_total %}
            <tr>
                <td colspan="5"><b>Grand Total</b></td>
                <td><b>${{ object.grand_total|floatformat:2 }}</b></td>
            </tr>
            <tr>
                <td colspan="6">
                <a class='btn btn-primary float-right ml-2'href='/'>Continue Shopping</a>
                <a class='btn btn-warning float-right'href='/checkout/'>Proceed to Checkout</a></td>
            </tr> 
            {% endif %}                          
            </tbody>
        </table>
        </div>
        </div>
    </main>
    <!--Main layout-->
{% endblock content %} 

Here is the views.py

class OrderSummaryView(LoginRequiredMixin, View):
    def get(self, *args, **kwargs):

        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            context = {
                'object': order
            }
            return render(self.request, 'order_summary.html', context)
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("/")


@login_required
def add_to_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)

    order_item_qs = OrderItem.objects.filter(
        item=item,
        user=request.user,
        ordered=False
    )

    item_var = []  # item variation
    if request.method == 'POST':
        for items in request.POST:
            key = items
            val = request.POST[key]
            try:
                v = Variation.objects.get(
                    item=item,
                    category__iexact=key,
                    title__iexact=val
                )
                item_var.append(v)
            except:
                pass

        if len(item_var) > 0:
            for items in item_var:
                order_item_qs = order_item_qs.filter(
                    variation__exact=items,
                )

    if order_item_qs.exists():
        order_item = order_item_qs.first()
        order_item.quantity += 1
        order_item.save()
    else:
        order_item = OrderItem.objects.create(
            item=item,
            user=request.user,
            ordered=False
        )
        order_item.variation.add(*item_var)
        order_item.save()

    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        # check if the order item is in the order
        if not order.items.filter(item__id=order_item.id).exists():
            order.items.add(order_item)
            messages.info(request, "This item quantity was updated.")
            return redirect("core:order-summary")
    else:
        ordered_date = timezone.now()
        order = Order.objects.create(
            user=request.user, ordered_date=ordered_date)
        order.items.add(order_item)
        messages.info(request, "This item was added to cart.")
        return redirect("core:order-summary")


@login_required
def remove_from_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_qs = Order.objects.filter(
        user=request.user,
        ordered=False
    )
    if order_qs.exists():
        order = order_qs[0]
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item = OrderItem.objects.filter(
                item=item,
                user=request.user,
                ordered=False
            )[0]
            order.items.remove(order_item)
            order_item.delete()
            messages.info(request, "This item was removed from your cart")
            return redirect("core:order-summary")

        else:
            messages.info(request, "This item was not in your cart")
            return redirect("core:product", slug=slug)
    else:
        messages.info(request, "You don't have an active order")
        return redirect("core:product", slug=slug)


@login_required
def remove_single_item_from_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_qs = Order.objects.filter(
        user=request.user,
        ordered=False
    )
    if order_qs.exists():
        order = order_qs[0]
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item = OrderItem.objects.filter(
                item=item,
                user=request.user,
                ordered=False
            )[0]
            if order_item.quantity > 1:
                order_item.quantity -= 1
                order_item.save()
            else:
                order.items.remove(order_item)
            messages.info(request, "This item quantity was updated")
            return redirect("core:order-summary")
        else:
            messages.info(request, "This item was not in your cart")
            return redirect("core:product", slug=slug)
    else:
        messages.info(request, "You do not have an active order")
        return redirect("core:product", slug=slug)
# End Remove Items (Products removed from Cart)

here is the models.py


class Item(models.Model):
    title             = models.CharField(max_length=100)
    -------------------------------------------------------------------------
    updated           = models.DateTimeField(auto_now_add=False, auto_now=True)
    active            = models.BooleanField(default=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("core:product", kwargs={
            'slug': self.slug
        })

    def get_add_to_cart_url(self):
        return reverse("core:add-to-cart", kwargs={
            'slug': self.slug
        })

    def get_remove_from_cart_url(self):
        return reverse("core:remove-from-cart", kwargs={
            'slug': self.slug
        })


class VariationManager(models.Manager):
    def all(self):
        return super(VariationManager, self).filter(active=True)

    def sizes(self):
        return self.all().filter(category='size')

    def colors(self):
        return self.all().filter(category='color')


VAR_CATEGORIES = (
    ('size', 'size',),
    ('color', 'color',),
    ('package', 'package'),
)


class Variation(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    category = models.CharField(
        max_length=120, choices=VAR_CATEGORIES, default='size')
    title = models.CharField(max_length=120)
    image = models.ImageField(null=True, blank=True)
    price = models.DecimalField(
        decimal_places=2, max_digits=100, null=True, blank=True)
    objects = VariationManager()
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.title

class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    variation = models.ManyToManyField(Variation)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"


Get this bounty!!!

#StackBounty: #django #http #logging #django-rest-framework #gunicorn How to log requests and responses in Django?

Bounty: 50

How can I log all my requests and responses (headers and body) in Django using a middleware?
I’m using Django 2.2 with Django rest framework, so sometimes the requests and responses are original Django type, sometimes of drf.
The app is served behind gunicorn.
I’ve developed middleware but the main problem is I can’t read request’s body twice as it gives me error.


Get this bounty!!!

#StackBounty: #python #django Including an Item Context to a Post Model to activate if statement in Django

Bounty: 50

I am trying to add an Item to a list view, the UserPost list view has already a Post context.

In my project, a user can add a post and add an item each is a different app with different models.

So In my UserPost list view, I have my Posts looped related to a specific user related to it.

What I am trying to do is check if this post.user has an item filtered by the same user and if it does exist a button show appears in the page linking to another page with this list of items related to this user.
To be more descriptive I want to check for Item for the designer__post and link to this page which is {% url 'core:designer-posts' item.designer %}

I hope this clears my question if there are any more clarifications required or code please let me know to add it.

I tried to use make use of an Exists subquery [Django-doc] but I didn’t succeed it perfecting it

Here is the models.py

class Post(models.Model):
    designer = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

Here is the views.py

class UserPostListView(ListView):
    model = Post
    template_name = "user_posts.html"
    context_object_name = 'posts'
    queryset = Post.objects.filter(admin_approved=True)
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted')

Here is the template user_posts.html

{% if item %}
 <a class="primary btn-lg" href="{% url 'core:designer-posts' item.designer %}" role="button">Go to items</a>
{% else %}
  <a href="{% url 'core:designer-posts' item.designer %}">
    <button type="button" class="btn btn-primary btn-lg btn-block">Go to items</button>
  </a>   
{% endif %}

here is the item models.py

class Item(models.Model):
    designer = models.ForeignKey(
        User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

here is the designerlist views.py that I am trying to link to from the user post view if it is available

class DesignerPostListView(ListView):
    model = Item
    template_name = "designer_posts.html"
    context_object_name = 'items'
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Item.objects.filter(designer=user).order_by('-timestamp')

enter image description here


Get this bounty!!!