Can we use instance in the form? - django

hello guys i am working on form i didint find how to get instance in the form. This is not a model form
def form(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
else:
form = Form()
return render(request, 'app/form.html', {'form': form})

You should have a form class something like below:
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Now To handle the form we need to instantiate it in the view for the URL where we want it to be published:
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# process the data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Refer the Django documentation for more details.
https://docs.djangoproject.com/en/3.0/topics/forms/

Related

The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead

from django import forms
from .models import Blog
I just rewrite code this point,
from ↓:
# class BlogPost(forms.ModelForm):
# class Meta:
# model = Blog
# fields = ['title', 'body']
to ↓:
class BlogPost(forms.Form):
email = forms.EmailField()
files = forms.FileField()
url = forms.URLField()
words = forms.CharField(max_length=200)
max_number = forms.ChoiceField(choices=[('1','one'), ('2','two'),('3','three')])
and views.py file is here ↓:
from django.shortcuts import render, get_object_or_404, redirect
from .models import Blog
from django.utils import timezone
from .form import BlogPost
from django.views.decorators.http import require_http_methods
# Create your views here.
def home(request):
blogs = Blog.objects #쿼리셋
return render(request, 'home.html', {'blogs'`enter code here`:blogs})
def detail(request, blog_id):
details = get_object_or_404(Blog, pk=blog_id)
return render(request, 'detail.html', {'details':details})
def new(request):
return render(request, 'new.html')
def create(request):
blog = Blog()
blog.title = request.GET['title']
blog.body = request.GET['body']
blog.pub_date = timezone.datetime.now()
blog.save()
return redirect('/blog/'+str(blog.id)) #이 URL로 넘기세요 처리된 정보를
def blogpost(request):
if request.method =='POST':
form = BlogPost(request.POST)
if form.is_valid():
post = form.save(commit=False)
# post.pub_date = timezone.now()
post.save()
return redirect('home')
else:
form = BlogPost()
return render(request, 'newblog.html',{'form':form})
I don't know why I only rewrite 'form.py' file, but vscode program says "The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead."
what should I do?? help..
def blogpost(request):
if request.method =='POST':
form = BlogPost(request.POST)
if form.is_valid():
post = form.save(commit=False)
# post.pub_date = timezone.now()
post.save()
return redirect('home')
else:
form = BlogPost()
return render(request, 'newblog.html',{'form':form})
You don't have a return statement on here due to your if statement and indentation.
Write it like:
def blogpost(request):
if request.method =='POST':
form = BlogPost(request.POST)
if form.is_valid():
post = form.save(commit=False)
# post.pub_date = timezone.now()
post.save()
return redirect('home')
else:
form = BlogPost()
return render(request, 'newblog.html',{'form':form})
And it should work.

save() got an unexpected keyword argument 'force_insert'

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been created. Log In to continue.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
This is the code when I run it I get an error. But that error shouldn't be there since I am not overriding the the save() method. please help.
try to get each form input one by one and then save the form. for example:
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = YourModelName()
data.input1 = form.cleaned_data['input1']
data.input2 = form.cleaned_data['input2']
# ...
form.save()
messages.success(request, 'Your account created. You can now Login.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
I have a feeling that you are doing Corey Schafer's Django tutorial. If so, other users have had the same problem, which is discussed here:
Django - TypeError - save() got an unexpected keyword argument 'force_insert'
The issue lies in overriding the save method in your Profile model

Attaching logged in user to a class based form and model

views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadDocument
from .models import Document
def upload_document(request):
if request.method == 'POST':
form = UploadDocument(request.POST, request.FILES)
if form.is_valid():
# file is saved
instance = Document(passport=request.FILES['passport'])
instance.save()
instance = Document(id_license=request.FILES['id_license'])
instance.save()
instance = Document(User=request.user)
instance.save()
# needs to add instance of User from cache
return HttpResponseRedirect('/success/url/')
else:
form = UploadDocument()
return render(request, 'verification/verificate.html', {'form': form})
forms.py
from django import forms
class UploadDocument(forms.Form):
passport = forms.ImageField()
id_license = forms.ImageField()
models.py
from django.conf import settings
from django.db import models
class Document(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
passport = models.ImageField()
id_license = models.ImageField()
Exception Value: NOT NULL constraint failed:
verification_document.user_id
I want to create a form that allows uploading documents, for verification purpose. How to attach a loged in User?
try this code:
views.py
def upload_document(request):
if request.method == 'POST':
form = UploadDocument(request.POST, request.FILES)
if form.is_valid():
instance=Document()
instance.passport=request.FILES['passport']
instance.id_license=request.FILES['id_license']
instance.User=request.user
instance.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadDocument()
return render(request, 'verification/verificate.html', {'form': form})

Django link two apps

im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app).
this is the error i get:
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
urls.py
...
from quickblog import views as core_views
from accounts import views as views_accounts
...
url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'),
views.py (accounts app):
from django.shortcuts import render, redirect
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('accounts:home'))
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'reg_form.html', args)
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'profile.html', args)
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'edit_profile.html', args)
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('accounts:view_profile'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'change_password.html', args)
This is my first django app, is there maybe anything i need to know about linking two apps within one project?
thanks

confirmation form step2.html Django

What is the best way to show confirmation on step2.html in Django?
forms.py:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea())
views.py:
from django.views.generic import FormView
from .forms import ContactForm
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import HttpResponseRedirect
def step1(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
#save and cleared_form
return HttpResponseRedirect('/step2/')
else:
form = ContactForm()
return render(request, 'step1.html', {'form': form})
def step2(request):
ctx = { 'Test_1': 'email#email.com'}
return render(request, 'step2.html', ctx)
step2.html:
{{Test_1}}
On step 2 I want to show fields submitted on step 1, how to achieve that?
Good solution will be to show step2.html in step1 view when valid form is submitted, instead of redirecting user to step2. That way you will have access to your form data in view and template.
When submitting confirmation, values from step 1 can be passed by hidden fields or saved into session storage.
Example:
def step1(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
ctx = {'contact_data': form.cleaned_data}
return render(request, 'step2.html', ctx)
else:
form = ContactForm()
return render(request, 'step1.html', {'form': form})
You can save whole form data (cleaned_data) into session storage before redirection in step 1. That way you will be able to retrieve that data in step 2. Example:
def step1(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
#save and cleared_form
request.session.contact_form = form.cleaned_data
return HttpResponseRedirect('/step2/')
else:
form = ContactForm()
return render(request, 'step1.html', {'form': form})
def step2(request):
contact_data = request.session.get('contact_form', None)
if contact_data is None:
return HttpResponseRedirect('/step1/')
# someone is entering step 2 directly, without submitted form in step 1, we should redirect him back to step 1.
ctx = {'contact_data': contact_data}
return render(request, 'step2.html', ctx)
Consider using Form wizard. It will handle for you passing submitted data between steps (using cookies or session). All you need to do is: create 2 views, one with proper form, one with just some confirmation button and in template for step 2 retrieve all data from step 1.