如果他们已经在Updateview
模型中创建了记录,我试图将登录用户重定向到Createview
而不是organizations
。
我的organizations
与我的users
模型具有1:1的关系。
如果相关记录存在,我目前可以使用Updateview
方法返回get
,但是Url不会重定向到/update
我的代码:
urls.py
urlpatterns = [
path("add/", view=organization_add_view, name="add"),
path("update/", view=organization_update_view, name="update"),
path("<int:id>/<str:slug>", view=organization_detail_view, name="detail"),
]
models.py
class Organization(TimeStampedModel):
name = CharField(_("Organization Name"), blank=False, max_length=255, unique=True)
slug = AutoSlugField(_('slug'), max_length=100, unique=False, populate_from=('name',))
user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE, db_index=True)
def __str__(self):
return self.name
views.py
class OrganizationDetailView(DetailView):
model = Organization
slug_field = "slug"
slug_url_kwarg = "slug"
organization_detail_view = OrganizationDetailView.as_view()
class OrganizationAddView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = Organization
form_class = OrganizationForm
success_message = "%(name)s was created successfully"
def form_valid(self, form):
obj = form.save(commit=False)
obj.user = self.request.user
obj.save()
return self.get_success_url()
def get_form_kwargs(self):
kwargs = super(OrganizationAddView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
def get_initial(self):
return {
'user': self.request.user,
'is_update': False
}
def get(self, *args, **kwargs):
if self.model.objects.filter(user=self.request.user).exists():
return redirect("organizations:update")
else:
return super(OrganizationAddView, self).get(*args, **kwargs)
def get_success_url(self):
return reverse("organizations:list")
organization_add_view = OrganizationAddView.as_view()
class OrganizationUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = Organization
form_class = OrganizationForm
success_message = 'Organization updated successfully.'
def get_object(self, queryset=None):
obj = self.model.objects.get(user=self.request.user)
return obj
def get_initial(self):
return {
'is_update': True
}
def get(self, *args, **kwargs):
if self.model.objects.filter(user=self.request.user).exists():
return super().get(*args, **kwargs)
else:
return redirect("organizations:add")
def get_form_kwargs(self):
kwargs = super(OrganizationUpdateView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
def get_success_url(self):
return reverse("organizations:update")
organization_update_view = OrganizationUpdateView.as_view()
forms.py
class OrganizationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(OrganizationForm, self).__init__(*args, **kwargs)
organization = kwargs.get('instance')
user = self.request.user
self.helper = FormHelper(self)
if organization:
if organization.email is None:
self.initial['email'] = self.request.user.email
elif user.email:
self.initial['email'] = user.email
self.helper.form_method = 'post'
submit_btn_text = 'Continue'
if kwargs.get('initial')['is_update']:
submit_btn_text = 'Update'
self.helper.add_input(Submit('submit', submit_btn_text))
class Meta:
model = Organization
widgets = {
'description': forms.Textarea(attrs={'rows': 10, 'cols': 60}),
# 'logo': forms.ImageField()
}
fields = '__all__'
exclude = ['created', 'expires', 'is_sponsor', 'view_count', 'user']
答案 0 :(得分:1)
因此,这里的问题是您应该return
对其进行redirect
更新视图。返回指向更新URL的HttpResponseRedirect将为您提供所需的确切信息。只需确保将相关组织的pk
传递到重定向网址即可。
答案 1 :(得分:1)
您应该重定向而不是直接调用视图。
if self.model.objects.get(user=self.request.user):
return redirect("organisations:update")
else:
return super().get(*args, **kwargs)