简体   繁体   中英

ArrayField doesn't get updated?

I'm trying to check if a lesson has been done (by checking if the page has been visited once on a logged account).

I've been trying to check if the page has been visited. If not, the ID should be added in the array of visited pages.

I'm checking all the possible situations (or at least the one I could think of) and when I have to, I add another lection.id to the array of accessed lessons. After priniting this array everytime, I saw that the lesson id gets added, but not in the database. (if I check the DB or if I change the page the lesson id disappears)

views.py

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from .models import Lectie

def lectii(req):
    lectii = Lectie.objects.all().order_by("id")
    if req.user.is_authenticated:
        if req.user.profile.lectiiRezolvate == None:
            lectiiRezolvate=[]
        else:
            lectiiRezolvate = req.user.profile.lectiiRezolvate
    else:
        lectiiRezolvate=[]
    context = {
        'lectii': lectii,
        'lectiiRezolvate': lectiiRezolvate
    }
    print(lectiiRezolvate)
    return render(req, '../templates/pagini/lectii-selector.html', context)

def lectie(req, lectie_id):
    if req.user.is_authenticated:
        if req.user.profile.lectiiRezolvate == None:
            req.user.profile.lectiiRezolvate.append(lectie_id)
            user.profile.save()
            print(req.user.profile.lectiiRezolvate)
        else:
            if lectie_id in req.user.profile.lectiiRezolvate:
                pass
            else:
                req.user.profile.lectiiRezolvate.append(lectie_id)
                print(req.user.profile.lectiiRezolvate)
    else:
        pass        
    lectie2 = get_object_or_404(Lectie, pk=lectie_id)
    lectiePDF = 'lectii/lectia-{}.pdf'.format(lectie2)
    context = {
        'lectiePDF': lectiePDF,
        'lectie2': lectie2,
    }
    return render(req, '../templates/pagini/lectii.html', context)

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.lectii, name="lectii"),
    path('<int:lectie_id>', views.lectie, name="lectie")
]

lectii-selector.html

{% extends 'base.html' %}
{% block content %}
    </div>
    <div id="middle-section" class="container-fluid container-fluid-margin">
        {% for lectie in lectii %}
        <div class="row content-block" style="padding-top: 2rem;"> 
            <div class="col-md-12 text-card">
                    <div class="card card-custom">
                            {% if lectie.id in lectiiRezolvate %}               
                            <div class="card-body">                      
                                    <h5 class="card-title">Capitolul {{lectie.capitol}}<i class="fas fa-check"></i></h5>
                                    <p class="card-text">{{lectie.cardText}}</p>
                                    <a href="{% url 'lectie' lectie.id %}" class="btn btn-primary">Reia</a>
                            </div>
                            {% else %}
                            <div class="card-body">                      
                                    <h5 class="card-title">Capitolul {{lectie.capitol}}</h5>
                                    <p class="card-text">{{lectie.cardText}}</p>
                                    <a href="{% url 'lectie' lectie.id %}" class="btn btn-primary">Începe</a>
                            </div>
                            {% endif %}                                
                        </div>
            </div>
        </div>
        {% endfor %}
    </div>
{% endblock %}

models.py from accounts (I've extended the default user model)

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.postgres.fields import ArrayField

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    xp = models.IntegerField(default=0)
    lectiiRezolvate = ArrayField(models.IntegerField(), null=True, blank=True)
    exercitiiRezolvate = ArrayField(models.IntegerField(), null=True, blank=True)
    exercitiiProvocari = ArrayField(models.IntegerField(), null=True, blank=True)
    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

I feel like I'm not doing the adding into the DB correctly and I'm missing something. I've tried to solve it reading the django docs, but I didn't find anything useful.

So I suppose the Profile doesn't get updated and I'm doing something wrong. How can I make it work?

You only save the profile if the array field is previously blank; you don't save it after appending the new ID.

(Note also, you can avoid the need for checking for None if you make add a default=list to the field definition.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM