在这里,我有两个独立的模型' User'模特和'活动'模型。事件模型与用户模式相关。现在我想要做的是,当用户填写事件表单并提交时,应该仅针对该用户创建该事件记录。
views.py
class EventCreationForm(View):
template_eventcreationform = 'eventcreationform.html'
form_class = EventForm
def get(self, request):
form = self.form_class(None)
return render(request, self.template_eventcreationform, {'form': form})
def post(self, request):
# data is here
form = self.form_class(request.POST)
if form.is_valid():
event = form.save(commit=False)
user = User.objects.get(
#######################################################
##### currently logged user #####
### what should i put here to get current user? ###
#######################################################
)
form.user = user.email
event_name = form.cleaned_data.get('event_name')
event_date_time = form.cleaned_data.get('event_date_time')
event_address = form.cleaned_data.get('address')
event.save()
message = 'Event added'
return render(request, 'base.html', {'message': message})
else:
message = 'Invalid form data, try again'
form = self.form_class(None)
return render(request, self.template_eventcreationform, {'message': message, 'form': form})
答案 0 :(得分:1)
首先,您可能希望使用LoginRequiredMixin
,以便只有已登录的用户才能访问该视图。
from django.contrib.auth.mixins import LoginRequiredMixin
class EventCreationForm(LoginRequiredMixin, View):
您可以使用self.request.user
访问登录的用户。
if form.is_valid():
event = form.save(commit=False)
event.user = self.request.user
event.save()
message = 'Event added'
return redirect('/success-url/')
请注意,保存事件后重定向最好,以防止重复提交表单。
请注意,您正在复制FormView
或CreateView
的许多功能。如果您使用这些代码,则无需编写尽可能多的代码。
class EventCreationForm(LoginRequiredMixin, CreateView):
template_name = 'eventcreationform.html'
form_class = EventForm
success_url = '/success-url/' # form_valid() will redirect here
def form_valid(self, form):
form.instance.user = self.request.user
return super(EventCreationForm, self).form_valid(form)