简体   繁体   中英

Django stops updating data to mysql after page refresh

I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?

Stuff for reference:

views.py

from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages

def insertToDB(request):
    if request.method == "POST":

        if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
            post = dbInsert()
            post.uname = request.POST.get('uname')
            post.email = request.POST.get('email')
            post.message = request.POST.get('message')
            post.save()
            messages.success(request, "Message sent successfully.")
        return render(request, "contact.html")

    else:
        return render(request, "contact.html")

models.py

from django.db import models

class dbInsert(models.Model):
    uname = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.TextField()
    class Meta:
        db_table = "contactrequest"

urls.py

"""
websiteDB URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index

urlpatterns = [
   #path('admin/', admin.site.urls),

   path('homepage', index.page_home, name= 'hpage'),
   path('', views.insertToDB),
   path('contactpage', index.contact_page, name= 'cpage')
]

contact.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@200&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
    <title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">

    <script src="{% static 'js/main.js' %}"></script>

    <div class="top-nav">
        <a href="{% url 'hpage' %}">HOME</a>
        <a href="products.html">PRODUCTS</a>
        <a href="contact.html">CONTACT</a>
        <a href="about.html">ABOUT</a>
        <a href="community.html">COMMUNITY</a>
        </div>

        <div class="div-align">

            <h2>Contact</h2>
            <p>Reach us for questions/concerns through the form below.</p>
        </div>  
    <form class="fontmaker" method="post">
        {% csrf_token %}
        <label for="Username">Username:</label><br>
        <input type="text" id="Username" name="uname" required><br>
        <label for="E-mail">E-mail:</label><br>
        <input type="text" id="Email" name="email" required>
        <label for="Reason" class="margin">Message:</label>
        <textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
        <input type="submit" value="Submit" class="rounded-corners" id="submitBtn">

        {% if messages %}
        {% for message in messages %}
            {{message}}
        {% endfor %}
        {% endif %}
        
    </form>
    
</body>
</html>

There are no errors in terminal, and the button click also properly sends a POST req: Terminal output

I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.

index.py

from django.http import HttpResponse
from django.shortcuts import render

def page_home(request):
    return render(request, 'index.html')

def contact_page(request):
    return render(request, 'contact.html')

Thanks in advance.

If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:

urlpatterns = [
    # …,
    path('', views.insertToDB, name='insertToDB'),
    # …
]

and then specify the endpoint in the form:

<form class="fontmaker" method="post" action="{% insertToDB %}">
    <!-- … -->
</form>

In case of a successful POST request, you should also redirect, for example with:

from django.shortcuts import redirect

def insertToDB(request):
    if request.method == 'POST':
        if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
            post = dbInsert.objects.create(
                uname = request.POST['uname'],
                email = request.POST['email'],
                message = request.POST['message']
            )
            messages.success(request, 'Message sent successfully.')
            return redirect('cpage')
        return render(request, 'contact.html')

    else:
        return render(request, 'contact.html')

I would advise to work with Django forms [Django-doc] , for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM