Answer the question
In order to leave comments, you need to log in
What to do if when you change the class, the form changes places and only one works?
I have such a problem, I created two classes WatchingAnime and Comment, the first for adding to the 'watch' list by button, the second for adding comments, these two classes are inherited from FormMixin, then I inherited these two classes to my main class where information about the anime is located , and when these classes are swapped, only the form that stands before works, what needs to be done to make two work at once?
views:
Comment class:
class Comment(FormMixin):
form_class = CommentsForm
def post(self, request, *args, **kwargs):
comment_form = self.get_form()
if comment_form.is_valid:
return self.form_valid(comment_form)
else:
return self.form_invalid(comment_form)
def form_valid(self, comment_form):
self.object = comment_form.save(commit=False)
self.object.animes = self.get_object()
self.object.author = self.request.user
if self.request.POST.get("parent_id", None):
parent_id = int(self.request.POST.get('parent_id'))
parent_obj = Comments.objects.get(id=parent_id)
self.object.parent = parent_obj
self.object.save()
return super().form_valid(comment_form)
def get_context_data(self, **kwargs):
"""Insert the form into the context dict."""
if 'form' not in kwargs:
kwargs['comment_form'] = self.get_form()
return super().get_context_data(**kwargs)
class WatchingAnime(FormMixin):
form_class = ProfileWatchingForm
def anime_add(self, request, *args, **kwargs):
form_anime = self.get_form()
if form_anime.is_valid:
return self.form_valid(form_anime)
else:
return self.form_invalid(form_anime)
def form_valid(self, form_anime):
self.object = form_anime.save(commit=False)
prof = Profile.objects.get(id=self.request.user.id)
if self.request.POST.get('add_anime', None):
anime_id = int(self.request.POST.get('add_anime'))
anime_obj = Anime.objects.get(id=anime_id)
if Anime.objects.get(id=anime_id) in prof.watching.all():
self.object.watching = prof.watching.remove(anime_obj)
else:
self.object.watching = prof.watching.add(anime_obj)
self.object.save()
return super().form_valid(form_anime)
class AnimeDetailView(DetailView, WatchingAnime, Comment):
model = Anime
slug_field = 'url'
template_name = 'anime/anime_detail.html'
context_object_name = 'anime_detail'
def get_success_url(self, **kwargs):
return reverse_lazy('anime:anime_detail', kwargs={'slug': self.get_object().url})
def get_context_data(self, *args,**kwargs):
context = super().get_context_data(*args, **kwargs)
context['comments'] = Comments.objects.filter(parent__isnull=True)
return context
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question