Y
Y
Yes2019-10-10 15:14:00
Django
Yes, 2019-10-10 15:14:00

How to save a model via a function inside models.py?

There is a function that works fine in views.py:

def save_request_metric(request, result):
    user = None
    if not request.user.is_anonymous:
        user = request.user
    RequestMetric.objects.create(
        ip_address=ip_work.get_client_ip(request),
        user=user,
        request_url=request.get_full_path(),
        request_method=request.method,
        result=result
    )

The model looks like this:
class RequestMetric(models.Model):
    user = models.ForeignKey(
        User,  # - это from django.contrib.auth.models import User
        null=True,
        on_delete=models.CASCADE,
        verbose_name='Пользователь',
    )
    request_url = models.CharField(
        max_length=599,
        null=False,
        blank=True,
        verbose_name='Тип запроса'
    )
    request_method = models.CharField(
        max_length=29,
        null=False,
        blank=True,
        verbose_name='Метод запроса'
    )
    time = models.DateTimeField(
        auto_now_add=True,
        null=False,
        verbose_name='Вермя записи'
    )
    ip_address = models.GenericIPAddressField(
        null=True,
        verbose_name='IP адрес'
    )
    result = models.CharField(
        max_length=120,
        null=True,
        blank=False,
        verbose_name='Результат'
    )

So I'm trying to make a function inside the model in order to save data through it:
def create(self, request, result):
        user = None
        if not request.user.is_anonymous:
            user = request.user
        print(type(user))
        self.ip_address = ip_work.get_client_ip(request),
        self.user = user,
        self.request_url = request.get_full_path(),
        self.request_method = request.method,
        self.result = result
        self.save()

but I get
ValueError: Cannot assign "(,)": "RequestMetric.user" must be a "User" instance.

I searched for what the problem is, but I did not find anything to help:
self.user = User.objects.get(pk=user.id), 
#ValueError: Cannot assign "(<User: qqquser>,)": "RequestMetric.user" must be a "User" instance.

self.user = User.objects.get(pk=user),
#TypeError: int() argument must be a string, a bytes-like object or a number, not 'User'

self.user = None,
#ValueError: Cannot assign "(None,)": "RequestMetric.user" must be a "User" instance.

self.user = User.objects.get(user=request.user),
#django.core.exceptions.FieldError: Cannot resolve keyword 'user' into field. Choices are: 'список полей'

self.user_id = user.pk,
#TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

I call the functions like this:
save_request_metric(request, 'ok') # обычная def функция в том же view из которого идет вызов. Работает прекрасно.

RequestMetric().create( # функция внутри модели 'RequestMetric'
     request=request, result='ok'
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Keofaste, 2019-10-10
@volkihar

Extra commas at the end of lines

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question