#StackBounty: #python #django #oop Create a Blog which support multiple type of post

Bounty: 50

I am a new user of Django, and I am trying to figure out how to created a model which can support many kind (type) of elements.

This is the plot : I want to create a Blog module on my application.
To do this, I created a model Page, which describe a Blog Page. And a model PageElement, which describe a Post on the blog. Each Page can contain many PageElement.

A PageElement can have many types, because I want my users could post like just a short text, or just a video, or just a picture. I also would like (for example) the user could just post a reference to another model (like a reference to an user). Depending of the kind of content the user posted, the HTML page will display each PageElement in a different way.

But I don’t know what is the right way to declare the PageElement class in order to support all these cases 🙁

Here is my Page model :

class Page(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)

    # Basical informations
    title = models.CharField(max_length=150)
    description = models.TextField(blank=True)

    # Foreign links
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        related_name='pages_as_user'
    )

    created_at = models.DateTimeField(default=timezone.now)

    # Other fields ....

    class Meta:
        indexes = [
            models.Index(fields=['uuid']),
            models.Index(fields=['user', 'artist'])
        ]

For now, I have two solutions, the first one use inheritance : When you create a new post on the blog, you create an Element which inherit from PageElement model. Here are my different Models for each cases :

class PageElement(models.Model):
    page = models.OneToOneField(
        Page,
        on_delete=models.CASCADE,
        related_name='%(class)s_elements'
    )

    updated_at = models.DateTimeField(default=timezone.now)
    created_at = models.DateTimeField(default=timezone.now)

class PageImageElement(PageElement):
    image = models.ImageField(null=True)
    image_url = models.URLField(null=True)

class PageVideoElement(PageElement):
    video = models.FileField(null=True)
    video_url = models.URLField(null=True)

class PageTextElement(PageElement):
    text = models.TextField(null=True)

class PageUserElement(PageElement):
    user = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
        related_name='elements'
    )

This solution would be the one I have choosen if I had to work if a “pure” Django. Because I could stored each PageElement in a dictionnary and filter them by class. And this solution could be easily extended in the futur with new type of content.

But with Django models. It seems that is not the best solution. Because it will be really difficult to get all PageElement children from the database (I can’t just write “page.elements” to get all elements of all types, I need to get all %(class)s_elements elements manually and concatenate them :/). I have thinked about a solution like below (I don’t have tried it yet), but it seems overkilled for this problem (and for the database which will have to deal with a large number of request):

class Page(models.Model):
    # ...
    def get_elements(self):
        # Retrieve all PageElements children linked to the current Page
        R = []
        fields = self._meta.get_fields(include_hidden=True)
        for f in fields:
            try:
                if 'conversation_elements' in f.name:
                    R += getattr(self, f.name)
            except TypeError as e:
                continue

        return R

My second “solution” use an unique class which contains all fields I need. Depending of the kind of PageElement I want to create, I would put type field to the correct value, put the values in the corresponding fields, and put to NULL all other unused fields :

class PageElement(models.Model):
    page = models.OneToOneField(
        Page,
        on_delete=models.CASCADE,
        related_name='elements'
    )

    updated_at = models.DateTimeField(default=timezone.now)
    created_at = models.DateTimeField(default=timezone.now)

    TYPES_CHOICE = (
        ('img', 'Image'),
        ('vid', 'Video'),
        ('txt', 'Text'),
        ('usr', 'User'),
    )
    type = models.CharField(max_length=60, choices=TYPES_CHOICE)

    # For type Image
    image = models.ImageField(null=True)
    image_url = models.URLField(null=True)

    # For type Video
    video = models.FileField(null=True)
    video_url = models.URLField(null=True)

    # For type Text
    text = models.TextField(null=True)

    # For type User
    user = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
        related_name='elements',
        null=True
    )

With this solution, I can retrieve all elements in a single request with “page.elements”. But it is less extendable than the previous one (I need to modify my entire table structure to add a new field or a new kind of Element).

