When i'm submitting a jpg image then it refreshes and shows 'This field required'validation error,so in views i tried to print(request.POST),it shows csrfmiddlewaretoken and pic in console but field validation is getting violated. Please correct me.
models.py
from django.db import models
class picture(models.Model):
pic = models.ImageField(upload_to='documents/')
forms.py
from django import forms
from .models import picture
class pictureForm(forms.ModelForm):
class Meta:
model = picture
fields = ['pic',]
views.py
from django.shortcuts import render,redirect
from .models import picture
from .forms import pictureForm
# Create your views here.
def pictureView(request):
if request.method == 'POST':
print(request.POST)
form = pictureForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = pictureForm()
return render(request,'home.html',{'form':form})
urls.py(APP level urls)
from django.urls import path
from . import views
urlpatterns = [
path('',views.pictureView, name = 'home')
]
urls.py(Directory level urls)
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Media files
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
template
<form method="post">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
based on the doc: uploaded-files-with-a-model
you should initialize your form:
form = pictureForm(request.POST, request.FILES)
and in the template you need add enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input value="submit" type="submit">
</form>
Related
I was doing some How-To tutorials about Django Forms.
But it will not display anything for me. Any ideas why? Picture below illustrates my problem.
This is my Login -> index.html
<body>
<div class="gradient-border" id="box">
<h2>Log In</h2>
<form action = "" method = "post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</div>
</body>
this is forms.py
class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200)
last_name = forms.CharField(max_length = 200)
password = forms.CharField(widget = forms.PasswordInput())
this is views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
def index(request):
return render(request, 'login/index.html')
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "index.html", context)
def main(request):
return render(request, 'login/main.html')
this is urls.py
from django.contrib import admin
from django.urls import path, include
from login.views import index, main
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', index),
path('main/', main),
path('accounts/', include('django.contrib.auth.urls')),
]
Login Page
You are not passing the form context for the login route. In your index function, you don't have any context, and you put the form in home_view function which is not the view function being called by the /login route.
models.py
I write this code for creating a form which has two fileds named Title and Desc
from django.db import models.Here is models.py code.
class Post(models.Model):
title = models.CharField(max_length=200)
desc = models.TextField()
And Here is forms.py Code
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm,UsernameField
from django.contrib.auth.models import User
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','desc']
# label = {'title':'Title','desc':'Description'}
widgets={'title':forms.TextInput(attrs={'class':'form-control'}),
'desc':forms.Textarea(attrs={'class':'form-control'})}
Here is the views.py code
views.py
from django.shortcuts import render,HttpResponseRedirect
from .forms import SignUpForm,LoginForm,PostForm
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from .models import Post
def add_post(request):
if request.user.is_authenticated:
if request.method == "POST":
form = PostForm(request.method)
if form.is_valid():
title1 = form.cleaned_data['title']
description = form.cleaned_data['desc']
pst = Post(title=title1,desc=description)
pst.save()
form = PostForm()
else:
form = PostForm()
return render(request,'blog_app/addpost.html',{'form':form})
else:
return HttpResponseRedirect('/login/')
Here is the addpost.html
addpost.html
{% extends 'blog_app/base.html' %}
{% load static %}
{% block content %}
<div class="col-sm-10">
<h3 class="text-black my-5 alert alert-success">Add Post</h3>
<form action="" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Add" class="btn btn-primary">
Cancel
</form>
</div>
{% endblock content %}
But When I click on Add Button I got this errorenter image description here
What is the solution of it
Here is Url.py code
urls.py
from django.contrib import admin
from django.urls import path
from blog_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home),
path('about/', views.about,name='about'),
path('contact/', views.contact,name='contact'),
path('dashboard/', views.dashboard,name='dashboard'),
path('signup/', views.signup,name='signup'),
path('login/', views.user_login,name='login'),
path('logout/', views.user_logout,name='logout'),
path('add/', views.add_post,name='addpost'),
path('update/<int:id>/', views.update_post,name='updatepost'),
path('delete/<int:id>/', views.delete_post,name='deletepost'),
]
And This is the error Shows in my terminal
terminal img
This line in your view
form = PostForm(request.method)
should be
form = PostForm(request.POST)
So, I have a code below:
newEra/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include('mentor.urls')),]
mentor/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home_page),
]
my views.py
from django.shortcuts import render,redirect
from .models import *
from .forms import *
def home_page(request):
todo = ToDo.objects.all()
form = ToDoForms()
if request.method == 'POST':
form = ToDoForms(request.POST)
if form.is_valid():
form.save()
return redirect('')
context = {'todo' : todo, 'form':form}
return render(request, 'home.html',context)
home.html
<h1>To-Do list</h1>
<form action="POST" method="/">
{% csrf_token %}
{{form.name}}
<input type="submit" value="Create task" >
</form>
<ul>
{% for to in todo %}
<li>{{ to }}</li>
{% endfor %}
</ul>
But I am getting this error below
**Using the URLconf defined in NewEra.urls, Django tried these URL patterns, in this order:
admin/
The current path, POST, didn't match any of these.**
'mentor' file added to the SETTINGS
URLs are regexes.
Try:
urlpatterns = [
path('^/$',views.home_page),
]
I want to get a csv file from the user and then simply want to display the number of rows and columns in that file to the user
testapp.html:
<form method="POST" action="rowcol">
{% csrf_token %}
<input type="file" name="file" accept=".csv">
<button type="submit">Upload text</button>
</form>
views.py:
from django.shortcuts import render
from django.shortcuts import HttpResponse
import numpy as np
import pandas as pd
def testapp(request):
return render(request, 'testapp.html', {})
def rowcol(request):
if request.method == 'POST':
file = request.POST["file"]
dataset=pd.read_csv('file')
count_row = dataset.shape[0]
count_col = dataset.shape[1]
ans=("<H1>%d,%d</H1>",count_row,count_col)
return HttpResponse(ans)
urls.py:
from django.urls import path
from testapp import views
urlpatterns = [
path('', views.testapp, name='testapp'),
path('', views.rowcol, name='rowcol'),
]
urls.py in outer folder:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('testapp.urls')),
]
There are some problems here. First of all, your path(..)s clash with each other. You need to provide a different path for the second path. For example:
# testapp/urls.py
from django.urls import path
from testapp import views
urlpatterns = [
path('', views.testapp, name='testapp'),
path('rowcol/', views.rowcol, name='rowcol'),
]
Next in your template, you better use an {% url ... %} template tag, and set enctype to multipart/form-data:
<form method="post" action="{% url 'rowcol' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" accept=".csv">
<button type="submit">Upload text</button>
</form>
Finally in your view function, you forgot to format the string:
def rowcol(request):
if request.method == 'POST':
file = request.FILES['file']
dataset=pd.read_csv(file)
count_row, count_col = dataset.shape
ans='<H1>%d,%d</H1>' % (count_row,count_col)
return HttpResponse(ans)
return HttpResponse('')
views.py
name.html cannot be found
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import Get_name
# Create your views here.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/THANKS/')
else:
form = Get_name()
return render(request,'name.html',{'from':form})
name.html:why python is not able to find my template? my template dir structure is test2/templates/test2/name.html
<form action="/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
class Get_name(forms.Form):
user_name = forms.CharField(label='username',max_length='50')
test2/urls.py
from django.conf.urls import url
from .import views
urlpatterns=[
url(r'^$',views.index,name='index'),
]
test1/urls.py
from django.contrib import admin
from django.conf.urls import url , include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test2/',include('test2.urls')),
]
I think this will solve the problem.
Modify your views such that.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/THANKS/')
else:
form = Get_name()
return render(request,'test2/name.html',{'from':form})
prepend template name with test2 such that return render(request,'test2/name.html',{'from':form})