D
D
Dmitry2017-01-31 22:27:07
Django
Dmitry, 2017-01-31 22:27:07

Django doesn't update data on the front after adding a user to a group, why?

The front displays a list of filtered users by group. When adding or removing a user to a group, the data on the front is updated only after the application is restarted. Which way to look?

#model.py
class User(AbstractUser):
    name = models.CharField(_("Name of User"), blank=True, max_length=255)
    homepage = models.URLField(blank=True)
    about = models.TextField(_("About Me"), blank=True)
    country = models.CharField(_("Country"), blank=True, null=True, max_length=255)
    objects = UserManager()

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})

#views
class UserAmbassadorsListView(ListView):
    model = User
    # These next two lines tell the view to index lookups by username
    slug_field = "username"
    slug_url_kwarg = "username"
    template_name = 'users/user_ambassadors.html'
    ambassadors_users = User.objects.get_grouped_users("Ambassadors")
    user_photo_from_app = FpAvatar.objects.filter

    def sumchanters(self):
        # chants = counters.videos_moderated_published
        chanter = FPVideo.objects.aggregate(Sum('chanters'))
        result = chanter['chanters__sum']
        return result

    def am_photo(self, user_id):

        try:
            user = SocialAccount.objects.filter(user_id=user_id)
            data = user.values()

            dic_data = data[0]

            provider = dic_data['provider']

            if 'vk' in provider:
                photo_big = dic_data['extra_data']['photo_big']
                return photo_big
            elif 'facebook' in provider:
                uid = dic_data['extra_data']['id']

                photo_big = 'http://graph.facebook.com/'+uid+'/picture?type=large'

                return photo_big
            elif 'google' in provider:
                photo_big = dic_data['extra_data']['picture']
                return photo_big
        except Exception:
            return 'photo'

    def get_context_data(self, **kwargs):
        """
        Returns:
            dict
        """
        ambassadors = self.ambassadors_users

        dambassadors = []
        for i in range(len(ambassadors)):
            username = ambassadors[i]
            print(username)
            number_of_videos = FPVideo.objects.count_user_videos(username)

            chanters = FPVideo.objects.sum_user_videos_chants(username)
            if chanters == None:
                chanters = 0
            try:
                usercountry = User.objects.filter(username__exact=username).values_list('country', flat=True)[0]
            except IndexError as e:
                print(e)
                usercountry = ''

            print(usercountry)
            userid = User.objects.filter(username__exact=username)
            userid = userid.values()[0]['id']

            try:
                avatar = self.user_photo_from_app(user_id=userid).values()[0]['imagefile']
                if 'media' not in avatar:
                    avatar = str('/media/')+avatar
            except IndexError:
                avatar = '/static/img/avatar.svg'
            except Exception as e:
                return e
            photo = self.am_photo(userid)

            human = (userid, username, number_of_videos, chanters, usercountry, avatar)
            dambassadors.append(human)

        keys = ('userid', 'username', 'videos', 'chanters', 'country', 'avatar')
        ambass = {}
        for i in range(len(dambassadors)):
            ambass[dambassadors[i][1]] = dict(zip(keys, dambassadors[i]))



        context = super(UserAmbassadorsListView, self).get_context_data(**kwargs)
        context['left_days'] = counters.countdowntime()
        context['ambassadors'] = ambass.items()
        context['sumchanters'] = self.sumchanters()#counters.chanters['chanters__sum']
        context['total_videos'] = counters.videos
        context['total_ambassadors'] = len(ambassadors)
        return context

template.html
<table class="ambassadors-table">
    <tr>
        <th>Position</th>
        <th>Ambassador name</th>
        <th>Country</th>
        <th>Total videos</th>
        <th>Total chants</th>
    </tr>

    {% for key, value in ambassadors %}
        <tr class="a-rows">
            <td><span></span></td>
            {#            <td>{% avatar user 65 class="img-circle img-responsive" id="user_avatar" %}</td>#}
            {#            <td><a href="{% url 'users:detail' user.username %}" class="list-group-item">{{ user.username }}</a></td>#}
            {#            {% users.username  %}#}
            <td>
{#                <div class="avatar"><img src="{{ value.photo }}"></div>#}
                <div class="avatar"><img src="{{ value.avatar }}"></div>
                {{ value.username }}</td>
            <td>{{ value.country }}</td>
            <td>{{ value.videos }}</td>
            <td class="rating">{{ value.chanters }}</td>
        </tr>
    {% endfor %}
</table>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tema_sun, 2017-02-01
@tema_sun

Вот этот атрибут

ambassadors_users = User.objects.get_grouped_users("Ambassadors")
вычисляется один раз. И далее используется уже результат вычислений.
Поэтому
всегда одинаковый.

A
alex_deerk, 2017-02-01
@alex_deerk

Без JS страница "жить" не будет

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question