I have a models in models.py
class Page(models.Model):
url = models.CharField(verbose_name="url", unique=True, db_index=True, max_length=255)
template = models.ForeignKey(Template)
class PageToBlock(models.Model):
page = models.ForeignKey(Page)
placeholder = models.ForeignKey(Placeholder)
block = models.ForeignKey(Block,null=True)
and some code in views
PTBFormSet = inlineformset_factory(models.Page, models.PageToBlock, extra=0, can_delete=False)
formset = PTBFormSet(instance=page)
for form in formset:
# i need initial here for processing
print form.fields['placeholder'].initial #print None!, but in final rendered form it has value
How to extract initial?
form.initials['placeholder'] works fine
Related
I need to update the model according to the marked checkboxes in the django shape
How can I get only some of the table fields in a query
the "checked" line should be updated through the queryset
models.py
class moIn(models.Model):
date = models.DateTimeField(auto_now_add=True, verbose_name='')
dateUpdate = models.DateTimeField(auto_now=True)
ts = models.IntegerField(verbose_name='')
pl = models.IntegerField(verbose_name='')
rem = models.IntegerField(verbose_name='')
comment = models.TextField(max_length=200, verbose_name='', blank=True)
staffer = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='')
checked = models.BooleanField(verbose_name='', default=False)
checkedUser = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='', blank=True, null=True, related_name='checkedUser')
by clicking this checkbox, you will need to receive database records
forms.py
class checkForm(ModelForm):
checked = fields.BooleanField(required=False)
class Meta:
model = moIn
fields = {"id", "checked"}
views.py
def dashboard(request):
if request.user.groups.filter(name='DashBoardAccess').exists():
form = checkForm
f = tableDashFilter(request.GET, queryset=moIn.objects.all())
if request.method == 'POST':
form = checkForm(request.POST)
if form.is_valid():
tt = form.save(commit=False)
data = form.cleaned_data
field = data['checked']=True
f.qs.filter(checked=field).update(checked=True, checkedUser=request.user)
return HttpResponse('ok')
else:
context = {
'filter': f,
'form': form
}
return render(request, 'dashboard/index.html', context)
else:
raise Http404()
in a line in bold, you need to get only those lines in which the checkbox is marked
f.qs.filter(checked=field).update(checked=True, checkedUser=request.user)
You can get all the fields using ".values ()" for the queryset, and to use it with foreignKey, you need to explicitly specify the model fields:
f = tableDashFilter(request.GET, queryset=moIn.objects.values('id','date','ts','pl','rem','comment','checked','staffer__username','checkedUser__username'))
"Value" from the input, it is also going to be obtained through:
Since there can be several values (marked checkboxes), there will be a ".getlist"
checkID = request.POST.getlist('checked')
querySet filter:
f.qs.filter(id__in=checkID).update(checked=True, checkedUser=request.user)
in the html template through the loop, iterate over and insert into the input value of the model id
Hi im following the tango with django tutorial.. I've searched for a solution to this but nothing!
the error:
IntegrityError at /rango/add_category/
UNIQUE constraint failed: rango_category.name
my model:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category) #ForeignKey denotes a relationship between page and category
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
my add_category view:
def add_category(request):
# Get the context from the request.
context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
#Have we been provided with a valid form?
if form.is_valid():
#save the new category to the database
form.save(commit=True)
# Now call the index() view.
# The user will be shown the Homepage.
return index(request)
else:
# The supplied form contained errors - just print them to the terminal
print (form.errors)
else:
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error message(if any).
return render_to_response('rango/add_category.html', {'form':form}, context)
my forms:
from django import forms
from rango.models import Page, Category
class CategoryForm(forms.ModelForm):
names = forms.CharField(max_length=128, help_text="please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
#an inline class to to provide additional information on the form
class Meta:
# provide an association between the Modelform and a model
model = Category
fields = ('views', 'likes')
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page")
url = forms.URLField(max_length=200, help_text="Please enter the url of the page")
views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
#what fields do we want to include in our form
# this way we dont need every field in the model present
# Some fields may allow NULL values, so we may not want to include them...
# Here we are hiding.
fields = ('title', 'url', 'views')
'name' field is missing in CategoryForm's Meta 'fields'. Since Category::name is a unique field and default is not possible, any attempt to save will fail.
If the model does not allow the missing fields to be empty, and does
not provide a default value (not possible for unique) for the missing fields, any attempt to save() a ModelForm with missing fields will fail.
Can someone say, how create such form as in the picture below in Django?
I have model Product with field is_visable. In form I want to show all products with field is_visable. User can select checkboxes and change the value of is_visable field. In other words make products visable or invisable. I am thing about MultipleChoiceField in my form but not sure is it correct in my case.
models.py:
class Product(models.Model):
symbol = models.CharField(_('Symbol'), max_length=250)
name = models.CharField(_('Name'), max_length=250)
is_visible = models.BooleanField(default=False)
forms.py:
class ProductForm(forms.ModelForm):
product = forms.ModelChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Product.objects.all())
views.py:
if request.method == 'POST':
form = ProductForm(data=request.POST)
if form.is_valid():
ids = form.cleaned_data.get('product') # Example: ['pk', 'pk']
for id in ids:
product = Product.objects.get(pk=id)
product.is_visible = True
product.save()
I think what you want to use is a ModelChoiceField in your form with a widget of CheckboxSelectMultiple.
A queryset for the ModelChoiceField is a required argument, so you can build the queryset like this:
visible_products = Product.objects.filter(is_visible=True)
product_field = forms.ModelChoiceField(queryset=visible_products,
widget=CheckboxSelectMultiple()
See this post for more details:
Django ChoiceField populated from database values
I have been searching up and down and I can't seem to find the right answer.
I have been playing around with django and with my test project and I can't figure out how to implement this, I am trying to display dropdown contents dynamically based on foreign key from my views
Here is my sample views:
def job_display(request):
job_list = Job_Posting.objects.filter(Publication_Status="A", Available_Slots__gt=0).order_by('-Urgency_Status', '-Date_Modified')
context = {'job_list': job_list}
return render(request, 'frontend/home.html', context)
def save_page(request, job_id):
jreq = get_object_or_404(Job_Posting, fkey=job_id)
form = application_form(request.POST)
if request.method == 'POST':
.....
else:
.....
return render(request, 'frontend/apply.html ... )
My urls:
urlpatterns = patterns('',
url(r'^$', views.job_display, name='job_display'),
url(r'^(?P<job_id>[0-9]+)/apply$', views.save_page, name='save_page'),
)
My froms:
class edbackgound(ModelForm):
COURSE = forms.ModelChoiceField(queryset=Educational_Requirement.objects.all())
my models:
class Course_Selection(models.Model):
Course = models.CharField(max_length=30, unique=True)
Abbreviation = models.CharField(max_length=100, unique=True)
class Job(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
class Job_Posting(models.Model):
fkey = models.OneToOneField(Job, verbose_name="Job Positions")
....
class Educational_Requirement(models.Model):
fkey = models.OneToOneField(Job_Posting, verbose_name="Job Positions")
Ed_req = models.OneToOneField(Course_Selection, verbose_name = 'Educational Requirement')
def __unicode__(self):
return self.Ed_req
My problem is displaying the choices in modelform, in my views I can get the currently selected job_list through save_page's jreq via jreq.fkey where I can just get it's Job_position then save my form. How can I populate my form's ModelChoiceField through my selected job_list.
If my post is not clear, please, feel free to comment what my post lacks
EDIT
I have found out that you can set your queryset via views like this:
form.fields['COURSE'].queryset = Educational_Requirement.objects.filter(fkey=jreq.fkey_id)
My problem with that is I am using an inlineformset_factory to generate my fields dynamically, and if I do this:
for form in myinlineform:
form.fields['COURSE'].queryset = Educational_Requirement.objects.filter(fkey=jreq.fkey_id)`
I am raising an error that says: [u'ManagementForm data is missing or has been tampered with']
Make sure you have included the management form for your inline formset in your template:
{{ my_formset.management_form }}
Read more on it here: https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform
models.py:
class Tag(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=500, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
user = models.ForeignKey(User)
tag = models.ManyToManyField(Tag)
title = models.CharField(max_length=100)
content = models.TextField()
created = models.DateTimeField(default=datetime.datetime.now)
modified = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return '%s,%s' % (self.title,self.content)
class PostModelForm(forms.ModelForm):
class Meta:
model = Post
class PostModelFormNormalUser(forms.ModelForm):
class Meta:
model = Post
widgets = { 'tag' : TextInput() }
exclude = ('user', 'created', 'modified')
def __init__(self, *args, **kwargs):
super(PostModelFormNormalUser, self).__init__(*args, **kwargs)
self.fields['tag'].help_text = None
what i tried in views.py: (that doesn't look the correct way)
if request.method == 'POST':
form = PostModelFormNormalUser(request.POST)
print form
print form.errors
tagstring = form.data['tag']
splitedtag = tagstring.split()
if form.is_valid():
temp = form.save(commit=False)
temp.user_id = user.id
temp.save()
post = Post.objects.get(id=temp.id)
l = len(splitedtag)
for i in range(l):
obj = Tag(name=splitedtag[i])
obj.save()
post.tag.add(obj)
post = Post.objects.get(id=temp.id)
return HttpResponseRedirect('/viewpost/' + str(post.id))
else:
form = PostModelFormNormalUser()
context = {'form':form}
return render_to_response('addpost.html', context, context_instance=RequestContext(request))
Can anyone post example complete code editing this to save into Post table, Tag table and post_tag table?
The input form will contain a textbox to type 'title' and texarea for 'content' and a textbox to type 'tag' as string. The tag string is seperated by space. I need to save those tag words into Tag table and map in post_tag table.
How can i do this?
In the Django docs regarding ModelForms and save(commit=False), you'll find information regarding the save_m2m() method. I believe that is what you're looking for.
As an aside, if you're implimenting tagging, you could just use django-tagging or django-taggit
http://code.google.com/p/django-tagging/
http://django-taggit.readthedocs.org/en/latest/index.html
http://djangopackages.com/grids/g/tagging/