how to manipulate user submitted text and display it with django? - python

I want to build a very simple webapp that takes a user's text, runs a function on it that alters it and then displays the altered text. I have the code for the function but everything else is unclear.
I am very new to django and just need a push in the right direction with this problem. At the very least, tell me what to google, I've went through several tutorials but neither of them dealt with this kind of task.
Thanks in advance!

Define a form; in forms.py under your app's folder
class MyForm(forms.Form):
myinput = forms.forms.CharField(max_length=100)
Define a function in your views.py
import .forms
def handle_form(request):
if request.method == 'POST': # If the form has been submitted...
form = MyForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = MyForm() # An unbound form
return render(request, 'handle_form.html', {
'form': form,
})
Add a template
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Of course you need to add it to your urls.py
Most info was copy pasted from: https://docs.djangoproject.com/en/1.8/topics/forms/

Related

Avoiding page refresh when a form is used in Django

I have a very basic Django view:
def myview(request):
if request.method == 'POST':
if 'button1' in request.POST:
form1 = form = myForm(request.POST)
# check whether it's valid:
if form.is_valid():
profile = form.save()
profile.user = request.user
profile.save()
messages.success(request, f"Success")
return HttpResponseRedirect(request.path_info)
else:
form = myForm()
return render(request,
"main/mytemplate.html",
context={"form":form})
And its template:
<form method="post" novalidate>
{% csrf_token %}
{% include 'main/includes/bs4_form.html' with form=form %}
<button name="button1" type="submit" class="btn btn-primary">SUBMIT</button>
</form>
Everything works here, when this form is used, some data is saved on my DB. What i would like to change, though, is the page reload after the form is used.
When the Submit button is hit, the page will be refreshed. Since it makes the navigation way slower, i would like to have the view not refreshing the page each time the form is used.
Is it possible to accomplish this in Django? For example, instead of refreshing the page, i would like to only load part of it, or to have a 'Reload' icon while the view is doing its work.
I'm pretty new to Ajax, so i don't know how to get started on this.

Django - template build-in filter tags {% url %}

