I'm trying to upload csv through django but it's not working..
Code
Views.py
from django.shortcuts import render_to_response
from forms import UploadForm
from django.http import HttpResponseRedirect
def create(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadForm()
return render_to_response('upload.html', {'form': form})
Url.py
urlpatterns = patterns('',
(r'^$', create),
#url(r'^articles/create/$', create, name='done'),
url(r'^articles/create/$', 'article.views.create'),
)
models.py
from django.db import models
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)
class Article(models.Model):
file = models.FileField(upload_to=get_upload_file_name)
Forms.py
from django import forms
from models import Article
class UploadForm(forms.ModelForm):
class Meta:
model = Article
html file
{% csrf_token %}
{{form.as_p}}
Your template needs to be:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
See the binding uploaded files to a form section in the documentation.
Related
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>
I have a quiz form and when I want to save the answer the model does not store its question. I want to validate the form and save it when if form.is_valid (): I remove it and instead of AnswerForm I use the direct Answer model then it saves but not so. How to change it so that I can validate it and save it with the help of the form?
my code ->
models.py
from django.db import models
# Create your models here.
from django.core.exceptions import ValidationError
class Question(models.Model):
question=models.CharField(max_length=100)
answer_question=models.CharField(max_length=100, default=None)
def __str__(self):
return self.question
class Answer(models.Model):
questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions")
answer=models.CharField(max_length=100,blank=True)
def __str__(self):
return str(self.questin)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Question,Answer
class QuestionForm(forms.ModelForm):
class Meta:
model=Question
fields="__all__"
class AnswerForm(forms.ModelForm):
class Meta:
model=Answer
fields="__all__"
views.py
from django.shortcuts import render
from django.shortcuts import render, HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from .forms import QuestionForm,AnswerForm
from .models import Question,Answer
import random
from django.forms import modelformset_factory
def home(request):
form=QuestionForm
if request.method=='POST':
form=QuestionForm(request.POST)
if form.is_valid():
form.save()
return render(request, "question/base.html", {"form":form})
def ans(request):
questions=Question.objects.all()
form=AnswerForm()
if request.method=="POST":
if form.is_valid():
qu=request.POST["i_id"]
question_id=int(qu)
answ=AnswerForm(questin=question_id,answer=request.POST["answer"])
answ.save()
return render(request, "question/ans.html", {"form":form, "questions":questions})
ans.html
<!DOCTYPE html>
<html>
<head>
<title>question</title>
</head>
<body>
{% for i in questions %}
<form method="POST" required>
{% csrf_token %}
{{i}}
<input type="hidden" name="i_id" value="{{ i.id }}"/>
{% for a in form.answer %}
{{a}}
{% endfor %}
<input type="submit" name="sub">
</form>
{% endfor %}
</body>
</html>
I can't seem to get a model form to load in my template.
models.py
from django.db import models
class Event(models.Model):
name = models.CharField(max_length=60)
start_datetime = models.DateTimeField()
end_datetime = models.DateTimeField()
description = models.TextField()
forms.py
from django import forms
from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['name']
views.py
from django.shortcuts import render
from .forms import EventForm
def index(request):
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_valid():
form.save()
else:
form = EventForm()
return render(request, 'index.html')
index.html
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
</form>
<button type="submit">Save</button>
I can get the form to print to the console on load when adding print(form) in views.py on the GET request, but it doesn't load in the template.
Good examples on different ways to use forms : https://docs.djangoproject.com/en/1.11/topics/forms/#the-view
For index.html to render it is expecting form variable. So Render method call should be like this:
render(request, 'index.html', {'form': form})
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.
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>