Search code examples
htmldjangodjango-generic-views

Get url argument to process generic views


I would like to write a one-template view, which depending on the url path will show different field of the model. So for instance if path is

http://127.0.0.1:8000/trip/2/1/

I will get second trip from my db (that works), and 1 should give (as html is written) a description field. I don't know how to process this to context_processor in my view. Do you have any ideas?

views.py

class TripDescriptionCreate(LoginRequiredMixin, UpdateView):

    model = Trip
    template_name = 'tripplanner/trip_arguments.html'
    fields = ["description", "city", "country", "climate", "currency", "food", "cost", "comment", "accomodation",
    "car", "flight", "visa", "insurance", "remarks"]
    context_object_name = 'trips'
    success_url = '/'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

trip_arguments.html

 <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">{{ trips.tripName }}</legend>
                    {% if field_id == 1 %}
                        {{ form.description|as_crispy_field }}
                    {% elif field_id == 2 %}
                        {{ form.city|as_crispy_field }}
                    {% endif %}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Update</button>
            </div>
        </form>

urls.py

path('trip/<int:pk>/<int:field_id>', TripDescriptionCreate.as_view(), name='trip-fullfill'),

Solution

  • So I came up with this idea. In my html I added these lines:

    {% url 'trip-fullfill-description' pk=trip.pk as description_url %}
                    {% url 'trip-fullfill-city' pk=trip.pk as city_url %}
    
    {% if request.get_full_path == description_url %}
                        {{ form.description|as_crispy_field }}
                    {% elif request.get_full_path == city_url %}
                        {{ form.city|as_crispy_field }}