Это возможно? Использование сигналов для установки глобальной переменной - PullRequest
0 голосов
/ 29 марта 2020

Я сделал эту функцию, которая запускается каждый раз, когда пользователь входит в систему. Я хочу получить ветку от 'user', но каждый раз, когда сеанс установлен, он доступен только для функции, даже после того, как он установлен в BRANCH_ID в файле настроек , любая помощь? Кроме того, я не хочу делать что-либо в функции просмотра с запросом, так как он недоступен для моделей

РЕДАКТИРОВАТЬ Я добавил все модели

def perform_some_action_on_login(sender, request, user, **kwargs):
    """
    A signal receiver which performs some actions for
    the user logging in.
    """
    request.session[settings.BRANCH_ID] = user.profile.branch_id
    branch = request.session.get(settings.BRANCH_ID)
    print(branch)


user_logged_in.connect(perform_some_action_on_login)


class WaybillTabularInlineAdmin(admin.TabularInline):
    model = WaybillItem
    extra = 0
    # form = WaybillItemForm
    fk_name = 'waybill'
    autocomplete_fields = ('product',)


class WaybillAdmin(admin.ModelAdmin):
    list_display = (
        'from_branch',
        'to_branch',
        'updated_by',
    )
    list_filters = (
        'from_branch',
        'to_branch',
        'product',
    )
    inlines = [WaybillTabularInlineAdmin]
    readonly_fields = ("updated_by",)

что Я пытался сделать это продукты по отрасли

class Waybill(models.Model):
    from_branch = models.ForeignKey(
        Branch,
        default=1,
        on_delete=models.CASCADE, related_name='from_branch')
    to_branch = models.ForeignKey(
        Branch, on_delete=models.CASCADE, related_name='to_branch')
    comments = models.CharField(max_length=1024, blank=True)
    created_date = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(
        User, on_delete=models.CASCADE,
        blank=True, null=True,
        related_name='waybill_created')
    updated = models.BooleanField(default=False)
    updated_by = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='waybill_user')

    def __str__(self):
        return 'from {} to {}'.format(
            self.from_branch.branch_name,
            self.to_branch.branch_name,
        )


class WaybillItem(models.Model):
    waybill = models.ForeignKey(Waybill, on_delete=models.CASCADE)
    product = models.ForeignKey(ProductDetail, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()

    def __str__(self):
        return 'from {} to {}'.format(
            self.waybill.from_branch,
            self.waybill.to_branch
        )

class Product(models.Model):
    item = models.ForeignKey(
        Item, on_delete=models.CASCADE, related_name="product")
    branch = models.ForeignKey(
        Branch, default=1, on_delete=models.CASCADE)
    in_stock = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    objects = ProductManager()

    class Meta:
        verbose_name = "Inventory"
        verbose_name_plural = "Inventories"
        ordering = ("-created_date",)
        constraints = [
            models.UniqueConstraint(
                fields=['item', 'branch'], name='unique product'),
        ]

    def __str__(self):
        return self.item.item_description



class ProductDetail(models.Model):
    ITEM_CONDITION_CHOICES = (
        ("NEW", "New"),
        ("BROKEN", "Broken"),
        ("FAIRLY USED", "Fairly Used"),
    )
    condition = models.CharField(max_length=12, choices=ITEM_CONDITION_CHOICES,
                                 default=ITEM_CONDITION_CHOICES[0][0])
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    short_description = models.CharField(max_length=255, blank=True)
    color = models.CharField(max_length=15, blank=True)
    bought_price = models.PositiveIntegerField(default=0.00)
    sales_price = models.PositiveIntegerField(default=0.00)
    retail_price = models.PositiveIntegerField(default=0.00)
    item_code = models.CharField(max_length=15, default=0)
    item_model_number = models.CharField(max_length=20, default=0)
    quantity = models.PositiveIntegerField(default=0)
    manufacturer_website = models.CharField(max_length=255, blank=True)
    generated_url = models.CharField(max_length=255, blank=True)
    created_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(auto_now=True)
    # objects = ProductDetailManager()
...