V
V
Vitaly Ananiev2022-01-03 19:05:50
Django
Vitaly Ananiev, 2022-01-03 19:05:50

How to display the form in the Detailview so that the form fields display the information associated with the slug?

url.py

urlpatterns = [
    path('', BaseView.as_view(), name='base'),
    path('sell_game_currency/<int:slug>', SellAvailabilityDetail.as_view(), name='sell_game_currency'),
]

views.py
class SellAvailabilityDetail(FormView, DetailView):
    model = Games
    template_name = 'Pay/sell_availability_detail.html'
    slug_field = "id_num"
    context_object_name = 'games'
    form_class = AddAvailabilityForm
    success_url = reverse_lazy('base')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'] = AddAvailabilityForm
        return context

    def form_valid(self, form):
        Availability.objects.create(**form.cleaned_data)
        return redirect('base')

models.py
class Games(models.Model):
    name = models.CharField(max_length=255, verbose_name='Наиминование игры')
    id_num = models.PositiveIntegerField(default=0, verbose_name='id-номер')

    def sell_game_currency_url(self):
        return reverse('sell_game_currency', kwargs={'slug': self.id_num})

    def __str__(self):
        return self.name

forms.py
class AddAvailabilityForm(forms.Form):
    games = forms.ModelChoiceField(queryset=Games.objects.all(), label="игра")

sell_availability_detail.html
<form action="{% url 'sell_game_currency' slug=games.id_num %}" method="post">
    {% csrf_token %}
    {% for f in form %}
    <p><label class="">{{f.label}}: </label>{{ f }}</p>
    <div class="">{{ f.errors }}</div>
    {% endfor %}
    <button type="submit">Добавить</button>
</form>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question