To be honnest, I have absolutly no idea of which solution is the best. And I am sure other (better) solutions exist, but my poor Oriented-Object skills don’t give me the ability to think about them ( 🙁 )…

I want a solution which can be easily modified in the future (if for example, I want to add a new Type “calendar” on the Blog, which reference a DateTime). And which would be easy to use in my application if I want to retrieve all Elements related to a Page…

Thanks for your attention 🙂


Get this bounty!!!

#StackBounty: #python #django #session #cookies #redis Django: Sessions not working, users continually being logged out and prompted to…

Bounty: 100

I want to keep users on a Heroku app logged in, and they are currently being logged out on every view that requires login. The problem seems to be related to the sessionid in the Response Cookie not being set. E.g., clicking on “Account” will redirect users to the login view.

Response Headers

Location: /login?next=/home/
Set-Cookie: sessionid=; Domain=.appname.com; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/

settings.py

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_DOMAIN = ".appname.com"
SESSION_COOKIE_AGE = 2419200
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_SECURE = True

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_DOMAIN = ".appname.com"

SECURE_SSL_REDIRECT = True

# ...

MIDDLEWARE_CLASSES = [
    'django.middleware.cache.UpdateCacheMiddleware',

     # ...

    'django.middleware.cache.FetchFromCacheMiddleware',
]

# ...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'appname',
    }
}

# https://devcenter.heroku.com/articles/python-concurrency-and-database-connections
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# https://devcenter.heroku.com/articles/heroku-redis
CACHES = {
    "default": {
         "BACKEND": "redis_cache.RedisCache",
         "LOCATION": os.environ.get('REDIS_URL'),
    }
}

views.py

def login(request):
    if hasattr(request, 'session') and not request.session.session_key:
        request.session.save()
        request.session.modified = True
    if request.user.is_authenticated():
        return redirect('home')
    else:
        return render(request, "login.html", {})

@login_required
def home(request):
    return render(request, "home.html", {})

@require_POST
def ajax_login(request):
    data = {}

    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']

        user = authenticate(username=email, password=password)
        if user is not None:
            login(request, user)
            data = {
                'is_authenticated': True
            }
    else:
        form = LoginForm()
        data = {
            'is_authenticated': False
        }
    return JsonResponse(data)

Here is how the app makes AJAX calls.

app.js

$.ajaxSetup({
  beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});
$.ajax({
  url: '/ajax/login',
  type: 'POST',
  data: {
    'username': username,
    'password': password,
  },
  dataType: 'json',
  credentials: 'include',
  success: function (data) {
    if (data.is_authenticated) {
      window.location.href = "/home/";
    }
  }
});

app.html


var csrftoken = $("[name=csrfmiddlewaretoken]").val();


Get this bounty!!!

#StackBounty: #python #django #django-rest-framework Django Rest Framework – passing Model data through a function, then posting output…

Bounty: 50

(Django 2.0, Python 3.6, Django Rest Framework 3.8)

I’m trying to fill the calendarydays field in the model below:

Model

class Bookings(models.Model):
    booked_trainer = models.ForeignKey(TrainerProfile, on_delete=models.CASCADE)
    booked_client = models.ForeignKey(ClientProfile, on_delete=models.CASCADE)
    trainer_availability_only = models.ForeignKey(Availability, on_delete=models.CASCADE)
    calendarydays = models.CharField(max_length=300, blank=True, null=True)

    PENDING = 'PENDING'
    CONFIRMED = 'CONFIRMED'
    CANCELED = 'CANCELED'

    STATUS_CHOICES = (
        (PENDING, 'Pending'),
        (CONFIRMED, 'Confirmed'),
        (CANCELED, 'Canceled')
    )


    booked_status = models.CharField(
        max_length = 9,
        choices = STATUS_CHOICES,
        default = 'Pending'
    )

    def __str__(self):
        return str(self.trainer_availability_only)

Now, I have a function that takes values from trainer_availability_only and converts those values to a list of datetime strings, the returned output would look like this:

