I was going through "Django for Beginners", there is a project that make posts with title, author and body fields, u can add posts via admin where in author field u choose either -- or the admin itself, what I'd like to do is if this field is not edited then then its value would be a string that i can pass (i. e. in that case 'anon') . I've found a way to make a default for ForeignKey but without models.User so how to do it in that case?
from django.db import models
from django.urls import reverse
def anon():
return 'User.username="Anon"'
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
"auth.User",
on_delete=models.CASCADE, default=anon
)
body = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("post_detail", kwargs={"pk": self.pk})
Firstly I've tried to plainly type in author = models.ForeignKey("auth.User", on_delete=models.CASCADE, default='anon')
.
Then to make a function that would return the desired string, then looked up models.User fields and found username field, tried to return it in anon() but only got SyntaxError: expression cannot contain assignment, perhaps you meant "=="? when entered makemigrations command