I am a new coder with Django. So, first apologize for it if this question is too easy.
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea)
def save_comments_into_database(topic, user_id, content):
data = Comment(topic=topic, commenter_id=user_id, content=content)
data.save()
this is the code for form
<form action = "{% url 'post:comment' the_topic=topic user_id=1 %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
I am trying to use url tag to call a function is views.py.
topic is a variable I passed in when this page is created.
this is my code in urls.py
url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="comment"),
then this is how I do in views.py
def comment(request, the_topic, user_id):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CommentForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
text = form.cleaned_data['comment']
args = {'form': form, 'text': text, 'topic': the_topic}
# save the data in database
save_comments_into_database(the_topic.id, user_id, text)
# redirect to a new URL:
return render(request, 'post/detail.html', args)
# if a GET (or any other method) we'll create a blank form
else:
form = CommentForm()
return render(request, 'post/detail.html', {'form': form, 'topic': the_topic})
I get the NoReserveMatchException:
I really don't get where it goes wrong.
Your comment URL only has one var, the topic_id, but you passed two vars, the_topic and user_id. You need to pass just the topic ID. Also, in views you would normally access the current user via request.user.
you should to change declare the urls, added second parameter and change name of the first
url(r'^(?P<the_topic>[0-9]+)/comment/(?P<user_id>[0-9]+)/$', views.comment, name="comment"),
# ^^^^^^^^^ ^^^^^^
It's better to serve the action redirection using Django built in HttpResponseRedirect in the views.py and combine it with reverse of your url Django docs ref, check bellow and change yourapp_path with your app path and name_space with url name like "blog".
main urls.py with "name_space"
like namepsace="blog"
url(r'^', include('yourapp_path.urls', namespace='name_space))
# ^^^^^^^^^^^^ ^^^^^^^^^^
app urls.py with name="name"
like name="comment"
url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="name")
# ^^^^^^
reverse with name_space:name
will return the complete path of the url taking name_space:name lets say blog:comment
reverse('name_space:name')
reverse with kwargs or args
reverse('name_space:name', kwargs={'kw1': 'val1'})
reverse('name_space:name', args=['val1'])
HttpResponseRedirect()
302 redirect to a given url in that case we will pass the reverse url.
like: HttpResponseRedirect(reverse('blog:comment', kwargs={'topic_id': topic.id}))
HttpResponseRedirect(reverse('name_space:name', kwargs={'kw1': 'val1'}))
views.py
#import HttpResoneRedircet and reverse
from django.shortcuts import HttpResponseRedirect, reverse
def comment(request, the_topic, user_id):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CommentForm(request.POST)
# check whether it's valid:
if form.is_valid():
# your is_valid()
return HttpResponseRedirect(reverse('name_space:name', kwargs={'the_topic': the_topic.id}))
template
<form action="{{ action }}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>

Why is my Django form not raising any errors?

I have a simple form and whenever the user does something wrong on the form I'd like to raise a validation error on Django. The problem is that I set up the form validation but when the form is submitted with wrong values, it goes through. I was wondering why it's happening and how I can avoid that?
Here is the html form:
<form id="ask-project" method="post" action="{% url 'ask-project' %}">
{% csrf_token %}
<input required="required" class="form-control form-text required" id="prenom" name="prenom" type="text">
<button class="btn btn-default submit">Submit</button>
</form>
views.py:
def askProject(request):
if request.method == 'POST':
form = AskProjectForm(request.POST)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return redirect('/merci/') #success
forms.py:
class AskProjectForm(forms.ModelForm):
class Meta:
model = AskProject
fields = ['prenom']
def clean_prenom(self):
prenom = self.cleaned_data['prenom']
if len(prenom) < 3:
raise ValidationError('Votre prénom doit etre plus long que 1 caractère.')
return prenom
Am I doing something wrong?
With the pattern that you are using, this sort of problem is inevitable and order of the day. The first thing is not to render the form manually as you appear to be doing. That means you are not showing any feedback when the user enters invalid data. Consider using {{ form }}, {{ form.as_table }} etc or rendering the fields with all information as described here: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually
Second problem is that you are redirecting when the form is submitted, regardless of whether it's valid or not. The recommended pattern is to redirect only when the form is valid. So even if you apply the suggestion in the first para, you are still not getting the required feedback. Consider implementing the form as suggested in the manual. A straight copy past follows
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Finally getting onto the specific case of why your form validation doesn't work, add a print statement in your clean method to print out both the string and it's length see if it tallies (or if your method even gets called)

Django Form request not saving data to db

I am using a django form in atemplate to save data entered to database.
In my view after the request is made, the response is redirected correctly but the data is not saved to db.
I might be missing something. but am unable to find it even after a lot of debugging.
here is what has been done so far:
views.py:
from .models import testmodel
def testview(request):
if request.method== 'POST':
form=MapForm(request.POST)
if form.is_valid():
test1=request.POST.get('t1')
print meaningid1
test2=request.POST.get('t2')
print meaningid2
pobj=testmodel(test1=test1,test2=test2)
pobj.save()
return HttpResponse('Successful')
after this the response message "Successful" is seen
from template:
<form action="/testview/" method="post"> {% csrf_token %}
{{form.as_p}}
<input type="text" name="t1" value='' id='t1'/> <br><br><br>
<input type="text" name="t2" value='' id='t2'/><br>
<input type="submit" value="Submit" />
</form>
from forms.py:
from .models import testmodel
class MapForm(forms.ModelForm):
class Meta:
model = testmodel
fields = ['test1','test2']
after the data is entered in form it is going to page /testview and showing message on page. but from backend data is not been saved to db.
Can some one suggest what could be done
Thanks
In python, indentation matters.
def testview(request):
if request.method== 'POST':
form=MapForm(request.POST)
if form.is_valid():
test1=request.POST.get('t1')
print meaningid1
test2=request.POST.get('t2')
print meaningid2
pobj=testmodel(test1=test1,test2=test2)
pobj.save()
return HttpResponse('Successful')
In the above code 'Successful' will be displayed regardless of whether the form is actually successful or not. You need to push your return statement four spaces to the right, and you also need to add an else clause which handles the situation where the form is not valid. Typically that is just to display the form again (with form errors which wil be displayed for you automatically is you use form.as_p or form.as_table)

Django form processing

I'm during the form tutorial on https://docs.djangoproject.com/en/1.8/topics/forms/. I'm trying to make a simple form element, which will be POSTing some data. This is function launched in urls.py:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
HTML code looks as follows:
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
When I input some data to form and click 'Submit' button, function connected to /your-name/ URL is launched and I'm redirected to /your-name/. I'm wondering why function connected to /thanks/ URL is not launching. How can it be reached?
For the view to work, the form's action /your-name/ must be served by your view get_name.
You haven't shown your url patterns, so it's impossible to tell whether the mistake is there or not.

Categories

Resources