{‘calendarydays’: [‘2018-07-23 01:00:00’, ‘2018-07-23 02:00:00’,
‘2018-07-23 03:00:00’, ‘2018-07-30 01:00:00’, ‘2018-07-30 02:00:00’,
‘2018-07-30 03:00:00’, ‘2018-08-06 01:00:00’, ‘2018-08-06 02:00:00’,
‘2018-08-06 03:00:00’, ‘2018-08-13 01:00:00’, ‘2018-08-13 02:00:00’,
‘2018-08-13 03:00:00’, ‘2018-08-20 01:00:00’, ‘2018-08-20 02:00:00’,
‘2018-08-20 03:00:00’]}

Problem

How can I fill the calendarydays field with the function output for a user to select from a dropdown, and where should I implement this logic (in my view or the serializer)? My main point of confusion is that, because my function depends on data from trainer_availability_only, I don’t want to create a separate model/table for this information (as that would seem too repetitive). I also don’t fully understand where in my serializers or views I can implement some sort of dropdown for a User to choose a single calendarydays value for (like I would be able to for a ForeignKey or OneToOneField for example).

Details for the other models aren’t really relevant to the question, except trainer_availability_only, which basically gives the user a dropdown selection that would look like this:

('Monday','12:00 am - 1:00 am')
('Wednesday','4:00 pm - 5:00 pm')
etc.

Any help is greatly appreciated.


Get this bounty!!!

#StackBounty: #python #django #amazon-web-services #deployment #elastic-beanstalk AWS Elastic Beanstalk health check issue

Bounty: 50

First I apologize for not being familiar with English.

My web application is Django and web server use Nginx, use Docker image and Elastic Beanstalk to deployment.

Normally there was no problem, but as the load balancer expands EC2, my web server becomes 502 Bad Gateway.

I’m checked Elastic Beanstalk application logs, about 16% of the requests returned 5xx errors, at which time the load balancer expands EC2, causing the web server to transition to the 502 Bad Gateway state and the Elastic Beanstalk application to the Degraded state.

Is this a common problem when the load balancer performs a health check? If not, can I tell you how to turn off the Health Check?

I will attach a capture image for your help.

enter image description here


Get this bounty!!!

#StackBounty: #python #django #django-models #django-1.8 #django-1.9 Using a model's sub-classes as choice options for that model r…

Bounty: 100

We are trying to upgrade a legacy code’s django version from 1.8 to 1.9. We have one model that is defined like this:

def _get_descendant_question_classes():
    stack = [Question]

    while stack:
        cls = stack.pop()
        stack.extend(cls.__subclasses__())
        yield cls

def _get_question_choices():
    question_classes = _get_descendant_question_classes()

    for cls in question_classes:
        yield (cls.slug, cls._meta.verbose_name)

class Question(models.Model):
    type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug)

class TextQuestion(Question): pass
class SelectQuestion(Question): pass
...

Basically the model wants to use its sub-classes as choice options for one of its fields. It does this with traversing the model in a DFS manner and yielding all the sub-classes.

This code works in django 1.8 but in django 1.9 it gives this error:

