I have simple model where user writes some text and saves it, I need to add current user to this created object. Right now I have such code where user can be chosen manually, how do I make it automatically? I know about user=self.request.user, but I don't know how to use it in Models. Sorry if this question is silly, I'm new to Django
class SomeText(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
keyword = models.TextField(verbose_name='Add your text here')
CodePudding user response:
To assign a user automatically user must be login. If user is already login then you can try the below code
In your views.py
from django.http import HttpResponse
from .models import SomeText
def assign(request):
text=request.POST['text'] #It will coming from your HTML form (front end)
user=reuqest.user
obj=SomeText()
obj.user=user
obj.text=text
obj.save()
return HttpResponse("Text added!")