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

Timed Actions - Randomized
Split pandas column into two
Case insensitive field in Django
How to rewrite the code which appends to lists with numpy arrays
Figure in a figure in a figure
Cron job not working all the way. and Python is only half working on my script
Module vtkCommonCorePython not found in windows
Trying to use exec() to define a variable by setting a string equal to a numpy ndarray, but I get a syntax error. Python 2.7.10
Django Staticfiles not being served on Azure
Create virtualenv with most recent version of python
Python date function bugs
Maya/Python: How do I scale multiple selected animation curves each from their own specific pivot point?
django model instance in form without model
How can I generically call super().method(), without explicitly passing in the current class? [duplicate]
Why is honcho forking recursively?
Using IFNULL in sqlalchemy core

Categories

HOME
makefile
jsf
caching
vhdl
websphere
xamarin.android
sed
boost-thread
jbehave
otrs
deep-linking
actionscript
windows-store-apps
console
histogrammar
filter
proguard
contact-form-7
goutte
gatsby
mongodb-query
future
riak
apache-karaf
uiautomator
embedly
sensu
google-ima
onesignal
interrupt-handling
edge-detection
devforce
svnkit
helix-3d-toolkit
construct-2
backup-strategies
shapes
large-data
rider
pmwiki
es-shell
coreclr
initializer
active-model-serializers
agent
cross-entropy
floating-accuracy
ssh.net
distributed-transactions
html-agility-pack
amd
php-ews
lirc
nstouchbar
gist
android-bitmap
build-process
manifest.mf
debugdiag
mongoose-populate
slam-algorithm
spoofing
spatial-query
gmsmapview
console-redirect
concur
proxygen
schtasks.exe
lmfit
sem
fabric-twitter
apigee-baas
virus
ibmsbt
ember-components
firebug-lite
bullet
korma
funkload
ssms-addin
dynamic-proxy
onselect
jqmobi
threadx
manage.py
tridion2009
android-4.0
usn
feof
caliper
goliath
authenticode
msbuildextensionpack
squeel
hibernate3-maven-plugin
revert
web-statistics
usergroups
divx
associativity

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