I was reading django docs and found the add_fields method.
The documentation says:
"If you need to add additional fields to the formset this can be
easily accomplished. The formset base class provides an add_fields
method."
I want to use it but there is no example or explanation how
it can be used in views and templates. Can you provide me a small
example of using this method?
I will give a small example.
The models.py looks like this,
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
forms.py looks like this,
from django import forms
from django.forms import BaseFormSet
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title']
class BaseArticleFormSet(BaseFormSet):
def add_fields(self, form, index):
super().add_fields(form, index)
form.fields['body'] = forms.CharField()
views.py looks like this,
from django.shortcuts import render
from django.forms import formset_factory
from .forms import ArticleForm, BaseArticleFormSet
def home(request):
ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, extra=3)
context = dict()
formset = ArticleFormSet()
if request.method == 'POST':
formset = ArticleFormSet(request.POST)
if formset.is_valid():
print(formset.cleaned_data)
context['formset'] = formset
return render(request, 'home.html', context)
Finally, home.html will look like this,
<form method="post">
{% csrf_token %}
<table>
{{ formset }}
</table>
<button type="submit">submit</button>
</form>
As you can see, the body field appears in templates but it is not included in the the Article model.
Hope that helps!
Related
i am a beginner django developer, "ModelForm has no model class specified. " is given on my project , what i can do pls help, i will be greatfull to you if you solve my problem
models.py
from django.db import models
class product(models.Model):
name = models.CharField(max_length=50)
forms.py
from django.forms import ModelForm
from .models import product
class productform(ModelForm):
class Meta:
model:product
fields: '__all__'
views.py
from django.shortcuts import render
from formt.forms import productform
def index(request):
form = productform()
context = {
'form' : form
}
return render(request, 'index.html' , context )
index.html
<h1>form model</h1>
<form action="">
{% csrf_token %}
{{form}}
<input type="submit" text="submit">
</form>
forms.py
class ProductForm(ModelForm):
class Meta:
model = Product
fields = '__all__'
views.py
from .forms import ProductForm
Look at your syntax.
Class names should start with a capital letter.
class ProductForm(ModelForm):
class Meta:
model = Product
fields: '__all__'
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".
I have a small problem with adding data to the database in django 2.0.3
I created the following model:
from django.contrib.auth.models import User
class UserInputSignal(models.Model):
name = models.CharField(max_length=512)
author = models.ForeignKey(User, on_delete=models.CASCADE)
input_file = models.FileField(upload_to='signals/', null=True)
I tried to solve the problem using this form:
from django import forms
from .models import UserInputSignal
class UserInputSignalForm(forms.ModelForm):
name = forms.CharField()
input_file = forms.FileField()
class Meta:
model = UserInputSignal
fields = ('name', 'input_file', )
and this view:
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate
from .forms import UserInputSignalForm
#login_required
def storage(request):
form = UserInputSignalForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
name = request.POST.get('name')
author = request.POST.get(request.user)
input_file = request.POST.get('input_file')
return redirect('home')
else:
form = UserInputSignalForm()
return render(request, 'storage.html', {'form': form})
In the template I called, I created the form as follows:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
I am able to load a page with a form, but it does not post data to the database. I would like to add that I am a novice in django and some mechanisms are just plain understandable for me. Can I ask someone for help with this problem?
Before the redirect, call form.save()
Okay, i worked on your code and it works with me with slight modifications:
models.py
class UserInputSignal(models.Model):
name = models.CharField(max_length=512)
author = models.ForeignKey(User, on_delete=models.CASCADE)
input_file = models.FileField(upload_to='signals/', null=True)
objects = models.Manager()
#this returns the name for your modelobject
def __str__(self):
return self.name
forms.py
#excluded the assiging as fields defination is enough in itself
class UserInputSignalForm(forms.ModelForm):
class Meta:
model = UserInputSignal
#this will exclude the formfield it self but the author will be saved as the person who is logged in
exclude = ["author"]
Edited - Views.py
#login_required
def storage(request):
#authentication for author field using request.user
insta = UserInputSignal(author=request.user)
print(request.user)
form = UserInputSignalForm(request.POST or None, request.FILES or None,instance=insta)
if request.method == 'POST':
if form.is_valid():
signal = form.save(commit=False)
signal.save()
return redirect('home')
else:
form = UserInputSignalForm(instance=insta)
return render(request, 'storage.html', {'form': form})
JlucasRs was right to tell you to use form.save(), but you needed to assign form to something and need not use model fields here as forms.py does that for you.
app/Urls.py - Just for reference
urlpatterns = [
path('home/', home, name='home'),
path('storage/', storage, name='storage'),
]
Edit- Admin.py
from .models import PostModel, UserInputSignal
class UserInputSignalAdmin(admin.ModelAdmin):
list_display = ('name', 'author', 'input_file' )
admin.site.register(UserInputSignal, UserInputSignalAdmin)
Add this code in Admin.py if its not there.
In a Django 1.9 online learning app, I have a form that I am making using the generic class-based view CreateView as wells as some other mixins. In the form the 'owner' is able to create a new course, but upon form submission I get the following error:
IntegrityError at /course/create/
NOT NULL constraint failed: courses_course.owner_id
I realize that I am getting the error, because the form isn't saving the owner, which is part of the Course model. And I know the owner isn't saving because the app is not even entering my form_valid method in OwnerEditMixin class. (My console is not printing the form validating ... message in the method.)
Here is the code from my view:
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import CreateView
from .models import Course
from django.contrib.auth.mixins import LoginRequiredMixin, \
PermissionRequiredMixin
class OwnerMixin(object):
def get_queryset(self):
qs = super(OwnerMixin, self).get_queryset()
return qs.filter(owner=self.request.user)
class OwnerEditMixin(object):
def form_valid(self, form):
print('form validating ...')
form.instance.owner = self.request.user
return super(OwnerEditMixin, self).form_valid(form)
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
model = Course
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin):
fields = ['subject', 'title', 'slug', 'overview']
success_url = reverse_lazy('manage_course_list')
template_name = 'courses/manage/course/form.html'
class CourseCreateView(OwnerCourseEditMixin, CreateView,
PermissionRequiredMixin):
permission_required = 'courses.add_course'
The relevant template code is here:
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Save course"></p>
</form>
Any ideas for why the class-based view isn't calling my form_valid method?
PS: I followed the example for class-based views form validation from https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user
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':
...