how to use if in django class based view - python

i want to use if and i need to have a variable and that variable needs kwords
class ResetPassword(FormView):
template_name = 'reset_password.html'
form_class = ResetPasswordForm
def get_context_data(self, **kwargs):
context = super(ResetPassword, self).get_context_data(**kwargs)
context['uuid'] = kwargs.get('uuid')
context['base64'] = kwargs.get('base64')
return context
if (get_context_data['context']['uuid'] and get_context_data['context']['base64']) == (url_uuid and url_base64):
def form_valid(self, form):
user = User.objects.get(id= self.request.user.id)
user.set_password(form.cleaned_data['password'])
user.save()
return redirect('/login')

Related

Update context of FormView only in certain condition

I have a code in my FormView in Django:
class SearchView(LoginRequiredMixin, FormView):
template_name = "dic_records/search_form.html"
form_class = KokyakuForm
success_url = 'search'
fetched_data = []
def form_valid(self, form):
print(form.cleaned_data)
kokyaku_instance = FetchKokyaku(form.cleaned_data['name_search'])
err_check = kokyaku_instance.connect()
kokyaku_instance.get_data()
if err_check is False:
messages.error(self.request, "データを出力できませんでした")
return super(SearchView, self).form_valid(form)
kokyaku_list = list(kokyaku_instance.get_data())
if len(kokyaku_list) == 0:
messages.error(self.request, "検索のデータを見つけられませんでした")
return super(SearchView, self).form_valid(form)
self.fetched_data = kokyaku_list
return super(SearchView, self).form_valid(form)
def get_context_data(self, **kwargs):
"""Use this to add extra context."""
context = super(SearchView, self).get_context_data(**kwargs)
context['list'] = self.fetched_data
return context
And I would like to provide to template a list of values kokyaku_list from context variable, but only if my form is valid and data are fetched from kokyaku_instance.get_data().
The code above wont pass values

Django generic view initial value in form

i want to have default value in my form which should be current user's choice. For example, user chooses to give 5 for a movie and he should see 5 in form until he changes it.
views.py
class MovieDetailView(FormMixin, DetailView):
model = Movie
template_name = 'main/detail_movie.html'
context_object_name = 'movie'
form_class = RateForm
def get_context_data(self, **kwargs):
context = super(MovieDetailView, self).get_context_data(**kwargs)
context['form'] = RateForm(initial={'movie': self.object})
context['my_rate'] = Rate.objects.filter(
sender=self.request.user,
movie=self.get_object()).first()
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if request.method == 'POST':
if form.is_valid():
new_rate, _ = Rate.objects.update_or_create(
sender=self.request.user,
movie=self.object,
defaults={'choice': form.cleaned_data['choice']}
)
return JsonResponse({'rate': model_to_dict(new_rate)}, status=200)
else:
return self.form_invalid(form)
def get_success_url(self):
return reverse('detail_movie', kwargs={'slug': self.object.slug})
I was trying get_initial method but it still gives me '---' in form as default.
def get_initial(self):
return {'choice': Rate.objects.filter(movie=self.object, sender=self.request.user).first().choice }
Even something like this doesn't work
def get_initial(self):
return {'choice': 1 }
If you want to use FormMixin and get_initial method you need to use get_form method in get_context_data
class MovieDetailView(FormMixin, DetailView):
model = Movie
template_name = 'main/detail_movie.html'
context_object_name = 'movie'
form_class = RateForm
def get_initial(self):
initial = super(MovieDetailView, self).get_initial()
initial['movie'] = self.object # selected movie
rate = Rate.objects.filter( # attempt to get rate
movie=self.object,
sender=self.request.user
).first()
if rate is not None: # set rate choice only if it has been done before
initial['choice'] = rate.choice
return initial
def get_context_data(self, **kwargs):
context = super(MovieDetailView, self).get_context_data(**kwargs)
context['form'] = self.get_form() # use from mixin instead manual init
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if request.method == 'POST':
if form.is_valid():
new_rate, _ = Rate.objects.update_or_create(
sender=self.request.user,
movie=self.object,
defaults={'choice': form.cleaned_data['choice']}
)
return JsonResponse({'rate': model_to_dict(new_rate)}, status=200)
else:
return self.form_invalid(form)
def get_success_url(self):
return reverse('detail_movie', kwargs={'slug': self.object.slug})
Ok, i just had to input
'choice': Rate.objects.filter(movie=self.object, sender=self.request.user).first().choice
to my context['form'] where i already had initial:
def get_context_data(self, **kwargs):
context = super(MovieDetailView, self).get_context_data(**kwargs)
context['form'] = RateForm(
initial={
'movie': self.object,
'choice': Rate.objects.filter(movie=self.object, sender=self.request.user).first().choice
})
context['my_rate'] = Rate.objects.filter(
sender=self.request.user,
movie=self.get_object()).first()
return context
Put this in your form.
form = RateForm(initial={'choice': 1})

