【发布时间】:2020-05-19 13:34:45
【问题描述】:
总结:我正在尝试创建一个工作委员会网站。我有一个dashboard 视图,它返回所有job 对象并将它们显示在模板中。用户可以在此处导航以查看他们的帖子,并且在创建新帖子、编辑帖子或删除帖子后,用户也会被重定向到此处。我希望能够根据用户进入此页面的情况提醒用户“您的帖子已成功创建/编辑/删除”,但不确定最佳方式。下面是我如何实现提醒用户已创建帖子的功能,但我认为这不是最好的方法。
我创建的第一个视图是post_job 视图,用户可以在其中创建新职位。为了标记工作是否是新的,我想在 Job 模型中添加一个布尔字段:
class Job(models.model):
#...
new = models.BooleanField(default = True) # post is new by default, set to False later
然后在dashboard 中执行此操作:
@login_required
def dashboard(request):
jobs = Job.objects.all()
new_job = False # set to true if there is a new job ( would only be the case if the user got directed to this view after posting a job)
for job in jobs: # loop through jobs to see if any have new=True
if job.new:
new_job = True
job.new = False # set to false so it's not considered new next time dashboard is loaded
job.save()
return render(request, 'job/dashboard.html', {'jobs':jobs, 'new_job': new_job})
在dashboard.html中:
{% if new_job %}
<p>Your job was posted successfully</p>
{% endif %}
仅当用户刚刚创建新帖子时,这才有效并成功提醒用户。但是,我觉得必须有一种更好的方法来实现此功能,然后将 edited 字段添加到 Job 模型并且正要说 deleted 字段但我猜该对象将不再存在。无论如何,如果您能提出任何建议来实现这一目标,感谢您的帮助。不确定这是否是正确的术语,但似乎会有一个标记系统在创建/编辑/更新对象时发出警报,因为这相当普遍?
编辑:重定向到dashboard 视图时是否可以传递其他变量?例如这里是post_job 视图:
def post_job(request):
if request.method == 'POST':
form = JobForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.business= Business.objects.get(user=request.user)
instance.save()
return redirect('dashboard') # is there a way to tell the dashboard view the post_job view sent the user?
else:
form = JobForm()
return render(request, 'job/post_job.html', {'section': 'dashboard', 'form':form})
如果有的话,我可以为 edit 和 delete 视图执行此操作。
【问题讨论】:
标签: django django-models django-templates django-views