Reputation: 964
I am working on a django application, which contains a form. I defined the model and made the migrations. But the data is not being saved into the database. And the URL for the application gets messed up when I use submit the form.
This is my code so far
class modelPost(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(max_length=70)
phone = models.CharField(max_length=12)
def publish(self):
self.save()
def __str__(self):
return self.name
from .models import modelPost
class testForm(forms.ModelForm):
class Meta:
model = modelPost
fields = ('name', 'email', 'phone')
from .forms import testForm
# Create your views here.
def index(request):
if request.method == "POST":
testForm = testForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('home')
else:
testForm = testForm()
return render(request, 'index.html', {'testForm': testForm})
<form>
{% csrf_token %}
{{ testForm.name|as_crispy_field }}
{{ testForm.email|as_crispy_field }}
{{ testForm.phone|as_crispy_field }}
<input type="submit" value="check" class="save btn submit_button">
</form>
when I try to submit the form, this happens to the url
http://127.0.0.1:8000/?csrfmiddlewaretoken=BG2i7fSbwG1d1cOlLWcEzy5ZQgsNYzMrhDJRarXkR3JyhetpWvqNV48ExY7xM9EW&name=randomPerson&email=test%40test.com&phone=12345678
These are some links that I checked, but the answers dont work
Upvotes: 1
Views: 345
Reputation: 33
You need to specify the method in form tag , method = "post" and you need to give the path or url in form tag where you want to go after clicking the submit or check button.
<form method="post" acton="Enter the path or url here">
{% csrf_token %}
{{ testForm.name|as_crispy_field }}
{{ testForm.email|as_crispy_field }}
{{ testForm.phone|as_crispy_field }}
<input type="submit" value="check" class="save btn submit_button">
</form>
Also try to pass request in form parameters like testform(request, data=request.POST), It should work now.
Upvotes: 1
Reputation: 476503
You did not make a POST request, you should specify method="post"
in the <form>
tag:
<form method="post">
{% csrf_token %}
{{ testForm.name|as_crispy_field }}
{{ testForm.email|as_crispy_field }}
{{ testForm.phone|as_crispy_field }}
<input type="submit" value="check" class="save btn submit_button">
</form>
By default the method is GET. You can actually see this, since the data is passed in the querystring of the URL. This thus means that the request.method == 'POST'
check will fail, and therefore, it will indeed not save the data to the database.
Upvotes: 4