Traceback (most recent call last):
  File "./manage.py", line 16, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 324, in execute
    django.setup()
  File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/saeed/saeed/survey/models.py", line 85, in <module>
    class Question(models.Model):
  File "/home/saeed/saeed/survey/models.py", line 99, in Question
    type = models.CharField(max_length=10, choices=_get_question_choices(), default=slug)
  File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1072, in __init__
    super(CharField, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__
    choices = list(choices)
  File "/home/saeed/saeed/survey/models.py", line 65, in _get_question_choices
    for cls in question_classes:
  File "/home/saeed/saeed/survey/models.py", line 54, in _get_descendant_question_classes
    stack = [Question]
NameError: global name 'Question' is not defined

I understand the problem what I don’t understand is how this works in django 1.8? What has changed in django 1.9 that causes this? What is the best way to fix this?


Get this bounty!!!

#StackBounty: #python #django #django-i18n "django-admin.py makemessages -l en" adds Plural-Forms to the output file

Bounty: 50

Every time I run django-admin.py makemessages -l en, it adds the following line to the djangojs.po file:

"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;n"

after that running python manage.py runserver break out whith this error:

ValueError: plural forms expression could be dangerous

Of course removing that line fix the error and make it go away.
How can I prevent this line from being added?


Get this bounty!!!

#StackBounty: #python #django #python-3.x #django-models Django 2.0 Access Models (CREATE/REMOVE/FILTER) Standalone [without manage.py …

Bounty: 50

I have a Django project and I wanted to generate some objects (from the models)

What I’m trying to get at : Standalone Python Script to create bunch of objects and/or filter,delete.

after importing the model with from apps.base.models import MyModel
and setting up the configuration as the previous StackOverflow Questions suggested I was not able to run the script.

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")
import django

django.setup()
from apps.base.models import MyModel

Please note that this is on Django version 2.0.6 [Django 2.0+].

Correct settings have been used, (i.e. myProject.settings)

  • After properly configuring everything else I get the following error:
    • RuntimeError: Model class apps.base.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.


Get this bounty!!!

#StackBounty: #apache-2.4 #django Apache: LocationMatch or ProxyMatch doesn't work with RegEx

Bounty: 50

I want to redirect requests for a exact specific location to proxy server but both solutions doesn’t work:

<VirtualHost *:80>
  ServerName exmaple.com

<LocationMatch "^/test01$">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</LocationMatch>

<ProxyMatch "^/test02$">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</ProxyMatch>

</VirtualHost>

Test:

$ curl -I exmaple.com/test01
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:37:10 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

$ curl -I exmaple.com/test02
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:37:13 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

When I remove the RegEx part then it works but I want Apache to display the 404, not the Django development server:

<LocationMatch "/test01">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</LocationMatch>

$ curl -I exmaple.com/test01
HTTP/1.1 200 OK
Date: Sun, 17 Jun 2018 15:42:26 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
Content-Length: 12767

$ curl -I exmaple.com/test01/none
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:42:33 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html; charset=UTF-8
X-Frame-Options: SAMEORIGIN
Content-Length: 2073

Update: Mon 18 Jun 14:40:59 UTC 2018

So I’ve done some further research and according to Apache docs:

When used inside a <Location> section, the first argument is omitted
and the local directory is obtained from the <Location>. The same will
occur inside a <LocationMatch> section; however, ProxyPass does not
interpret the regexp as such, so it is necessary to use ProxyPassMatch
in this situation instead.

So I tried ProxyPassMatch and it works however the RegEx matched is passed to Proxy http://localhost:8000/test01 and this is not what I want.

I can achieve this easily with Nginx:

server {
    listen 80;
    server_name exmaple.com;

    location = /test01/ {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
    }
}

How I can do something similar with Apache?

Update: Sun 24 Jun 10:46:12 UTC 2018

<LocationMatch "^/test01$">
  Redirect / http://test.com/
</LocationMatch>

$ curl -I exmaple.com/test01
HTTP/1.1 302 Found
Date: Sun, 24 Jun 2018 10:47:04 GMT
Server: Apache
Location: http://test.com/test01
Content-Type: text/html; charset=iso-8859-1


Get this bounty!!!

#StackBounty: #apache-2.4 #django Apache: LocationMatch or ProxyMatch doesn't work with RegEx

Bounty: 50

I want to redirect requests for a exact specific location to proxy server but both solutions doesn’t work:

<VirtualHost *:80>
  ServerName exmaple.com

<LocationMatch "^/test01$">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</LocationMatch>

<ProxyMatch "^/test02$">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</ProxyMatch>

</VirtualHost>

Test:

$ curl -I exmaple.com/test01
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:37:10 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

$ curl -I exmaple.com/test02
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:37:13 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

When I remove the RegEx part then it works but I want Apache to display the 404, not the Django development server:

<LocationMatch "/test01">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</LocationMatch>

$ curl -I exmaple.com/test01
HTTP/1.1 200 OK
Date: Sun, 17 Jun 2018 15:42:26 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
Content-Length: 12767

$ curl -I exmaple.com/test01/none
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:42:33 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html; charset=UTF-8
X-Frame-Options: SAMEORIGIN
Content-Length: 2073

Update: Mon 18 Jun 14:40:59 UTC 2018

So I’ve done some further research and according to Apache docs:

When used inside a <Location> section, the first argument is omitted
and the local directory is obtained from the <Location>. The same will
occur inside a <LocationMatch> section; however, ProxyPass does not
interpret the regexp as such, so it is necessary to use ProxyPassMatch
in this situation instead.

So I tried ProxyPassMatch and it works however the RegEx matched is passed to Proxy http://localhost:8000/test01 and this is not what I want.

I can achieve this easily with Nginx:

server {
    listen 80;
    server_name exmaple.com;

    location = /test01/ {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
    }
}

How I can do something similar with Apache?

Update: Sun 24 Jun 10:46:12 UTC 2018

<LocationMatch "^/test01$">
  Redirect / http://test.com/
</LocationMatch>

$ curl -I exmaple.com/test01
HTTP/1.1 302 Found
Date: Sun, 24 Jun 2018 10:47:04 GMT
Server: Apache
Location: http://test.com/test01
Content-Type: text/html; charset=iso-8859-1


Get this bounty!!!

#StackBounty: #apache-2.4 #django Apache: LocationMatch or ProxyMatch doesn't work with RegEx

Bounty: 50

I want to redirect requests for a exact specific location to proxy server but both solutions doesn’t work:

<VirtualHost *:80>
  ServerName exmaple.com

<LocationMatch "^/test01$">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</LocationMatch>

<ProxyMatch "^/test02$">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</ProxyMatch>

</VirtualHost>

Test:

$ curl -I exmaple.com/test01
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:37:10 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

$ curl -I exmaple.com/test02
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:37:13 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

When I remove the RegEx part then it works but I want Apache to display the 404, not the Django development server:

<LocationMatch "/test01">
  ProxyPreserveHost On
  ProxyPass http://localhost:8000/
  ProxyPassReverse http://localhost:8000/
</LocationMatch>

$ curl -I exmaple.com/test01
HTTP/1.1 200 OK
Date: Sun, 17 Jun 2018 15:42:26 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
Content-Length: 12767

$ curl -I exmaple.com/test01/none
HTTP/1.1 404 Not Found
Date: Sun, 17 Jun 2018 15:42:33 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html; charset=UTF-8
X-Frame-Options: SAMEORIGIN
Content-Length: 2073

Update: Mon 18 Jun 14:40:59 UTC 2018

So I’ve done some further research and according to Apache docs:

When used inside a <Location> section, the first argument is omitted
and the local directory is obtained from the <Location>. The same will
occur inside a <LocationMatch> section; however, ProxyPass does not
interpret the regexp as such, so it is necessary to use ProxyPassMatch
in this situation instead.

So I tried ProxyPassMatch and it works however the RegEx matched is passed to Proxy http://localhost:8000/test01 and this is not what I want.

I can achieve this easily with Nginx:

server {
    listen 80;
    server_name exmaple.com;

    location = /test01/ {
        proxy_pass http://localhost:8000/;
        proxy_set_header Host $host;
    }
}

How I can do something similar with Apache?

Update: Sun 24 Jun 10:46:12 UTC 2018

<LocationMatch "^/test01$">
  Redirect / http://test.com/
</LocationMatch>

$ curl -I exmaple.com/test01
HTTP/1.1 302 Found
Date: Sun, 24 Jun 2018 10:47:04 GMT
Server: Apache
Location: http://test.com/test01
Content-Type: text/html; charset=iso-8859-1


Get this bounty!!!