I'm building a dynamic formset based on the dynamic-formset jquery plug-in: I've constructed an alpha model that works except that it doesn't commit data from any of the fileupload fields to the database. Have I blown my formset view function?
#forms.py
class PostEntryForm(ModelForm):
class Meta:
model = PostEntry
ContactFormset = formsets.formset_factory(PostEntryForm)
#models.py
class PostEntry(models.Model):
client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
job_number = models.CharField(validators=[RegexValidator(regex='^\w{8}$', message='Please enter a valid job number', code='nomatch')], max_length=8, unique=False, blank=False, null=False)
cell_number = models.CharField(max_length=4, unique=False, blank=True, null=True)
post_title = models.CharField(max_length=64, unique=False, blank=True, null=True)
date = models.DateField(("Date"), default=datetime.date.today)
post_type = models.CharField(max_length=64, choices=POST_CHOICES)
post_round = models.CharField(max_length=20, blank=False, null=False)
docfile = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
url_link = models.URLField(blank=True, null=False, max_length=300)
misc_link = models.CharField(max_length=64, blank=True, null=True)
link_misc = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
misc_link2 = models.CharField(max_length=64, blank=True, null=True)
link_misc2 = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
mobile_view_url = models.URLField(validators=[RegexValidator(regex='^(http|https)://', message='url must begin with http or https', code='nomatch')], blank=True, null=False, max_length=300)
link_pdf = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
link_html = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
link_report = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
link_text = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
link_zip = models.FileField(upload_to=content_file_name, blank=True, null=True, max_length=300)
def __unicode__ (self):
return u'%s %s %s %s %s' % (self.client, self.job_number, '-', self.cell_number, self.post_title)
def save(self, force_insert=False, force_update=False):
self.job_number = self.job_number.upper()
self.cell_number = self.cell_number.upper()
super(PostEntry, self).save(force_insert, force_update)
class Meta:
ordering = ['-date', 'cell_number']
class Admin:
pass
#views.py
def formset(request, formset_class, template):
if request.method == 'POST':
formset = formset_class(request.POST, request.FILES)
if formset.is_valid():
for form in formset.forms:
form.save()
return HttpResponseRedirect('/main')
else:
formset = formset_class()
return render_to_response(template, {'formset': formset},
context_instance=RequestContext(request))
If it's not sending just your fileupload, I guess it could be a missing enctype attribute on your form.
So, try to do this:
<form action="" method="POST" enctype="multipart/form-data">
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
</form>
Related
I have a product update form where I want to update the sizes of a product, with a many-to-many column relation.
I am able to get the saved values but I can't get item ID or size.
{{item.id}} shows empty value.
{% for item in form.size.value %}
<span>
<input type="checkbox" name="size" id="{{ item.id }}" value="{{ item.id }}">
<label for="{{ item.id }}">{{ item }}</label>
</span>
{% endfor %}
SIZE MODEL
class Size(models.Model):
identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
size = models.CharField(max_length=200, unique=True, null=False, blank=False)
active = models.BooleanField(default=True)
date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True)
date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True)
PRODUCT MODEL
class Product(models.Model):
identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=200, null=False, blank=False)
slug = models.SlugField(max_length=30, unique=True)
showcased = models.BooleanField(default=False)
recommended = models.BooleanField(default=False)
active = models.BooleanField(default=True)
price = models.DecimalField(max_digits = 5, decimal_places = 2, null=True, blank=True)
pagetitle = models.CharField(max_length=200, null=True, blank=True)
shortDescription = models.CharField(max_length=200, null=True, blank=True)
longDescription = HTMLField(null=True, blank=True)
specifications = models.TextField(null=True, blank=True)
features = models.TextField(null=True, blank=True)
care = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
subCategory = models.ForeignKey(SubCategory, null=True, blank=True, on_delete=models.PROTECT)
image = models.ManyToManyField(Image, blank=True)
size = models.ManyToManyField(Size, blank=True)
tag = models.ManyToManyField(Tag, blank=True)
date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True)
date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True)
I have tried different ways but not had success in getting the name or id
def updateProduct(request, pk):
categories = Category.objects.all()
sizes = Size.objects.all()
tags = Tag.objects.all()
product = Product.objects.get(id=pk)
subCategories = SubCategory.objects.filter(category=product.category.id)
images = product.image.all()
if request.method == 'POST':
form = ProductForm(request.POST, instance=product)
if form.is_valid():
form.save()
return redirect('product-panel')
form = ProductForm(instance=product)
return render(request, 'public/views/backend/product-update.html', {'categories':categories,'subCategories':subCategories, 'sizes':sizes, 'tags':tags, 'form':form, 'images':images})
I am making a app for one kindergarten in my city. I have kids model and payment model.
For updating kid I am using class based view generic UpdateView and for creating a payment i am using form and function view. I have not problems with payment form when I am using a different template but when I try to put it on the same template, payment form is not showing up and it's not working. Is it possible to have payment form on same template as UpdateView class ? I am using UpdateView class as profile page and I would like to have payment form on the same page. Please help. Thanks
models:
class Kids(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
city_birthday = models.CharField(max_length=100, blank=True, null=True)
custom_id = models.CharField(max_length=100 ,blank=True, null=True)
gender = models.CharField(max_length=100, choices=gender_choices, null=True, blank=True)
address = models.CharField(max_length=250, null=True, blank=True)
contact_phone = models.CharField(max_length=100, blank=True, null=True)
family_size = models.IntegerField(null=True, blank=True)
living_with = models.CharField(max_length=100, choices=living_choices, null=True, blank=True)
number_of_preschool_kids_in_family = models.IntegerField(null=True, blank=True)
kid_already_been_in_kindergarten = models.CharField(max_length=100, choices=preschool_choices,
null=True, blank=True ,default=False)
father_name = models.CharField(max_length=100, blank=True, null=True)
father_education_level = models.CharField(max_length=200, blank=True, null=True)
father_company = models.CharField(max_length=200, blank=True, null=True)
mother_name = models.CharField(max_length=100, blank=True, null=True)
mother_education_level = models.CharField(max_length=200, blank=True, null=True)
mother_company = models.CharField(max_length=200, blank=True, null=True)
parent_notes = models.CharField(max_length=500, blank=True, null=True)
program_choice = models.CharField(max_length=100, choices=kindergarten_program_choice, null=True,
blank=True)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
class Payment(models.Model):
user = models.ForeignKey(Kids, on_delete=models.CASCADE, blank=True, null=True)
bank_paper_id = models.IntegerField(null=True, blank=True)
payment_date = models.CharField(max_length=100, null=True, blank=True)
paid = models.FloatField(null=True, blank=True)
need_to_pay = models.FloatField(null=True, blank=True)
notes = models.CharField(max_length=500, blank=True, null=True)
def __str__(self):
return self.user.name
views:
class UpdateKidView(UpdateView):
model = Kids
fields = '__all__'
template_name = 'vrtic/update_kid.html'
success_url = reverse_lazy('vrtic:kids')
def create_payment(request, pk):
kid = Kids.objects.get(id=pk)
payment_form = PaymentForm()
if request.method == 'POST':
payment_form = PaymentForm(request.POST)
if payment_form.is_valid():
payment = payment_form.save(commit=False)
payment.user = kid
payment_form.save()
return redirect('vrtic:kids')
context = {
'payment_form': payment_form,
'kid': kid
}
return render(request, 'vrtic/update_kid.html', context)
form:
class PaymentForm(forms.ModelForm):
class Meta:
model = Payment
fields = '__all__'
class UpdateKidView(UpdateView):
model = Kids
form_class = KidsForm
second_form_class = PaymentForm
template_name = 'vrtic/update_kid.html'
success_url = reverse_lazy('vrtic:kids')
def get_context_data(self, **kwargs):
context = super(UpdateKidView, self).get_context_data(**kwargs)
context['form'] = self.form_class(instance=self.get_object())
context['second_form'] = self.second_form_class()
return context
def post(self, request, **kwargs):
kids_form = self.form_class(request.POST, request.FILES, instance=self.get_object())
if kids_form.is_valid():
kid = kids_form.save()
payment_form = self.second_form_class(request.POST)
...
Not the happiest solution, but u got the idea, if need more help contact me to explain on Serbian, not sure how are the rules here for languages : )
I'm trying to add extra content to Djangos Class-based view to the template
I have some models like this
class District(models.Model):
district = models.CharField(max_length=255, null=False, unique=False, blank=True)
def __str__(self):
return self.district
class Street(models.Model):
street_name = models.CharField(max_length=255, null=False, unique=False, blank=True)
district = models.ForeignKey(District, verbose_name=_('district'), on_delete=models.CASCADE, null=True, blank=True)
zone = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.street_name
class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL)
timestamp = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=1, choices=STATUS, default=CREATED)
comment = models.CharField(max_length=255, null=True, unique=False, blank=True)
name = models.CharField(max_length=255, null=True, unique=False)
street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True)
class ArticlesListView(LoginRequiredMixin, PermissionRequiredMixin,ListView):
model = Article
paginate_by = 50
context_object_name = "articles"
permission_required = 'is_staff'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['Filter_name'] = Article.objects.order_by().values('name').distinct()
context['Filter_user'] = Article.objects.order_by().values('user').distinct()
return context
def get_queryset(self, **kwargs):
return Article.objects.all()
And late in the template
{% for f in Filter_name %}
<ul>
<li>{{f.name}}</li>
</ul>
{% endfor %}
How can I display a list of the district names and a list of the author names in the template with ForeignKey?
U can try something like that
{% for item in model_1.foreign_model_set.all %}
<h1>{{ item }}</h1>
{% endfor %}
I'm using a ModelForm to load a Form and all of the values are pulling properly except the checkboxes. They always load in unchecked whether or not their state is True or False.
I've tried creating the checkbox fields like:
<label>
<input type="checkbox" checked='{{ form.instance.hot }}'>
<span>Hot{{ form.hot }}</span>
</label>
<li>CSR: {{ form.csr }}</li>
{% if request.user|has_group:"Customer Service Manager" %}
<li>Documents: {{ form.documents }}</li>
{% endif %}
<li>Notes: {{ form.notes }}</li>
<li>First Name:{{ form.first_name }}</li>
<li>Last Name: {{ form.last_name }}</li>
<li>Address: {{ form.address }}</li>
Which results in the checkbox always being checked instead matching what's in the table for that client.
models.Client
class Client(models.Model):
#Account Information
client_status =[("1", "Active"), ("0", "Inactive")]
WHOPAYS =[("0", "Not Applicable"), ("1", "They Pay"), ("2", "We Pay")]
hot = models.BooleanField(default=False, required=False)
region = models.ForeignKey('Region', to_field='region_id', on_delete=None, null=True, blank=True)
sub_account = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub_account_of_client', null=True, blank=True)
created = models.DateField('Account Creation', auto_now_add=True)
client_class = models.ForeignKey('ClientClass', on_delete=None, null=True, blank=True)
category = models.ForeignKey('ClientCategory', on_delete=None, null=True, blank=True)
they_pay = models.BooleanField('They Pay', default = False, required=False)
we_pay = models.BooleanField('We Pay', default = False, required=False)
csr = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='extension', on_delete=None, blank=True, null=True, limit_choices_to= Q( groups__name = 'Customer Service'))
#Upload location /<ClientID>/documents/*
documents = models.FileField(null=True, blank=True, upload_to=client_directory_path)
notes = models.TextField(null=True, blank=True)
active_status = models.CharField('Status', max_length=1, choices=client_status, default="1")
client = models.CharField('Client/Company Name',max_length=200, null=True, blank=True)
account_number = models.CharField(max_length=50, null=True, blank=True)
#Contact Information
first_name = models.CharField('First Name', max_length = 200, null=True, blank=True)
last_name = models.CharField('Last Name', max_length = 200, null=True, blank=True)
email = models.EmailField(max_length = 254, null=True, blank=True)
main_phone = models.CharField(null=True, blank=True, max_length=50)
alt_phone = models.CharField(null=True, blank=True, max_length=50)
fax = PhoneField(null=True, blank=True)
follow_up = models.DateField('Date to Follow Up', default=three_days())
#Billing and Shipping Addresses
address = models.CharField('Address Line 1', max_length=200, null=True, blank=True)
address2 = models.CharField('Address Line 2', max_length=200, null=True, blank=True)
city = models.CharField('City', max_length=200, null=True, blank=True)
zipcode = models.CharField('Zip Code', max_length=200, null=True, blank=True)
state = models.CharField('State', max_length=2, null=True, blank=True, choices=STATE_CHOICES)
country = models.CharField('Country', max_length=200, null=True, blank=True, default='USA')
def __str__(self):
if self.sub_account:
return '{0}: Sub-Account for {1}'.format(self.client, self.sub_account)
else:
return '{0} - {1}'.format(self.client, self.zipcode)
views.client_view
def client_view(request):
FormSet = modelformset_factory(Client, form=ClientSheet, extra=0)
if request.method == 'POST':
formset = FormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save(commit=False)
formset.save()
return HttpResponseRedirect('/client/')
else:
query = Client.objects.filter(follow_up__lte=date.today(), csr__extension=request.user.extension).order_by('-hot')
currentcall = Client.objects.filter(follow_up__lte=date.today(), csr__extension=request.user.extension).order_by('-hot').first()
paginator = Paginator(query, 1) # Show 1 forms per page
page = request.GET.get('page')
try:
objects = paginator.page(page)
except PageNotAnInteger:
objects = paginator.page(1)
except EmptyPage:
objects = paginator.page(paginator.num_pages)
page_query = Client.objects.filter(id__in=[object.id for object in objects])
formset = FormSet(queryset=page_query)
context = {'objects': objects, 'formset': formset, 'callqueue': query, 'currentcall': currentcall}
return render(request, 'main/client.html', context)
Whenever Checkbox will always be checked as soon as you pass checked attribute.
Your template should look like
<input type="checkbox" {{ form.instance.hot|yesno:"checked,'',''" }}>
I am trying to make a formset of 3 foreign keys. Servicer, Sdescrition, and Stag. For some reason it is give me this error
ManagementForm data is missing or has been tampered with
I am pretty new at coding, if there is a better way than inlineform_factory please let me know and suggest. Thank you very much. I am pretty much trying to connect three foreign keys together put them into a single form page on the webpage. Once again, Thank you
Views.py
def home(request):
title = 'Please Enter Company Information'
SdescriptionFormSet = inlineformset_factory( Servicer, Sdescription, form = InputFormSdescription, extra=1)
StagFormSet = inlineformset_factory( Sdescription, Stag, form = InputFormStag, extra=1) #new
Sdescription_formset = InputFormSdescription()
Stag_formset = StagFormSet()
if request.POST:
FormServicer = InputFormServicer(request.POST or None)
FormSdescription = InputFormSdescription(request.POST or None) #new
if FormServicer.is_valid() and FormSdescription.is_valid():
servicer = FormServicer.save(commit=False)
Sdescription_formset=SdescriptionFormSet(request.POST, instance =servicer)
sdescription = FormSdescription.save(commit=False) #new
Stag_formset=StagFormSet(request.POST, instance =sdescription) #new
if Sdescription_formset.is_valid():
servicer.save()
Sdescription_formset.save()
sdescription.save() #n
Stag_formset.save() #new
return HttpResponseRedirect(reverse('serv.views.home'))
else:
FormServicer = InputFormServicer()
Sdescription_formset = SdescriptionFormSet(instance=Servicer())
Stag_formset=StagFormSet(instance=Sdescription())
context = {
"title": title,
"FormServicer": FormServicer,
"Sdescription_formset": Sdescription_formset,
"Stag_formset": Stag_formset, #new
}
return render(request, 'serv.html', context)
Models.py:
class Servicer(models.Model):
servicer_name = models.CharField(max_length=45,unique=True)
pub_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.servicer_name
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
# adds view site button on admin.
def get_absolute_url(self):
return '/video/%s/' % self.id
class Sdescription(models.Model):
servicer = models.ForeignKey(Servicer, on_delete=models.CASCADE, blank=True, null=True)
address = models.CharField(max_length=100,blank=True, null=True, unique=True)
address_line_2= models.CharField(max_length=100, blank=True, null=True)
city= models.CharField(max_length=50, blank=True, null=True)
state= models.CharField(max_length=25, blank=True, null=True)
zip = models.CharField(max_length=15, blank=True, null=True)
near_landmark = models.CharField(max_length=200, blank=True, null=True)
main_contact_name = models.CharField(max_length=20, blank=True, null=True)
phone_number1 = models.CharField(max_length=20, blank=True, null=True)
phone_number2 = models.CharField(max_length=20, blank=True, null=True)
comments = models.TextField(max_length=200, blank=True, null=True)
website = models.CharField(max_length=40, blank=True, null=True)
email = models.EmailField(max_length = 20,blank=True, null=True)
image = models.ImageField(upload_to='uploads/',blank=True, null=True)
def __str__(self):
return '%s %s %s %s %s %s %s %s %s %s %s' % (self.address,
self.address_line_2, self.city, self.state, self.zip,
self.near_landmark, self.phone_number1, self.phone_number2, self.comments,
self.website, self.email)
class Stag(models.Model):
tag_name = models.CharField(max_length=30,blank=True, null=True)
price = models.DecimalField(max_digits=9, decimal_places=2,blank=True,
null=True)
comments = models.CharField(max_length=100,blank=True, null=True)
sdescription = models.ForeignKey(Sdescription,
on_delete=models.CASCADE,blank=True, null=True)
def __str__(self):
return '%s $%s %s' % (self.tag_name, self.price, self.comments)
Forms.py:
class InputFormServicer(forms.ModelForm):
class Meta:
model = Servicer
fields=['servicer_name']
class InputFormSdescription(forms.ModelForm):
class Meta:
model = Sdescription
fields=['address','address_line_2','city','state','zip','near_landmark',
'main_contact_name', 'phone_number1', 'phone_number2', 'comments',
'website', 'email','image'
]
class InputFormStag(forms.ModelForm):
class Meta:
model = Stag
fields=['tag_name','price','comments']
Serv.html:
<h1>{{title}}</h1>
<form method='POST' action=''> {% csrf_token %}
{{FormServicer}}
{{Sdescription_formset.as_p}}
{{Sdescription_formset.management_form}}
{{Stag_formset.as_p}}
{{Stag_formset.management_form}}
<input type='submit' value='save'/>
</form>