How to pass argument from previous View to a Form?

Im trying to pass the "test" argument from this View to a Form:
class ListCreateFormView(CreateView):
template_name = 'armybuilder_list_create.html'
model = List
form_class = CreateListForm
def form_valid(self, form):
form.instance.author = self.request.user
self.test = Faction.objects.get(title="Blood Angels")
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('add_unit_to_list', kwargs={'pk': self.object.pk, 'test': self.test.id})
To this View and Form:
class AddUnitsToListFormView(LoginRequiredMixin,CreateView):
model = SoldierToList
form_class = SoldierToListForm
template_name = 'armybuilder_add_unit_to_list.html'
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.list_id = self.kwargs['pk']
return super().form_valid(form)
class SoldierToListForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# factions_obj = Faction.objects.get(pk=my_test)
self.fields['soldier'].queryset = Soldier.objects.filter(factions=4)
class Meta:
model = SoldierToList
fields = ('soldier',)
My urls:
urlpatterns = [
path('list/create', ListCreateFormView.as_view(), name='create_list'),
path('list/own/<int:pk>/<int:test>/addunit', AddUnitsToListFormView.as_view(), name='add_unit_to_list'),
]
Im hardcoding the value 4 in my form but I would like to use the argument test that I defined in the previous View ListCreateFormView, can you please tell me how to do it ?
Thanks

How can i get the pk from a cloned model instance in form_valid to use in get_success_url in an UpdateView?

class DomainRegistrationItemUpdateView(UpdateView):
model = DomainRegistrationItem
form_class = DomainAddYearsForm
template_name = "add_years.html"
def get_context_data(self, *args, **kwargs):
context = super(DomainRegistrationItemUpdateView,
self).get_context_data(**kwargs)
# tld_ppy Top Level Domain Price Per Year
context['tld_ppy'] = TLD.objects.get(
name='.%s' % (self.kwargs['domain_name'].split('.')[1])).yearly_price
return context
def get_object(self, queryset=None):
return DomainRegistrationItem.objects.get(domain=self.kwargs['domain_name'], purchased=True)
def get_success_url(self):
split_dn = self.kwargs['domain_name'].split('.')
namespace = split_dn[0]
sld = split_dn[1]
return reverse("domain_registraiton_item_detail", kwargs={
"pk": self.kwargs['pk'],
'namespace': namespace,
'second_level_domain': sld})
def form_valid(self, form):
f = form.save(commit=False)
working_dri = DomainRegistrationItem.objects.get(domain=self.kwargs['domain_name'])
working_dri.pk = None
working_dri.save()
working_dri.purchased = False
working_dri.years = f.years
f.save()
return super(DomainRegistrationItemUpdateView, self).form_valid(form)
The working_dri code is code that clones a DomainRegistrationItem under consideration by the view.
I want to get the pk from working_dri to usee in get_success_url. How can I do this? Thanks in advance for any and all help.
An UpdateView stores the object it saves to self.object, as we can see in the source code:
def form_valid(self, form):
"""If the form is valid, save the associated model."""
self.object = form.save()
return super().form_valid(form)
so we can make use of:
class DomainRegistrationItemUpdateView(UpdateView):
model = DomainRegistrationItem
form_class = DomainAddYearsForm
template_name = "add_years.html"
# …
def get_success_url(self):
split_dn = self.kwargs['domain_name'].split('.')
namespace = split_dn[0]
sld = split_dn[1]
return reverse("domain_registraiton_item_detail", kwargs={
"pk": self.object.pk,
'namespace': namespace,
'second_level_domain': sld})
def form_valid(self, form):
form.instance.pk = None
form.instance.purchased = False
form.instance.years = f.years
return super(DomainRegistrationItemUpdateView, self).form_valid(form)

in django CreateView, how do I add field and send that field as a context to template?

I know this is very beginner question but I still don't get it even after I read https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/
so I have this createView right...
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'main/add_post.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# any manual settings go here
self.object.moderator = self.request.user
self.object.image = extract(self.object.url)
self.object.thumbnail = extractt(self.object.content)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostCreateView, self).dispatch(request, *args, **kwargs)
and in add_post.html I want to use
hotCat = Category.objects.get_hotCat()
how do I use that hotCat in add_post.html?
You add variables into the context by overriding the get_context_data() method.
def get_context_data(self, **kwargs):
ctx = super(PostCreateView, self).get_context_data(**kwargs)
ctx['hotCat'] = Category.objects.get_hotCat()
return ctx

Categories

Resources