Hi all
I am trying to allow tasks to be allocated to users in my to do app. Users will have multiple tasks and the same task might have multiple users at the same time. Tasks do not have to be allocated to any users, so the form field can be blank.
I have a Task model with a many-to-many relationship with the User model, called “assigned”. (Separately, there is a foreign key to the User model to identify the user that created the instance. I don’t think that’s problematic, here):
class Task(models.Model):
"""
Stores a single task, related to :model:`core.User` and model: `core.Space`.
"""
...
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="creator", null=False, blank=False
) # Required, links to core.User
text = models.CharField( # Required
null=False,
max_length=250,
validators=[
MaxLengthValidator(
limit_value=249, message="Tasks can only have 250 characters"
)
],
blank=False,
verbose_name="Task",
)
assigned = models.ManyToManyField(
User, blank=True, related_name="assignee"
# Default is the user creating the task
)
...
It works, and if a one or more users is associated with a task in the form, then the junction table in the database is updated, as you would expect.
What I am looking to do is ensure that when a task is created the form suggests the current user be assigned the task, by default. This default could be changed in the browser - including not assigning the task to any users.
I’ve tried:
- using the form init method to set a value for
assigned
. This didn’t work because the new instance of the Task hadn’t been saved, so it couldn’t add it to the junction table; - updating cleaned_data in the form_valid method in the view. Also didn’t work because, again, the new instance of the Task hadn’t been saved, so it couldn’t add it to the junction table;
- overriding the
save
method on the Task model, which I can’t get to work, but also isn’t really what I’m trying to do. I’d like the default to be a prompt to the user through the view/form, rather than embedded in the logic of the database.
def save(self, *args, **kwargs):
print("Creator:", self.creator)
super().save(*args, **kwargs)
# If the value of 'assigned' is empty, then set it to 'creator' (ie. the current user)
if not self.assigned.all():
print ("assigned is empty")
# print(type(self.assigned))
self.assigned.add(self.creator)
print("Assigned is now:", self.assigned)
Sorry to add to the litany of many-to-many related questions, but I can’t find a way through this one. I’ve read so many conflicting posts and bits of documentation that I am now even more confused and now completely stuck.
Thanks in advance