Answer the question
In order to leave comments, you need to log in
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
)
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='Результат'
)
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()
ValueError: Cannot assign "(,)": "RequestMetric.user" must be a "User" instance.
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'
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question