I have a model.py:
class Author(models.Model):
Author= models.CharField(max_length=500) ##field required
and a form.py:
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
widgets = {
'Author': TextInput(attrs={'class':'form-control', 'placeholder': 'Author...'}),
in template I render whit:
{{ form.Author }}
Form works but if I try to save leave the field empty it not display any error.
I try with
{{ form.Author.errors }}
but nothing appear!
Any idea?
TY
UPGRADE 1
simple view:
#login_required
def auth_reg(request):
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
member = form.save()
return redirect('home')
else: form = AuthorForm()
return render(request, auth_reg.html', {'form': form})
and simple template:
{% extends 'base.html' %}
{% block content %}
<div id="page-content-wrapper">
<form method="post">
{% csrf_token %}
<div id="page-title">
<h2>Registration</h2>
</div>
<div class="content-box-wrapper">
<div class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">Author</label>
<div class="col-sm-3">
{{ form.Author}}
</div>
</div>
</div>
</div>
</div>
Related
I am new at Django I want some helps. Basically,I want from users that they can select multiple images and save it, but I got like this and I don't know how to do it. I want to display the images and user can select one of them.
please help me.
models.py
class Images(models.Model):
product_image=models.ImageField(upload_to='media',null=True, blank=True)
def __str__(self):
return "{}".format (self.product_image)
class user_select(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
product_image=models.ForeignKey(Images, on_delete=models.CASCADE)
def __str__(self):
return "{}".format (self.name)
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = user_select
fields = '__all__'
views.py
def home(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'home.html', {'form':form})
home.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-5">
<div class="row mt-5 mr-5">
<div class="col-md-8 mt-5">
<div class="card border border-secondary mt-5">
<div class="col-md-8 mt-5" align='center'>
<form method="POST" action="" >
{% csrf_token %}
<div class="col-md-8">
{{ form|crispy }}
</div>
</form>
<button type="submit" class="btn btn-success mt-5 mb-5">Place Order</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
enter image description here
Good morning guys, I have a problem with a form.
My code:
models.py
class AnagraficaGenerale(models.Model):
ragionesociale = models.CharField(max_length=40, null=True, blank=True)
cf = models.CharField(max_length=40, null=True, blank=True)
piva = models.CharField(max_length=40, null=True, blank=True)
forms.py
class AnagraficaGeneraleForm(forms.ModelForm):
class Meta:
model = AnagraficaGenerale
fields = '__all__'
views.py
#login_required
def anagrafica_new(request):
if request.method == "POST":
form = AnagraficaGeneraleForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('anagrafica_list')
else:
form = AnagraficaGeneraleForm()
return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form})
html
{% extends 'FBIsystem/basenobar.html' %}
{%load staticfiles %}
{% block content %}
<div id="page-wrapper">
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
Nuova Anagrafica
</h3>
<form method="POST" class="form-horizontal bordered-row">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
<label class="col-sm-2 control-label" > Ragione Sociale:</label>
<div class="col-sm-6">
{{ form.ragionesociale }}
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</form>
</div>
</div>
</div>
{% endblock %}
Everything seems ok but not save, if I try with {{form.as_table}} it save.
I think there is a problem with custom field but I don't know how.
whats wrong?
TY
I have a problem in my Django form. When I click the submit button in my form, no data is saved to the database. I found that the data was bound but it did not pass through the form.is_valid() function. Below is the code for forms.py, views.py, urls.py and new-event.html respectively:
forms.py
from django import forms
class EventForm(forms.Form):
name = forms.CharField(label='event-name',
max_length=50,
widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'event-name', 'name': 'event-name'}))
start_datetime = forms.DateTimeField(
widget=forms.DateTimeInput(attrs={'class': 'form-control', 'id': 'start-datetime', 'name': 'start-datetime', 'type': 'datetime-local'}))
end_datetime = forms.DateTimeField(
widget=forms.DateTimeInput(attrs={'class': 'form-control', 'id': 'end-datetime', 'name': 'end-datetime', 'type': 'datetime-local'}))
event_category = forms.ChoiceField(widget=forms.Select(attrs={'class': 'custom-select', 'id': 'event-type'}),
choices=((None, 'Please select an option'), ('Daily Life', 'Daily Life'), ('Study', 'Study'), ('Social', 'Social'), ('Work', 'Work')))
description = forms.CharField(max_length=250, widget=forms.Textarea(attrs={'class': 'form-control', 'id': 'description', 'name': 'description'}), required=False)
views.py
from django.shortcuts import render, redirect
from .models import Entry
from .forms import EventForm
from django.views.decorators.http import require_POST
# request is required that represents HttpResponse
# return value can be response, JSON or template
def index(request):
entries = Entry.objects.order_by('-date_added')
context = {'entries': entries}
return render(request, 'event/list-events.html', context)
def new_event(request):
form = EventForm()
context = {'form': form}
return render(request, 'event/new-event.html', context)
#require_POST
def add_event(request):
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_bound: print('form is bound')
else: print('form is unbound')
if form.is_valid():
print('form is valid')
new_entry = Entry(name=form.cleaned_data['name'], start_datetime=form.cleaned_data['start_datetime'],
end_datetime=form.cleaned_data['end_datetime'], category=form.cleaned_data['event_category'],
description=form.cleaned_data['description'])
new_entry.save()
else:
print('form is invalid')
return render(request, 'event/new-event.html', {'form': form})
return redirect('index')
# else:
# form = EventForm()
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('new-event/', views.new_event, name='new_event'),
path('add-event/', views.add_event, name='add_event')
]
new-event.html
{% extends 'todo/base.html' %}
{% block title %}New Entry{% endblock %}
{% block content %}
<form action="{% url 'add_event' %}" method="POST" class="container-fluid">
{% csrf_token %}
<div class="form-group row">
<label for="event-name" class="col-sm-2 col-form-label">Event</label>
<div class="col-sm-10">
{{ form.name }}
</div>
</div>
<div class="form-group row">
<label for="event-type" class="col-sm-2 col-form-label">Event type</label>
<div class="col-sm-10">
{{ form.event_category }}
</div>
</div>
<div class="form-group row">
<label for="start-datetime" class="col-sm-2 col-form-label">Start Time</label>
<div class="col-sm-10">
{{ form.start_datetime }}
</div>
</div>
<div class="form-group row">
<label for="end-datetime" class="col-sm-2 col-form-label">End Time</label>
<div class="col-sm-10">
{{ form.end_datetime }}
</div>
</div>
<div class="form-group">
{{ form.description }}
</div>
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</form>
{% endblock %}
The output on my terminal is: form is bound form is invalid... I am sure that I do not fall into the confusion of concepts between bound and instance. Could anyone give me some tips on how this occurs?
I'm not sure why you think that this is a problem. Your form was correctly bound to the POST data; then, that data was validated, and found not to pass the validation.
To see why - and allow the user to correct the issue - you should output {{ form.errors }} on your template, or use the individual errors attributes for each field, eg {{ form.name.errors }} etc.
Im new with Django and Im trying to include my own form
My forms.py
class MyOwnForm(forms.ModelForm):
class Meta:
model = Album
fields = ['username']
My views.py
def testing_Form(request):
if not request.user.is_authenticated:
return render(request, 'login.html')
else:
form = MyOwnForm(request.POST or None)
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
username = form.cleaned_data['username']
return render(request, 'form.html', {'form': form})
my form.html
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
and the last one form_template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2" >{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
When I open the Form Webpage, I get a empty entry field and the submit button. But when I click this button. The page is reloading and nothing more.
what do i have to do that i can work with the entered data?
But when I click this button. The page is reloading and nothing more.
Because of this, I'm assuming that you intend to show some information after the form is submitted. Here's a simple example that just displays an acknowledgement after the form is submitted.
{% if submitted %}
<div class="jumbotron contactainer">
<h1 class="display-4">Submitted</h1>
<hr class="my-4">
<p class="lead">{{ username }}'s album has been submitted</p>
</div>
{% else %}
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
{% endif %}
views.py
def testing_Form(request):
submit = False
if not request.user.is_authenticated:
return render(request, 'login.html')
else:
form = MyOwnForm(request.POST or None)
if form.is_valid():
album = form.save(commit=False)
album.username = request.user
album.save()
submit = True
username = form.cleaned_data['username']
return render(request, 'form.html', {'username':username, 'submitted':submit})
else:
return render(request, 'form.html', {'form': form, 'submitted':submit})
You can do anything you wish with the username variable or add new variables, just remember to add them to the context dictionary if you wish to display them. The submit variable I've added is used in the template to determine what to show. Hope this helps :)
Not quite sure what you are exactly trying to achieve. However if you want to show the value of your previous submit on your screen for example as: Previous submitted username: <input username>, you can use the defined form in your template, including the values if there was a submit before.
{% if form.username.value %}
Previous submitted username: {{ form.username.value }}
{% endif %}
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{# ... all as it was ... #}
</form>
You can always add extra context to your template by assigning it to the context dictionary in the similar way you did with the {'form': form} as {'form': form, 'hello': "My hello string"} in your view.
In your template you could now use {{ hello }} as an variable.
Note that you are also using commit=False in your form to add more request data to the model after (user). Currently you left it in the unsaved state. To save the new form entry, you need to call album.save() after the modifications.
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
album.save() # now commit
The username = form.cleaned_data['username'] has been defined, but never been used. Which with the example above is no longer required.
You can fetch the album objects when the user is authenticated and pass them to the template to work with as context like:
(bad practice style, but just to give you an idea within the scope of your code)
if request.user.is_authenticated:
return render(request, 'login.html')
else:
form = AlbumForm(request.POST or None)
if form.is_valid():
album = form.save(commit=False)
album.user = request.user
albums = Album.objects.all()
return render(request, 'formhandle/form.html', {'form': form, 'albums': albums})
Which you could show in your form template as:
{% if form.username.value %}
Previous submitted username: {{ form.username.value }}
{% endif %}
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{# ... all as it was ... #}
</form>
<ul>
{% for album in albums %}
<li>{{ album.user.username }}</li>
{% endfor %}
</ul>
I have started learning django, but I can't understand how to render form.
This is form.py I have made.
from django import forms
class TweetForm(forms.Form):
text = forms.CharField(widget = forms.Textarea(attrs = {'rows' : 1, 'cols' : 85}), max_length = 160)
country = forms.CharField(widget = forms.HiddenInput())
This is code snippet in views.py.
from .forms import TweetForm
class Profile(View):
def get(self, request, username):
params = dict()
user = User.objects.get(username = username)
tweets = Tweet.objects.filter(user = user)
params["user"] = user
params["tweets"] = tweets
form = TweetForm
return render(request, 'profile.html', {'params' : params, 'form' : form})
This is html file and it must render form I have made.
{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
<div class="col-md-12 column">
<form method="post" action="post/">
{% csrf_token %}
<div class="col-md-8 col-md-offset-2 fieldWrapper">
{{ form.text.errors }}
{{ form.text }}
</div>
{{ form.country.as_hidden }}
<div>
<input type="submit" value="post">
</div>
</form>
</div>
<h3> </h3>
<div class="col-md-12 column">
{% for tweet in tweets %}
<div class="well">
<span>{{ tweet.text }}</span>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
When I issue command(run server), browser don't render form without any exception.
I think there is a problem in views.py file, But I can't find it.
How can I send form parameter to Template(.html file) and render form in result?
You didn't instantiate the form.
You need to instantiate the form, for rendering in a template, like this,
form = TweetForm()
Note:
The params variable is already a dict(), you could just add form into the params like this,
params['form'] = form
Then, render the template with context as params,
render(request, 'profile.html', params)