How to save Request URL from inspector in Django Model

I’m trying to implement a web application in which the user fills out a form and separately there is a form that the user fills out and selects a route on the map.
I use Mapbox for this. In HTML it looks like I have a separate form in the form element and a separate map in the div element. When I built a route in the inspector, I find a processed request with the GET method and the Request URL. This page is NOT UPDATED at this time. It’s reall time.


My question is how to save this Request URL together with the form, or at least separately? How do I even save this URL request to the Django Model.

Part from my model.py:

class Route(models.Model):
    route_name = models.CharField(max_length=50)
    lvl = models.IntegerField(default=0)
    about = models.TextField(max_length=1500)
    total_distance = models.IntegerField(default=0)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    def __str__(self):
        return self.route_name
    def __str__(self):
        return self.about

class RoutesURL(models.Model):
    url = models.CharField(max_length=1000)
    def __str__(self):
        return self.url

And I tried to make something this in my views.py:

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404, get_list_or_404

from .forms import RouteForm

from .models import Route, RoutesURL

def getForm(request):
    form = RouteForm()
    routeURL = RoutesURL
    if request.method == 'POST':
        form = RouteForm(request.POST)
        if form.is_valid():
            form.save()
            routeURL.objects.create(url=request.get_full_path_info())
            return HttpResponseRedirect('example_page')
    return render(request, 'routes_form/route_form.html', {'form': form})

It would be helpful if you posted the forms and templates associated with this. It’s hard to tell what you’re actually getting submitted to you.

Also, is it really necessary to create a separate model for the RoutesURL? Or should the url be another field in the Route model?

Thank you for your feedback. Sorry for not adding all the code.

About why I have a separate table for urls, and why not add this information to the column: this is just a test case, it’s not a problem to update the old “Route” table and add a column there. This is what I plan to do when I figure out how to get the url. I realized that I can get the route that the user builds and information from it thanks to requests in the JavaScript script that creates this route. After it, for example, add fetch() with a POST method. But now I have a question, how can I accept this request in Django along with the form and save it to the database.

Here is my forms.py:

from django import forms
from .models import Route


class RouteForm(forms.ModelForm):
    class Meta:
        model = Route
        fields = ['route_name', 'lvl', 'about',
                  'total_distance', 'country', 'state', 'city']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['route_name'].widget.attrs.update(
            {'class': 'form-control', 'placeholder': 'Give a short name to the route'})
        self.fields['lvl'].widget.attrs.update(
            {'class': 'slider col-md-10', 'id':'customRange1','min': '1', 'max': '10'})
        self.fields['lvl'].widget.input_type = 'range'
        self.fields['about'].widget.attrs.update({'class': 'form-control', 'rows':'2'})
        self.fields['total_distance'].widget.attrs.update(
            {'class': 'form-control'})
        self.fields['country'].widget.attrs.update(
            {'class': 'form-select', 'placeholder': 'Choose country'})
        self.fields['state'].widget.attrs.update({'class': 'form-select'})
        self.fields['city'].widget.attrs.update({'class': 'form-select'})

And here are my template and approximately how it looks (maybe this is very bad, but I will refactor everything in the future):

<body>

    <div class="container-fluid">
        <div class="row">
            <nav id="sidebar" class="col-md-3 col-lg-3 d-md-block bg-light sidebar collapse nopadding"
                style="padding-right: 0">
                <div class="position-sticky pt-3 sidebar-sticky">
                    <form method="post" class="nav flex-column">
                        {% csrf_token %}
                        {{ form.media.js }}

                        <div id="name_form" class="col-sm-9">
                            <label for="firstName" class="form-label">Route name</label>
                            {{ form.route_name }}
                        </div>
                        <div id="name_form" class="col-sm-10">
                            <label for="about" class="form-label">Tell about</label>
                            {{ form.about }}
                        </div>
                        <div>

                            <div class="col-md-10">
                                <label for="Country">Country</label>
                                {{form.country}}
                                </select>
                            </div>
                            <div class="col-md-10">
                                <label for="State">State</label>
                                {{form.state}}
                            </div>
                            <div class="col-md-10">
                                <label for="City">City</label>
                                {{form.city}}
                            </div>

                            <div id="dificult_form" class="col-md-12">
                                <label for="customRange1">Dificult level</label>
                                <br>
                                {{ form.lvl }}
                            </div>
                            <div id="distance_form" class="col-md-10">
                                <label for="total_distance">Total distance</label>
                                {{ form.total_distance }}
                            </div>
                            <hr class="my-4">

                            <button type="submit" value="" class="btn btn-outline-primary me-2">Send</button>


                    </form>
                </div>
            </nav>

            <div class="col-md-9 ms-sm-auto col-lg-9 px-md-4">
                <div id="map" class="#"></div>
            </div>
        </div>
    </div>
<!-- Below is the script for the Mapbox map. I don't add it because there is a lot of it. -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
        crossorigin="anonymous"></script>
</body>

A couple different thoughts here. I’m still not sure what level of integration is available with this other JavaScript module on your page, so I’m not sure how any of these may apply - some experimentation may be necessary.

  • Create another field on your form for that URL. Make it hidden. At some event (a button on your other JavaScript module? triggered by your submit button?) copy the URL to that field.

  • Have your submit button make an AJAX-style call to submit the form. Include any data in the response that may be needed for the submission of the URL (e.g. foreign keys to any related tables), then submit the URL to a different view designed to save that URL.

I followed your advice, but in the end I got the result without the help of an ajax request. In the JavaScript script itself, which forms the Request URL when creating a route on the map, I forcibly passed a string with the request to the URL form element using the DOM. It looks like this:

Now the URL is not hidden, but in the future I will hide it. Also followed your advice and added the URL column to the existing table. My code above is quite hard to read, but it’s a rough draft because in a real project, everything is divided into blocks:: {% extends “base.html” %}{% block content %}, {% endblock content %}. Therefore, it was difficult to show the full code.

Thank you very much for helping me solve my problem!