Home > database >  Django Ajax form submission, how to get a specific model field from a form
Django Ajax form submission, how to get a specific model field from a form

Time:08-18

For my project I need to be able to submit a form through ajax without refreshing the page. I have a model called Post with three fields: animal, image, and description.

here is a picture of my model

class Post(models.Model):
BISON = 'Bison'
WOLF = 'Wolf'
ELK = 'Elk'
BLACKBEAR = 'Black Bear'
GRIZZLY = 'Grizzly Bear'
MOOSE = 'Moose'
MOUNTAINLION = 'Mountain Lion'
COYOTE = 'Coyote'
PRONGHORN = 'Pronghorn'
BIGHORNSHEEP = 'Bighorn Sheep'
BALDEAGLE = 'Bald Eagle'
BOBCAT = 'Bobcat'
REDFOX = 'Red Fox'
TRUMPETERSWAN = 'Trumpeter Swan'
YELLOWBELLIEDMARMOT = 'Yellow-bellied Marmot'
RIVEROTTER = 'River Otter'
LYNX = 'Lynx'
SHREW = 'Shrew'
PIKA = 'Pika'
SQUIRREL = 'Squirrel'
MULEDEER = 'Mule Deer'
SANDHILLCRANE = 'Sandhill Crane'
FLYINGSQUIRREL = 'Flying Squirrel'
UINTAGROUNDSQUIRREL = 'Uinta Ground Squirrel'
MONTANEVOLE = 'Montane Vole'
EASTERNMEADOWVOLE = 'Eastern Meadow Vole'
BUSHYTAILEDWOODRAT = 'Bushy-tailed Woodrat'
CHIPMUNK = 'Chipmunk'
UINTACHIPMUNK = 'Uinta Chipmunk'
WHITETAILEDJACKRABBIT = 'White-tailed Jackrabbit'
BEAVER = 'Beaver'
AMERICANMARTEN = 'American Marten'
MOUNTAINCHICKADEE = 'Mountain Chickadee'
BOREALCHORUSFROG = 'Boreal Chorus Frog'
CUTTHROATTROUT = 'Cutthroat Trout'
GREATHORNEDOWL = 'Great Horned Owl'
SNOWSHOEHARE = 'Snowshoe Hare'
ROCKYMOUNTAINELK = 'Rocky Mountain Elk'
NORTHWESTERNWOLF = 'Northwestern Wolf'
BLACKFOOTEDFERRET = 'Black-footed Ferret'
WOLVERINE = 'Wolverine'
ANIMALS = [
    (BISON, ('Bison')),
    (WOLF, ('Wolf')),
    (ELK, ('Elk')),
    (BLACKBEAR, ('Black Bear')),
    (GRIZZLY, ('Grizzly Bear')),
    (MOOSE, ('Moose')),
    (MOUNTAINLION, ('Mountain Lion')),
    (COYOTE, ('Coyote')),
    (PRONGHORN, ('Pronghorn')),
    (BIGHORNSHEEP, ('Bighorn Sheep')),
    (BALDEAGLE, ('Bald Eagle')),
    (BOBCAT, ('Bobcat')),
    (REDFOX, ('Red Fox')),
    (TRUMPETERSWAN, ('Trumpeter Swan')),
    (YELLOWBELLIEDMARMOT, ('Yellow-bellied Marmot')),
    (RIVEROTTER, ('River Otter')),
    (LYNX, ('Lynx')),
    (SHREW, ('Shrew')),
    (PIKA, ('Pika')),
    (SQUIRREL, ('Squirrel')),
    (MULEDEER, ('Mule Deer')),
    (SANDHILLCRANE, ('Sandhill Crane')),
    (FLYINGSQUIRREL, ('Flying Squirrel')),
    (UINTAGROUNDSQUIRREL, ('Uinta Ground Squirrel')),
    (MONTANEVOLE, ('Montane Vole')),
    (EASTERNMEADOWVOLE, ('Eastern Meadow Vole')),
    (BUSHYTAILEDWOODRAT, ('Bushy-tailed Woodrat')),
    (CHIPMUNK, ('Chipmunk')),
    (UINTACHIPMUNK, ('Uinta Chipmunk')),
    (WHITETAILEDJACKRABBIT, ('White-tailed Jackrabbit')),
    (BEAVER, ('Beaver')),
    (AMERICANMARTEN, ('American Marten')),
    (MOUNTAINCHICKADEE, ('Mountain Chickadee')),
    (BOREALCHORUSFROG, ('Boreal Chorus Frog')),
    (CUTTHROATTROUT, ('Cutthroat Trout')),
    (GREATHORNEDOWL, ('Great Horned Owl')),
    (SNOWSHOEHARE, ('Snowshoe Hare')),
    (ROCKYMOUNTAINELK, ('Rocky Mountain Elk')),
    (NORTHWESTERNWOLF, ('Northwestern Wolf')),
    (BLACKFOOTEDFERRET, ('Black-footed Ferret')),
    (WOLVERINE, ('Wolverine'))
]

animal = models.CharField(max_length=32, choices=ANIMALS, default=BISON)
image = models.ImageField(upload_to='images', default='static/images/yellowstonelake.jpg')
description = models.TextField(null=True, blank=True)

def __str__(self):
    return self.animal

here is a picture of my form.py

class PostForm(ModelForm):
class Meta:
    model = Post
    fields = '__all__'

here is a picture of my views page

def homePage(request):
form = PostForm()
if request.method == 'POST':
    animalType=request.POST['animal']
    new_post = Post(animal=animalType)
    new_post.save()

context = {'form': form}
return render(request, 'home.html', context)

I believe the problem lies within the javascript I am using to submit my form without refreshing the page. I am able to submit by form successfully, but the data:{...} section within my <script type="text/javascript>... section has to be incorrect? I am referring to line 651 in the following image.

ajax javascript img

 <script type="text/javascript">
        $(document).on('submit','#post-form',function(e){
            e.preventDefault();
            $.ajax({
                type:'POST',
                url:'',
                data:
                {
                    animal:$("form").val(),
           
                    csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                },
                success:function(data){
                    alert("success!")
                    }
                })
            });
        </script>

I need this value to be something other than just:

animal:$("form).val()

since whenever I submit this and go to the backend admin site of my project, I am unable to edit my posts and they are just empty objects within my data base. Ideally I would like this value to be the name of the animal the user selected. I have tried using values such as $("form.model.animal").val() or $("form").val(animal) but i am having no luck.

This is what my back end admin site looks like with a few "successful" submission. Please let me know I you can see where I am making a mistake and how to fix this annoying issue! Thanks!

Admin Posts Page

Form field Template:

const postpopup = new mapboxgl.Popup({ offset: [0, -15] })
                    .setLngLat([lt, lg])
                    .setHTML(
                    `<h1>Yellowmap :) Post Forum</h1>
                        <div style="margin-left: 40px;">
                            <form id="post-form">
                            {% csrf_token %}
                            {{form}}
                            <input type="submit"/>
                            </form>
                            <p></p>
                        </div>`
                    )

CodePudding user response:

Everything in your code is alright, you just have to change your AJAX code a little bit. and your views.py file.

AJAX

    $(document).on('submit', '#post-form', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: "{% url 'insert_form' %}",
            data:
                {
                    animal: $("#id_animal").val(),
                    image: $("#id_image").val(),
                    description: $("#id_description").val(),
                    csrfmiddlewaretoken: '{{ csrf_token }}',
                },
            success: function () {
                alert("success!")
            }
        })
    });

views.py

def homePage(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('')

    context = {'form': form}
    return render(request, '.html', context)

  • Related