简体   繁体   中英

Can't get forms in Django to create a POST request (and save to database)

I'd like to point out that this is my first Django project and I don't have much other programming experience, so my error might be simple. Still, I spent a few days trying to fix it with no progress. It's also my first question here, so I hope I'm doing everything right.

The following is from the template of my form page. The form is displaying alright. It's just not causing the page to reload when the "submit" button is clicked and it's definitely not submitting a POST request.

<form role="form" action="." method="POST">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons submit='Add new book' reset="Cancel" %}{% endbuttons %}
</form>

models.py:

class Book(models.Model):
    title = models.CharField(max_length=80)
    photo = models.ImageField(upload_to='book_images', blank=True)
    author = models.CharField(max_length=150)
    category = models.CharField(max_length=50)
    product_url = models.CharField(max_length=200)
    num_of_chapters = models.IntegerField()

forms.py:

class AddBookForm(forms.ModelForm):

    class Meta:
         model = Book
         fields = ('title', 'photo', 'author', 'product_url', 'category', 'num_of_chapters')

views.py:

def add_new_book(request):
    if request.method == 'POST':
        form = forms.AddBookForm(data=request.POST)
        if form.is_valid():
            form.save()

    form = AddBookForm()
    return render(request, 'main/add_new_book.html', {'form': form})

There is a progress bar at the top of the page, which shows up whenever a page is loaded. It still shows up when I try to submit information for a new book, but PyCharm indicates that the page hasn't been reloaded and no post request has happened. There's no entry in the database as well.

By the way, that happens on all my other forms in the project as well. Seems like a rookie mistake, but I couldn't find a similar discussion.

Thanks!


UPDATE

I'm making progress, thanks to your input, but still I'm getting an error. This is what I get when I try to submit information for a new book:

[12/May/2015 16:12:54]"GET /main/add-new/?csrfmiddlewaretoken=FGaEtjH6ntyLSNm923OuYxBoOm9BQ0KN&title=Spiritual+Seduction&author=Jerry+Stocking&product_url=http%3A%2F%2Fwww.amazon.com%2FSpiritual-Seduction-Jerry-Stocking%2Fdp%2F0962959383&category=Spirituality&num_of_chapters=26 HTTP/1.1" 200 24399
[12/May/2015 16:12:54]"GET /static/assets/components/forms_elements_bootstrap-select/bootstrap-select.init.js?v=v2.0.0-rc1&sv=v0.0.1.2&1431436374743 HTTP/1.1" 200 185
[12/May/2015 16:12:54]"GET /static/assets/components/ui_sliders_jqueryui/jqueryui-sliders.init.js?v=v2.0.0-rc1&sv=v0.0.1.2&1431436374743 HTTP/1.1" 200 5282
[12/May/2015 16:12:54]"GET /static/assets/components/core/core.init.js?v=v2.0.0-rc1&1431436374743 HTTP/1.1" 200 7688
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 54178)
----------------------------------------
[12/May/2015 16:12:55]"GET /main/add-new/assets/images/logo/app-logo-style-default.png HTTP/1.1" 200 33624
Traceback (most recent call last):
  File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run
self.finish_response()
  File "C:\Python27\lib\wsgiref\handlers.py", line 128, in finish_response
    self.write(data)
  File "C:\Python27\lib\wsgiref\handlers.py", line 217, in write
self._write(data)
  File "C:\Python27\lib\socket.py", line 324, in write
self.flush()
  File "C:\Python27\lib\socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in your host machine
 [12/May/2015 16:12:55]"GET /main/add-new/assets/images/logo/app-logo-style-default.png HTTP/1.1" 500 59
Traceback (most recent call last):
  File "C:\Python27\lib\SocketServer.py", line 599, in process_request_thread
self.finish_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 102, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "C:\Python27\lib\SocketServer.py", line 657, in __init__
self.finish()
  File "C:\Python27\lib\SocketServer.py", line 716, in finish
self.wfile.close()
  File "C:\Python27\lib\socket.py", line 279, in close
self.flush()
  File "C:\Python27\lib\socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in your host machine
[12/May/2015 16:12:55]"GET /main/add-new/assets/images/people/100/15.jpg HTTP/1.1" 200 33625
Traceback (most recent call last):
  File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run
self.finish_response()
  File "C:\Python27\lib\wsgiref\handlers.py", line 128, in finish_response
    self.write(data)
  File "C:\Python27\lib\wsgiref\handlers.py", line 217, in write
    self._write(data)
  File "C:\Python27\lib\socket.py", line 324, in write
[12/May/2015 16:12:55]"GET /main/add-new/assets/images/people/100/16.jpg HTTP/1.1" 200 33624
    self.flush()
  File "C:\Python27\lib\socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in your host machine
[12/May/2015 16:12:55]"GET /main/add-new/assets/images/people/100/15.jpg HTTP/1.1" 500 59
Traceback (most recent call last):
  File "C:\Python27\lib\SocketServer.py", line 599, in process_request_thread
    self.finish_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 102, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
  File "C:\Python27\lib\SocketServer.py", line 657, in __init__
self.finish()
  File "C:\Python27\lib\SocketServer.py", line 716, in finish
self.wfile.close()
  File "C:\Python27\lib\socket.py", line 279, in close
self.flush()
  File "C:\Python27\lib\socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in your host machine
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 54179)
----------------------------------------
[12/May/2015 16:12:55]"GET /main/add-new/assets/images/people/100/17.jpg HTTP/1.1" 200 33625

I don't know what you mean by "definitely not submitting a POST request", nor what any of that has to do with PyCharm.

There are two issues with your view: you're not redirecting after a valid POST, and you're not redisplaying errors when the post is invalid. To fix:

def add_new_book(request):
    if request.method == 'POST':
        form = forms.AddBookForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')  # or wherever you want

    else:
        form = forms.AddBookForm()

    return render(request, 'main/add_new_book.html', {'form': form})

it,s true :

def add_new_book(request):
 if request.method == 'POST':
   form = AddBookForm(request.POST)
     if form.is_valid():
        form.save()
 form = AddBookForm(request.POST)
 return render(request, 'main/add_new_book.html', {'form': form})

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