V
V
Vitaly Ananiev2022-04-03 21:22:15
Django
Vitaly Ananiev, 2022-04-03 21:22:15

How to filter online users in my ContextAvailability(View) class?

Tell me, not far away in Django, how can I filter online users when posting a request (what logic can I write here)?
models

class User(AbstractUser):
    last_online = models.DateTimeField(verbose_name='Online', blank=True, null=True)

    def is_online(self):
        if self.last_online:
            return (timezone.now() - self.last_online) < timezone.timedelta(minutes=15)
        return False

    def get_online_info(self):
        if self.is_online():
            return _('Online')
        if self.last_online:
            return _('Last visit {}').format(naturaltime(self.last_online))
           
        return _('Unknow')

    def get_online(self):
        if self.is_online():
            return True
        else:
            return False

class Sell(models.Model):
    class Meta:
        abstract = True

    owner = models.ForeignKey('Customer', null=True, blank=True, verbose_name='Продавец', on_delete=models.CASCADE)
    games = models.ForeignKey(Games, null=True, blank=True, verbose_name='Игра', on_delete=models.CASCADE)
    server = models.ForeignKey(Servers, blank=True, null=True, verbose_name='Сервер', on_delete=models.CASCADE)
    price = models.DecimalField(verbose_name='Цена', max_digits=9, decimal_places=2, null=True, blank=True)

    def __str__(self):
        return f'{self.owner}'


class Availability(Sell):
    availability = models.PositiveIntegerField(verbose_name='Наличие игровой валюты', null=True, blank=True)

    class Meta:
        verbose_name = "Игровая валюта(Продажа)"
        verbose_name_plural = "Игровая валюта(Продажа)"

    def get_online(self, owner):
        return User.get_online(owner)

class Customer(models.Model):
    user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE, blank=True, null=True,
                             max_length=25)
    avatar = models.ImageField("Аватар", upload_to=user_directory_path, default='photos/profile.png', blank=True)
    date = models.DateField("Дата создания", auto_now=False, auto_now_add=True, blank=True, null=True)

    def __str__(self):
        return f'{self.user}'

    class Meta:
        verbose_name = "Профиль пользователя"
        verbose_name_plural = "Профиль пользователей"
        ordering = ('id',)

    def profile_absolute_url(self):
        return reverse('profile_detail', kwargs={'slug': self.id})


views
class GamesDetailView(ContextDetail, ContextAvailability):
    model = Games
    slug_field = "id_num"
    context_object_name = 'games'
    queryset = Games.objects.filter(game_currency=True)

class ContextDetail(DetailView):
    def get_context_data(self, **kwargs):
        server = Servers.objects.filter(id_num=self.kwargs.get('slug'))
        context = super().get_context_data(**kwargs)
        context['availability'] = Availability.objects.filter(games__id_num=self.kwargs.get('slug'))
        context['accounts'] = Account.objects.filter(games__id_num=self.kwargs.get('slug'))
        context['items'] = Items.objects.filter(games__id_num=self.kwargs.get('slug'))
        context['services'] = Services.objects.filter(games__id_num=self.kwargs.get('slug'))
        context['server'] = Servers.objects.filter(id_num=self.kwargs.get('slug'))
        context['text'] = ContextText.objects.all()
        context['form'] = FilterServerForm(server)
        context['form_profile'] = ProfileForm()
        context['formAdd'] = AddAll(server)
        context['profiles'] = Customer.objects.all()

        if self.request.user.is_authenticated:
            context['user_name'] = Customer.objects.get(user=self.request.user)
        else:
            context['user_name'] = ''
        return context

class ContextAvailability(View):

    def post(self, request, **kwargs):
        server = Servers.objects.filter(id_num=self.kwargs.get('slug'))
        if request.method == 'POST':
            form = FilterServerForm(server, request.POST)
            if form.is_valid():
                servers = form.cleaned_data['name']

                contextAvailability = {
                    'games': Games.objects.get(id_num=self.kwargs.get('slug'), game_currency=True),
                    'form': form,
                    'text': ContextText.objects.all(),
                    'availability': Availability.objects.filter(server__name=servers.name,
                                                                server__id_num=self.kwargs.get('slug'))
                }

                return render(request, 'Pay/games_detail.html', contextAvailability)

forms
class FilterServerForm(forms.Form):
    def __init__(self, server, *args, **kwargs):
        super(FilterServerForm, self).__init__(*args, **kwargs)
        self.fields['name'].queryset = server

    name = forms.ModelChoiceField(queryset=Servers.objects.all(), label=False, empty_label=None)
    user_active = forms.BooleanField(label=False, required=False)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question