I am a learner in django. i have created my first form, but when i input data i dont see it in my database but see in in my shell. I have rechecked my code but it seem fine, yet still it wont save in my code in the database.
Please help me out here.Thanks.
Model:
from django.db import models
class Login(models.Model):
first_name = models.CharField(max_length=200)
second_name = models.CharField(max_length=200)
email = models.EmailField()
password = models.CharField(max_length=200)
View:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Login
from .forms import login_form
def homeview(request):
return HttpResponse("<h1>Hello There</h1>")
def login_view(request):
form = login_form(request.POST or None)
if form.is_valid:
form.save
context = {
"form":form
}
return render(request, "login.html", context)
Template:
{% block content %}
<form action="" method="GET">{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login"/>
</form>
{% endblock %}
Form:
from django import forms
from .models import Login
class login_form(forms.ModelForm):
class Meta:
model = Login
fields = [
"first_name",
"second_name",
"email",
"password"
]
Following lines are incorrect:
if form.is_valid:
form.save
Currently the if will always return True because .is_valid returns the bound method.
You need to call is_valid -> form.is_valid()
Same for form.save. You would only return the bound method save, but you don't call it.
These lines would look like this:
if form.is_valid():
form.save()
Furthermore: In your template the used method for your form is GET but you are accessing request.POST. You need to change either one of them to the other method, e.g. method="POST".
Related
I am new in Django but know some stuff and still need your help.
I want when a user submits a button after putting info in the search area to redirect to another page and accept data for future use.
What I did so far:
in models.py
from django.db import models
from django.contrib import auth
class Child(models.Model):
name = models.CharField(max_length=150, blank=True)
in forms.py
from django import forms
from .models import Child
class ChildlForm(forms.ModelForm):
class Meta:
model = Child
fields = ('name',)
in views.py
from django.shortcuts import render
import numpy as np
import pandas as pd
def home(request):
form = ChildForm()
if request.method == "POST":
form = ChildForm(request.POST)
if form.is_valid():
data = form.save(commit=True)
else:
return 'main/test.html'
return render(request,'main/index2.html',{'name':data.name})
return render(request,'main/index.html',{'form':form})
'test.html' is where the form is required to be filled by user. I want after the inform submitted the data is saved and then redirected to garden.html file.
the test.html file
<form method="POST">
{{ form }}
{% csrf_token %}
<input class="form-control mr-sm-2" type="text">
<button type="submit">OK</button>
</form>
the form is search ready template posted by bootstrap.
Could you please help to link successfully the files and get the data (name) to further use in garden.html?
In index2.html
{% extends "base.html" %}{% block content %}
{{b}}
{% endblock content %}
def home(request):
form = ChildForm()
if request.method == "POST":
form = ChildForm(request.POST)
if form.is_valid():
data = form.save(commit=True)
name=data.name
symbols = [name]
yahoo_financials = YahooFinancials(symbols)
new_data = pd.DataFrame()
for s in symbols :
new_data[s] = wb.DataReader(s, data_source ='yahoo', start = '2014-1-1')['Adj Close']
a = new_data[s]
b = a[-1]
context={
'name':name,
'b':b
}
else:
form = ChildForm()
return render(request,'test.html',{'form':form})
return render(request,'garden.html',context)
return render(request,'test.html',{'form':form})
besides there is a typo in your code
class ChildlForm(forms.ModelForm):
I'm familiar with creating forms based on Model forms, in that case I can use form.save() to save the data in database. The question is, how do I save/retrieve the data of this form that I didn't create through a model form?
I've tried the following code but I'm not sure how to retrieve and save the data from NameForm.
#forms.py file:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label = 'your name', max_length = 100)
# views.py file
from django.shortcuts import render, redirect
from .forms import NameForm
def home(request):
return render(request, 'meal_plans/home.html')
def name(request):
if request.method != 'POST':
form = NameForm()
else:
form = NameForm(data=request.POST)
if form.is_valid():
your_name = form.cleaned_data['your_name']
return redirect('meal_plans:home')
return render(request, 'meal_plans/name.html', {'form': form})
# name.html template
<form action="{% url 'meal_plans:home' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form
One option is to save the data in the users session. The docs explain quite nicely how to implement this. In your case, it would be something like this:
if form.is_valid():
request.session['your_name'] = form.cleaned_data['your_name']
...
To access that session variable in another view, you would use:
your_name = request.session.get('your_name')
Django 2.0
Python 3.6
I am having trouble with a Django form that is not saving the file that is selected through the form; whenever you select a file to upload, I receive the message "This Field is Required.".
I placed a blank=True and a null=True in the Model FileField to get rid of the same, but whenever I attempt to load the html, I get this error: "The 'copydoc' attirbute has no file associated with it."
I would like for a user to be able to log in, create an entry and upload a file along with said entry. Why doesn't the DB accept the file from the form?
Thank you.
views.py:
from django.shortcuts import render, redirect
from .models import notarizer, CustomUser, notarizerCreateForm
# from .forms import notarizerCreateForm
# Create your views here.
def home(request):
t = 'home.html'
return render(request, t)
def page1(request):
t = 'log1/page1.html'
if request.user.is_authenticated:
logger = notarizer.objects.filter(userziptie=request.user).order_by('-date')
return render(request, t, {'logger': logger})
else:
return redirect(home)
def create_entry(request):
createPath = 'log1/create_entry.html'
if request.method == 'POST':
if request.method == 'FILES':
form = notarizerCreateForm(request.POST, request.FILES)
if form.is_valid():
instance =notarizerCreateForm(
file_field=request.FILES['file']
)
instance.save()
else:
print(form.errors)
else:
form = notarizerCreateForm(request.POST)
if form.is_valid():
form.save()
else:
print(form.errors)
else:
form = notarizerCreateForm()
return render(request, createPath, {'form': form})
create_entry.html:
{% extends "base.html" %}
{% block placeholder1 %}
<div class="form-holder">
<form name="form" enctype="multipart/form-data" method="POST"
action="/create_entry/" >
{% csrf_token %}
{{ form.as_table }}
<input type="submit"/>
</form>
</div>
{% endblock %}
models.py:
from django.db import models
from users.models import CustomUser
from django.forms import ModelForm
# Create your models here.
class notarizer(models.Model):
date = models.DateField(auto_now_add=True)
docName = models.CharField(max_length=25, null=False)
describe = models.TextField(max_length=280)
signee = models.CharField(max_length=25, null=False)
signeeDets = models.TextField(max_length=280)
copydoc = models.FileField(upload_to='users/', blank=True, null=True)
userziptie = models.ForeignKey('users.CustomUser',
on_delete=models.DO_NOTHING, null=True)
def __str__(self):
return "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}".format(
self.pk,
self.date,
self.docName,
self.describe,
self.signee,
self.signeeDets,
self.userziptie
)
class notarizerCreateForm(ModelForm):
class Meta:
model = notarizer
fields = ['docName','describe','signee','signeeDets', 'copydoc']
There are some things that make the view workflow very weird:
you check request.method, first you check if it is a 'POST' which is a good idea, but then you check if it is 'FILES', there is no HTTP method named FILES, there are only GET, POST, PATCH, PUT, OPTIONS, etc.;
you call form.is_valid() which is again what should happen, but then you create a new Form, and only pass it a single parameter; and
in case of a POST you should not return a rendered page, but redirect to a GET page (for example showing the result). The workflow is typically Post-redirect-get, since if the user refreshes their browser, we do not want to make the same post again.
The workflow should look like:
def create_entry(request):
createPath = 'log1/create_entry.html'
if request.method == 'POST': # good, a post (but no FILES check!)
form = notarizerCreateForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
else:
# you probably want to show the errors in that case to the user
print(form.errors)
# redirect to a page, for example the `page1 view
return redirect(page1)
else:
form = notarizerCreateForm()
return render(request, createPath, {'form': form})
I am trying to have a user input a task from the frontend and have that data instantiate a new model and add this new field in the database associated with their account. I have tried the following;
Profile HTML
<form id="taskitem_form" method="post" action="/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Add Task" class ="btn btn-primary" />
</form>
Model
class TaskItem(models.Model):
taskn = models.CharField(max_length = 400)
usern = models.ForeignKey(User)
def __str__(self):
return self.taskn
Views
def add_task(request):
# Get the context from the request.
#context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = TaskItemForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
task = form.save(commit=False)
task.usern = request.user
task.save()
# we should redirect after data modifying
return redirect('/user/%s' %(request.user))
else:
# If the request was not a POST, display the form to enter details.
return render(request, 'profile.html', {'form': form})
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'profile.html', {'form': form})
Forms
from django import forms
from bkmks.models import TaskItem
class TaskItemForm(forms.ModelForm):
taskn = forms.CharField(max_length = 300, help_text = "Please enter your task")
# An inline class to provide additional information on the form.
class Meta:
fields = ('taskn', 'usern' )
#This is the association between the model and the model form
model = TaskItem
Lot's of Changes needed to your code.
I'm posting a working version so that you can try.
Put profile.html file as bkmks/templates/bkmks/profile.html
Get it working. Customize later.
profile.html
<form id="taskitem_form" method="post" action="">
{% csrf_token %}
{{form}}
<input type="submit" name="submit" value="Add Task" class ="btn btn-primary" />
</form>
model as it is.
views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, RequestContext, redirect
from .forms import TaskItemForm
#login_required
def add_task(request):
# Get the context from the request.
context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = TaskItemForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
task = form.save(commit=False)
task.usern = request.user
task.save()
# Redirect to home (/)
return redirect('/')
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = TaskItemForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render_to_response('bkmks/profile.html', {'form': form}, context)
forms.py
class TaskItemForm(forms.ModelForm):
# task is changed to taskn
taskn = forms.CharField(max_length = 300, help_text = "Please enter your task")
# An inline class to provide additional information on the form.
class Meta:
fields = ('taskn',)
#This is the association between the model and the model form
model = TaskItem
If you get any error or data is not getting saved post here.
Going through Django tutorial will be an wise decision.
The below should do what you need. You really want to inherit 100% of everything from your model when you can. This insures all model validation trickles down to the form. I utilized verbose_name and help_text on the model to achieve this.
Models
from django.conf import settings
class TaskItem(models.Model):
taskn = models.CharField(
max_length=400,
verbose_name="task",
help_text="Please enter your task.",
)
usern = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
related_name="tasks",
)
def __str__(self):
return self.taskn
For the forms, I have added a forms.HiddenInput widget to the user, assuming you want the user submitting the task to become the user.
Forms
from django import forms
from bkmks.models import TaskItem
class TaskItemForm(forms.ModelForm):
widgets = {
'user': forms.HiddenInput,
}
class Meta:
model = TaskItem
fields = ('taskn', 'usern')
I have used a CreateView to reduce code complexity, and overrode the form_valid to add the user instance to the form.
Views
from django.views.generic import CreateView
from bkmks.models import TaskItem
from bkmks.forms import TaskItemForm
class TaskCreateView(CreateView):
model = TaskItem
form_class = TaskItemForm
template_name = "path/to/template.html"
def form_valid(self, form):
form.instance.user = self.request.user
return super(TaskCreateView, self).form_valid(form)
Finally, in the template, we simply want to use {{ form }}. I see you are looking into bootstrap. I'll suggest django-crispy-forms for this, but that is beyond the scope of your question.
Template
<form id="taskitem_form" method="post" action="/">
{% csrf_token %}
{{ form }}
<input type="submit" name="submit" value="Add Task" class ="btn btn-primary" />
</form>
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response
render_to_response expects a template as the first argument, not a url.
I think in your second call to render_to_response should include the template name / path , while the first one should use a return HttpResponseRedirect("/") instead, though its not clear exactly what your problem is.
Add this line to imports in views.py
from django.contrib.auth.decorators import login_required
Decorate add_task view
#login_required
def add_task(request):
Then, edit part of your code
if form.is_valid():
task = form.save(commit=False)
task.usern = request.user
task.save()
# we should redirect after data modifying
return redirect('/')
else:
# etc.
Some notes. You may replace render_to_response to render.
Remove this line
context = RequestContext(request)
Replace
# Wrong usage, actually.
# Should be something like
# render_to_response(template_name, context, context_instance)
render_to_respone('/', {'form': form}, context)
with
# if template_name is "profile.html"
render(request, 'profile.html', {'form': form})
Why define a field called task in the form if you've already got a field in the model called taskn, wouldn't it be better to just use that? And like the guys have said, you need to specify a template to render (that's why you're not seeing anything).
It'd also be a good idea to pass the current user to the form's user field.
#login_required
def add_task(request):
# Get the context from the request.
context = {}
# A HTTP POST?
if request.method == 'POST':
form = TaskItemForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
form.save()
# Now call the index() view.
# The user will be shown the homepage.
return render_to_response(
'profile.html',
{'form': form},
RequestContext(request, context)
)
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = TaskItemForm(initial={'usern': request.user})
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render_to_response(
'profile.html',
{'form': form},
RequestContext(
request, context
)
)
Form;
from django import forms
from bkmks.models import TaskItem
class TaskItemForm(forms.ModelForm):
taskn = forms.CharField(max_length = 300, help_text = "Please enter your task")
# An inline class to provide additional information on the form.
class Meta:
fields = ('taskn', 'usern' )
#This is the association between the model and the model form
model = TaskItem
My problem is similar to how to edit model data using django forms, but I'm not able to solve it.
I would like to get an form with prefielled fields and to allow user to edit them.
I believe my problem is in views.py file, but unfrotuntely I'm not able to solve it.
models.py
from django.db import models
class Item(models.Model):
product = models.CharField(max_length=150)
quantity = models.DecimalField(max_digits=8, decimal_places=3)
price = models.DecimalField(max_digits=7, decimal_places=2)
purchase_date = models.DateTimeField()
warranty = models.DecimalField(max_digits=4, decimal_places=1)
comment = models.TextField()
forms.py
from django import forms
from items.models import Item
class EditItemForm(forms.ModelForm):
class Meta:
model = Item
fields = ('product','quantity', 'price', 'purchase_date', 'warranty', 'comment')
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^show_all/$', 'items.views.items'),
url(r'^(?P<item_id>\d+)/$', 'items.views.item'),
url(r'^edit/(?P<item_id>\d+)/$', 'items.views.edit'),
)
edit.html
<form action="/items/edit/" method="post" class="form horizontal well">{% csrf_token %}
{{ form.as_p }}
<imput type="submit" class="btn btn-inverse" value="Aktualizuj">
</form>
views.py
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from items.models import Item
from decimal import Decimal
from django.core.context_processors import csrf
from items.forms import EditItemForm
def edit(request):
if request.method == 'POST':
form = EditItemForm(request.POST, instance=request.item)
if form.is_valid():
form.save()
return HttpResponseRedirect('/items/show_all/')
else:
form = EditItemForm(instance=item)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('edit.html', args)
Above code is resulting this message:
TypeError at /items/edit/1/
edit() got an unexpected keyword argument 'item_id'
Can you please help me?
Django 1.6, Python 3.4
You've imagined an attribute called request.item. There's no such thing. You need to get the item from the database, via the ID passed into the function as alecxe showed.
def edit(request, item_id):
item = Item.objects.get(pk=item_id)
if request.method == 'POST':
form = EditItemForm(request.POST, instance=item)
edit() view should allow a keyword argument item_id:
def edit(request, item_id=None):
if request.method == 'POST':
...