python


Django Forms:Post request is got but data is not saved


So I'm trying to build a Django site that collects Mod Applications to learn Django Forms. Except that I'm an idiot and I don't know what am I doing.
The thing that I'm trying to do is collect and save the Form data the current part and later try to show that data in the Django Admin the part I still haven't done and don't know how.
When I fill out the form I get [06/May/2017 19:38:29] "POST /modapp HTTP/1.1" 200 2354
This is my forms.py:
class Application(forms.ModelForm):
class Meta:
model = ModApplication
fields = ('discord', 'reddit', 'serverrank','finds','serverstay','active','timezone','reason','helped','help')
def __init__(self, *args, **kwargs):
super(Application, self).__init__(*args, **kwargs)
self.fields['discord'].widget.attrs['placeholder'] = 'UnknownDeveloper#2068'
self.fields['reddit'].widget.attrs['placeholder'] = '/u/UnknownDeveloper'
self.fields['serverrank'].widget.attrs['placeholder'] = 'GEOCACHING + RANK'
self.fields['serverstay'].label = "How long have you been on the server"
self.fields['active'].label = "How active have you been on the server"
self.fields['timezone'].widget.attrs['placeholder'] = 'CET'
self.fields['reason'].label = "Why do you want to become a mod?"
self.fields['helped'].label = "How have you helped the server so far?"
self.fields['help'].label = "How will you help the server if you'll become a mod"
models.py
class ModApplication(models.Model):
def __unicode__(self):
return "Discord User: " + self.discord + " aka " + self.reddit
reddit = models.CharField("Reddit Username", max_length=30)
discord = models.CharField("Discord Username", max_length=30)
serverrank = models.CharField("Server Rank", max_length=60)
finds = models.CharField("Finds", max_length=12)
serverstay = models.CharField("Stayed on the server for",max_length=200)
active = models.CharField("Is Actice on Discord for", max_length=500)
timezone = models.CharField("Timezone", max_length=20)
reason = models.TextField("He likes to become a mod because", max_length=5000)
helped = models.TextField("He helped by", max_length=5000)
help = models.TextField("He'll help by", max_length=5000)
views.py
def formtofill(request):
form = Application()
return render(request, 'appmod.html', {'form': form,})
if request.method == "POST":
form = Application(request.POST)
print(request.POST)
if form.is_valid():
user = form.save()
user.discord = request.discord
user.reddit = request.reddit
user.serverrank = request.serverrank
user.finds = request.finds
user.serverstay = request.serverstay
user.active = request.active
user.timezone = request.timezone
user.reason = request.reason
user.helped = request.helped
user.help = request.help
user.save()
print(user)
messages.success(request, 'Your Mod Application has been successfully submitted!')
print(form)
return HttpResponse('Successful')
else:
form_class = Application
I searched a lot but I didn't find anything. I tried to print debug messages but they didn't print anything. I put the messages module but nothing happened. HTTPResponse just reloads back to the form. Help will be gladly accepted. Thanks for your time. If I am missing something please tell me and i'll edit my post
It's a suprise that this code runs at all, it should be producing attribute errors for these:
user.discord = request.discord
user.reddit = request.reddit
But the reason that it doesn't is because the execution path never reaches that point
def formtofill(request):
form = Application()
return render(request, 'appmod.html', {'form': form,})
Because of that return statement.
Your corrected code should look like
def formtofill(request):
form = Application()
if request.method == "POST":
form = Application(request.POST)
print(request.POST)
if form.is_valid():
user = form.save()
messages.success(request, 'Your Mod Application has been successfully submitted!')
return HttpResponseRedirect('/success_url')
else:
form_class = Application
return render(request, 'appmod.html', {'form': form,})
Dont save the form upfront. Save but put commit=false.
Also remove that return statement as in the answer above mine.
user = form.save(commit=False).
Then an instance is created, but its not written into the database. Now you can do the assignments.
user = form.save(commit=False).
#Now....
user.discord = request.POST['discord']
user.reddit = request.POST['reddit']
user.serverrank = request.POST['serverrank']
user.finds = request.POST['finds']
user.serverstay = request.POST['serverstay']
....................
user.save()
return HttpResponse('Successful')
Instead you were trying to access the data as an attribute of the request object itself. The form data are contained in request.POST, then you have to access it from there.
Also,
else:
form = Application()
You need to instantiate the form class.

Related Links

List Comprehension For Loop + Ternary Operation For Loop?
Pass variable to multiple templates in pybottle
Next and Before Links for a django paginated query
Python - String of Digits to Integer using Recursion?
Weird type error arising when I add to a database using SQL Alchemy
Python for loop causes system crash
Class object variable = none
Print last <td> in beautiful soup
Break python regular expression with escape into multiple lines
Django querying with Through table properties
How to get the 1st, 3rd and 5th element from an array in Python?
Unexpected unindent
Obscurity in “lambda” function in python
Having trouble getting “more like this” to return any results in Haystack using Elastic Search backend
Linear interpolation within groups
Is it possible to turn a widget [Kivy]

Categories

HOME
angular-cli
mapping
raspbian
decorator
ruby-on-rails-3
jscript
rfc
orientation
i2c
structuremap
shipping
unity2d
gatsby
xlsx
uiview
ida
multicore
deb
kitematic
rworldmap
pdfsharp
tampermonkey
non-deterministic
jenkins-job-dsl
metis
pentaho-report-designer
cell-array
canvasjs
nunit-3.0
pace
common.logging
wcf-security
ical-dotnet
ssh.net
android-maps-v2
openweathermap
lirc
number-theory
jags
amazon-machine-learning
mcrypt
info
iphone-developer-program
svn-merge
settimeout
pspice
build-process
icefaces
galleriffic
software-product-lines
wcf-ria-services
spark-cassandra-connector
kendo-combobox
project-online
picking
direct3d12
jta
coldfusion-7
geodjango
oai
abas
visual-studio-code
harp
viper-architecture
criteria-api
low-level
moai
gmaps4rails
snmp4j
ghostdoc
outline
eclipse-classpath
neoload
android-looper
slick-2.0
uipickerviewcontroller
svcutil.exe
modeshape
nscolor
surveyor-gem
cbcentralmanager
enumerators
plone-funnelweb
wcf-web-api
legacy-code
ninject-extensions
opengl-es-lighting
nvelocity
swfloader
usability-testing

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App