working with forms in django - python

I want to write form and when submit it write "welcome!" in my page.But after I submit form method still is GET!!what's wrong?
this is my models:
from django.db import models
import django_tables2 as tables
from django import forms
class Form1(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
this is my view:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the previous section
form = Form1(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
return render(request, 'student/Home.html',{'message':'welcome'})
else:
form = Form1() # An unbound form
return render(request, 'student/Home.html', {'form': form})
this is my template(Home.html):
<!DOCTYPE html>
<html>
<body>
<form action="{% url 'student:contact' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit" />
</form>
<p>{{message}}<p>
</body>
</html>

Related

Profile picture does not update after form submitted in django

I also created UserUpdateForm class which i did not include here and if i try to change my name and email through UserUpdateForm class it works but if try for profile picture it did not works
views.py
from django.shortcuts import render, redirect
from .forms import ProfileUpdateForm
def editprofile(request):
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid():
p_form.save()
return redirect('profile')
else:
p_form = UserRegisterForm(instance=request.user.profile)
context = {
'p_form': p_form,
}
return render(request, 'users/editprofile.html', context)
forms.py
from django import forms
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
html template
<form class="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form__group form__avatar">
<label for="avatar">Upload Avatar</label>
<input class="form__hide" required type="file" name="avatar" id="avatar" accept="image/png, image/gif, image/jpeg, image/jpg"/>
</div>
</form>

How to save form data from base.html in django?

In my app, I have created a context_proccessors.py to show the form to base.html file.
I am able to show the form in the base.html file. But the problem I am facing is I have no idea how to save that form data from base.html since there is no view for the base.html. Below is my code:
models.py
class Posts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts')
post_pic = models.ImageField(upload_to='post_pic', verbose_name="Image")
post_caption = models.TextField(max_length=264, verbose_name="Caption")
created_date = models.DateTimeField(auto_now_add=True)
edited_date = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.user.username}"
forms.py
from django import forms
from post_app.models import Posts
class PostForm(forms.ModelForm):
class Meta:
model = Posts
exclude = ('user',)
context_proccessors.py
from post_app.forms import PostForm
def post_form(request):
form = PostForm
return {
'post_form': form,
}
base.html
<form method="POST" enctype="multipart/form-data">
{{ post_form|crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Post</button>
</form>
I want the form to be displayed on every page so that the user can submit data from anywhere
def PostView(request):
form = PostForm()
if request.method == 'GET':
return render(request, 'base.html', {form:form})
elif request.method == 'POST':
form.save(request.data)
In the views.py of your app you can define this view, and the you have to provide it an url in the urls.py of the root directory. So evere time there is a request on that url, if the method is GET, the form will be rendered on base.html file, if the method is POST, the post will be saved.
By following the answer by N T I have implemented this. So, I had to make a URL pattern for the view and use that URL pattern in the action in the form of base.html.
view.py
#login_required
def postsaveview(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
user_obj = form.save(commit=False)
user_obj.user = request.user
user_obj.slug = str(request.user) + str(uuid.uuid4())
user_obj.save()
return HttpResponseRedirect(reverse('profile_app:profile'))
urls.py
urlpatterns = [
path('post-save/', views.postsaveview, name='post-save'),
]
base.html
<form action="{% url "post-save" %}" method="POST" enctype="multipart/form-data">
{{ post_form|crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Post</button>
</form>

Django 2.0 Form is not saving data to database

so I have a very simple blog app and I'm trying to figure out why the data entered in the form doesn't save to the database and it doesn't redirect me to my index page.
forms.py
from django import forms
class NewBlog(forms.Form):
blogger = forms.CharField(max_length=20, widget=forms.TextInput(attrs=
{'placeholder' : 'Name'}))
text = forms.CharField(widget=forms.Textarea(attrs={'placeholder' :
'Text'}))
new_blog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>New Blog</title>
</head>
<body>
<form action="{% url 'new_blog' %}" method="POST">
{% csrf_token %}
<h2>Write your blog here:</h2>
{{ form }}
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
views.py
from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import NewBlog
def index(request):
blogs = BlogPost.objects.all()
context = {'blogs' : blogs}
return render(request, 'blog/index.html', context)
def newBlog(request):
if request == 'POST':
form = NewBlog(request.POST)
if form.is_valid():
blogger = form.cleaned_data['blogger']
text = form.cleaned_data['text']
new_blog = BlogPost(blogger = blogger, text = text)
new_blog.save()
return redirect('index')
else:
form = NewBlog()
context = {'form' : form}
return render(request, 'blog/new_blog.html', context)
I think the problem is likely to be the first line of your view.
if request == 'POST':
should be:
if request.method == 'POST':
To save an Object into database
instead of
new_blog = BlogPost(blogger = blogger, text = text)
new_blog.save()
use the best way:
BlogPost.objects.create(blogger = blogger, text = text)
It will be automatically saved

newbie Django Choicefield/Charfield display on html page

I have been reading the django book and the django documentation, but still can figure it out.
i have this model.py:
from django.db import models
from django.forms import ModelForm
class Zonas(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class ZonasForm(ModelForm):
class Meta:
model = Zonas
this view.py:
from django import forms
from testApp.models import Zonas
from django.shortcuts import render_to_response
def menuForm (request):
z = list (Zonas.objects.all())
numbers = forms.CharField(max_length=30,
widget=forms.Select(choices=z))
return render_to_response('hello.html', {'numbers':numbers})
this html:
<html>
<body>
<form action="" method="get">
<div class="field">
{{ form.numbers }}
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
Ans this urls.py:
from django.conf.urls import patterns, include, url
from testApp.views import menuForm
urlpatterns = patterns('',
url(r'^hello/$', menuForm ),
)
All i get when i run the server is a page only with the submit button, and no form.number wich is supossed to be a select menu.
I tried this views.py:
def menuForm (request):
z = list (Zonas.objects.all())
numbers = forms.ChoiceField(choices=z)
return render_to_response('hello.html', {'numbers':numbers})
But the result is the same...
Any hints? Should i use a diferent return?
You are trying to access {{ form.numbers }} when you never pass a form variable to the template. You would need to access numbers directly with {{ numbers }}.
Also you aren't quite using forms correctly. Check this out https://docs.djangoproject.com/en/dev/topics/forms/
Create a menu form that contains a ModelChoiceField
forms.py
class MenuForm(Form):
zonas = forms.ModelChoiceField(queryset=Zonas.objects.all())
Now use that form in your view
views.py
from myapp.forms import MenuForm
def menuForm(request):
if request.method == 'POST': # If the form has been submitted...
form = MenuForm(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('/success/') # Redirect after POST
else:
form = MenuForm() # An unbound form
return render(request, 'hello.html', {
'form': form,
})
Now you can use the form in your template
hello.html
<html>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>
How about using ModelChoiceField? This code works for me.
views.py:
from django import forms
from models import Zonas
from django.shortcuts import render_to_response
class NumbersForm(forms.Form):
numbers = forms.ModelChoiceField(queryset=Zonas.objects.all())
def menuForm(request):
form = NumbersForm()
return render_to_response('hello.html', {'form': form})
hello.html:
<form action="" method="get">
<div class="field">
{{ form.as_p }}
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
You have several errors in your applications. Let's do the following:
You will need the following files in your testApp folder: models.py, views.py, forms.py. Now, inside models.py you will define model Zonas (pretty much as you have done)
#models.py
from django.db import models
class Zonas(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
Now, inside the forms.py file you will have this:
from testApp.models import Zonas
from django.forms import ModelForm
z = ((zona.name,zona.name) for zona in Zonas.objects.all())
class ZonasForm(ModelForm):
name = forms.CharField(max_length=30,widget=forms.Select(choices=z))
class Meta:
model = Zonas
Then, your views.py:
from testApp.forms import ZonasForm
from django.shortcuts import render_to_response
def menuForm (request):
if request.method = 'POST':
form = ZonasForm(request.POST)
if form.is_valid():
form.save()
else:
form = ZonasForm()
return render_to_response('hello.html', {'form':form})
There you have your form processed and everything.
Next, your hello.html:
<form action="" method="post">
{% csrf_token %}
<div class="field">
{{ form.as_p }}
</div>
<input type="submit" value="Submit">
</form>
</body>
All of this combined should work. You had some concept errors in your app definition, I hope this could help as a guide.

Uploading csv file from url using django forms

So I am trying to upload and save a csv file to a variable via a POST to a url. I have looked through the django documentation on file uploads found here. I just don't understand the use of a form? What's the purpose in this situation?
They use an example with a form:
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
Upload html:
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
<input id="file" type="file" name="test" />
<input id="signUpSubmit" type="submit" value="Submit">
</form>
models.py
from django.db import models
class Upload(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(upload_to="images")
forms.py
from django import forms
from app_name.models import Upload
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
views.py
def upload_file(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
upload.html
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
{% csrf_token %}
{{form.as_p}}
<input id="signUpSubmit" type="submit" value="Submit">
</form>

Categories