如何跟踪哪个用户正在为模型创建对象以及如何在 Django 中仅向该用户显示对象详细信息
How to track which user is creating object for a model and how to show the object details only to that user in django
我正在 Django 中做一个在线 classroom 项目,我在其中创建了一个名为 create_course 的模型,教师可以访问该模型。现在我正在尝试将其设计为创建 class 的老师,只有他在登录后才能看到这个,另一位老师不应该看到他的 classes 以及如何将学生添加到那个特定的 class 我创造了
课程模型
class course(models.Model):
course_name = models.CharField(max_length=200)
course_id = models.CharField(max_length=10)
course_sec = models.IntegerField()
classroom_id = models.CharField(max_length=50,unique=True)
created_by = models.ForeignKey(User,on_delete=models.CASCADE)
在这里,如果我在表单中使用“created_by”字段,它似乎是一个下拉菜单,每个用户都在其中显示,但我想自动保存创建对象的用户
views.py
def teacher_view(request, *args, **kwargs):
form = add_course(request.POST or None)
context = {}
if form.is_valid():
form.save()
return HttpResponse("Class Created Sucessfully")
context['add_courses'] = form
return render(request, 'teacherview.html', context)
forms.py
from django import forms
from .models import course
class add_course(forms.ModelForm):
class Meta:
model = course
fields = ('course_name', 'course_id', 'course_sec', 'classroom_id')
在您看来,使用 commit=False 停止保存表单,直到您添加 created_by 字段。
def teacher_view(request, *args, **kwargs):
form = add_course(request.POST or None)
context = {}
if form.is_valid():
course = form.save(commit=False)
course.created_by = request.user
course.save()
return HttpResponse("Class Created Sucessfully")
context['add_courses'] = form
return render(request, 'teacherview.html', context)
可以将登录用户注入form
中的.instance
的.created_by
,所以:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
@login_required
def teacher_view(request, *args, **kwargs):
if request.method == 'POST':
form = add_course(request.POST, request.FILES)
if form.is_valid():
form<strong>.instance.created_by = request.user</strong>
form.save()
return redirect(<em>'name-of-some-view'</em>)
else:
form = add_course()
return render(request, 'teacherview.html', {'add_courses': form})
Note: It is normally better to make use of the settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use the User
model [Django-doc] directly. For more information you can see the referencing the User
model section of the documentation.
Note: You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc].
Note: Usually a Form
or a ModelForm
ends with a …Form
suffix,
to avoid collisions with the name of the model, and to make it clear that we are
working with a form. Therefore it might be better to use CourseForm
instead of
add_course
.
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from course
to Course
.
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
我正在 Django 中做一个在线 classroom 项目,我在其中创建了一个名为 create_course 的模型,教师可以访问该模型。现在我正在尝试将其设计为创建 class 的老师,只有他在登录后才能看到这个,另一位老师不应该看到他的 classes 以及如何将学生添加到那个特定的 class 我创造了
课程模型
class course(models.Model):
course_name = models.CharField(max_length=200)
course_id = models.CharField(max_length=10)
course_sec = models.IntegerField()
classroom_id = models.CharField(max_length=50,unique=True)
created_by = models.ForeignKey(User,on_delete=models.CASCADE)
在这里,如果我在表单中使用“created_by”字段,它似乎是一个下拉菜单,每个用户都在其中显示,但我想自动保存创建对象的用户
views.py
def teacher_view(request, *args, **kwargs):
form = add_course(request.POST or None)
context = {}
if form.is_valid():
form.save()
return HttpResponse("Class Created Sucessfully")
context['add_courses'] = form
return render(request, 'teacherview.html', context)
forms.py
from django import forms
from .models import course
class add_course(forms.ModelForm):
class Meta:
model = course
fields = ('course_name', 'course_id', 'course_sec', 'classroom_id')
在您看来,使用 commit=False 停止保存表单,直到您添加 created_by 字段。
def teacher_view(request, *args, **kwargs):
form = add_course(request.POST or None)
context = {}
if form.is_valid():
course = form.save(commit=False)
course.created_by = request.user
course.save()
return HttpResponse("Class Created Sucessfully")
context['add_courses'] = form
return render(request, 'teacherview.html', context)
可以将登录用户注入form
中的.instance
的.created_by
,所以:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
@login_required
def teacher_view(request, *args, **kwargs):
if request.method == 'POST':
form = add_course(request.POST, request.FILES)
if form.is_valid():
form<strong>.instance.created_by = request.user</strong>
form.save()
return redirect(<em>'name-of-some-view'</em>)
else:
form = add_course()
return render(request, 'teacherview.html', {'add_courses': form})
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc].
Note: Usually a
Form
or aModelForm
ends with a…Form
suffix, to avoid collisions with the name of the model, and to make it clear that we are working with a form. Therefore it might be better to useCourseForm
instead of.add_course
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
tocourse
Course
.
Note: In case of a successful POST request, you should make a
redirect
[Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.