Reputation: 35
Hi I am trying to add the User column to know which User added the tool in the tools/model.py page
tools_name = models.CharField('Tool\'s Name', max_length=100, unique=True)
tools_project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True, blank=True, limit_choices_to=~Q(project_status=2), verbose_name='Project\'s Name')
user = models.CharField(max_length=100, editable=False)
But I want to know how to save the user that created or updated the tool ?
Upvotes: 1
Views: 1210
Reputation: 477794
Models are normally request unaware, so you should not do this. This is a task that belongs in the view. Furthermore normally you work with a ForeignKey
or a OneToOneField
or another relation. This is useful since users might eventually change their (user)name. By storing the username, your database can contain a username that no longer exists or even worse: another user now uses that username and the use got then access to the models of the previous "owner".
Your model thus looks like:
from user.conf import settings
class MyModel(models.Model):
tools_name = models.CharField('Tool\'s Name', max_length=100, unique=True)
tools_project = models.ForeignKey(
Project,
on_delete=models.DO_NOTHING,
null=True,
blank=True,
limit_choices_to=~Q(project_status=2),
verbose_name='Project\'s Name'
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
editable=False
)
You can work with a ModelForm
for example and then let the view set the user:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
@login_required
def my_view(request):
if request.method == 'POST':
form = MyModelForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('name-of-some-view')
else:
form = MyModelForm()
return render(request, 'name-of-some-template.html', {'form': form})
For the ModelAdmin
you can override the .save_model(…)
method [Django-doc]:
from django.contrib import admin
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user
super().save_model(request, obj, form, change)
Upvotes: 2