Passing foreign key value to Choice in Django - python

I'm a bit confused on how Forms and ModelForms work, I want to create colored buttons based on a field value while creating a form.
{% for category in form.category %}
<label class="colored-icon btn btn-default btn-sm" style="background-color: {{ category.color }}">
{{ category.choice_label|slice:"1" }}
{{ category.tag }}
</label>
{% endfor %}
The problem is that category.colorobviously doesn't have value I need.
My form is based on a "Transaction" model. I need to somehow access "color" attribute from "Category" model, which looks like this:
forms.py
class TransactionForm(forms.ModelForm):
class Meta:
model = Transaction
models.py
class Transaction(models.Model):
category = models.ForeignKey(Category, default='Unspecified')
class Category(models.Model):
color = models.CharField(max_length=10)
views.py
def index(request):
form = TransactionForm(request.POST)
new_transaction = form.save()
context = {
'form': form,
}
return render(request, 'index.html', context)
What's the proper way to select and pass "category.color" to each field I'm creating?
Thanks.

Try this:
class Category(models.Model):
color = models.CharField(max_length=10)
def __unicode__(self):
return '%s - %s' % (self.OtherFieldName, self.color)
that way inside the select should look like this
<option value='CategoryID'>OtherFieldName_value - color_value</option>

Alright, I've figured out a way to do so with modified #warath-coder answer. I wasn't able to access "_value" property if it was a way to go, so I had to implement "split" filter and use it to split value I've got and use "color" part of this value.
models.py
class Category(models.Model):
color = models.CharField(max_length=10)
def __unicode__(self):
return '%s - %s' % (self.OtherFieldName, self.color)
split_filter.py
#register.filter(name='split')
def split(value, arg):
return value.split(arg)
index.html
{% with category.choice_label|split:"-" as label %}
<label class="btn btn-default btn-sm" style="background-color: {{ label.1 }}">
{{ label.0 }}
{{ category.tag }}
</label>
{% endwith %}

Related

Show item details together with item name in forms dropdown

currently I'm trying to show part quantity (quan) together with part name in the dropdown. I have a Part table that carries the part name and part quantity and this table called as ForeignKey into the Order table. So, in the Order form during choose the part name from the part dropdown, I would like to show part quantity as well besides the part name. Any idea to make it like that?
models.py
class Part(models.Model):
partno = models.CharField(max_length=50)
partname = models.CharField(max_length=50)
quan = models.PositiveIntegerField(default= 0)
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
part = models.ForeignKey(Part, on_delete=models.CASCADE)
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
for form_data in forms_data:
forms = OrderForm(request.POST)
if forms.is_valid():
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
supplier=supplier,
product=product,
part=part,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</form>
You will have to write "__ str __"(without spaces between str and __) method for model 'Part'
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
Check this post also: What is doing __str__ function in Django?

Django - Why is this random text rendering when I get errors upon form submission attempt?

I have a page with a form that takes in an employee # (using foreignkey), and when it is submitted it verifies that this employee # is in fact in another model (Salesman), and checks if 'WF' is in the team field for this employee. While the logic works and everything is being displayed, I keep getting this random bold text under the box Salesman object (406) (or whichever number I entered that would give me an error) after submitting the form, along with the proper error on top.
I think this is related to the foreignkey field part, but I'm not sure how to prevent this from showing up when there are errors.
models.py
class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, null=True, blank=False)
...
def __str__(self):
return self.employee_number
forms.py
class WarehouseForm(AppsModelForm):
class Meta:
model = EmployeeWorkAreaLog
widgets = {
'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
}
fields = ('employee_number', 'work_area', 'station_number')
def clean_employee_number(self):
employee_number = self.cleaned_data.get('employee_number')
if 'WF' in employee_number.team:
raise forms.ValidationError("Employee not valid, please contact manager")
else:
pass
return self.cleaned_data
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now())
return HttpResponseRedirect(self.request.path_info)
elif 'leave_area' in self.request.POST:
form.save()
return HttpResponseRedirect(self.request.path_info)
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<div style="color: red">{{ form.employee_number.errors.as_text }}</div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<!-- ... More fields ... -->
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% endblock main %}
That is part of the ForeignKeyRawIdWidget widget and it's the representation of the selected object (the Salesman object with ID 406).
If you wanted to get rid of it you would have to create a new widget which extends ForeignKeyRawIdWidget and removes that bit from the template. Here you can see how ForeignKeyRawIdWidget and its template look like.
Alternatively, and possibly better, you could consider to define the __str__ method of the Salesman model to show something more meaningful, in the same way you did for EmployeeWorkAreaLog.

Hidden fields, auto assign values in django

I am still a newbie on django and Python. This is also my first question. I am trying to create a hidden field and auto assign a value to the hidden field. It can be either in the views or in the templates. I have a field "kind" that needs to be hidden. Also I need to assign a value to it depending on different views/templates so it populates the database.
This is my class view:
class Monthlypage(CreateView):
template_name = 'monthly.html'
model = models.Lead
form = forms.LeadForm()
fields = ['name','email','tel','kind']
This is my model form:
class LeadForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kind = models.Lead.kind
class Meta:
model = models.Lead
kind = forms.CharField(widget=forms.HiddenInput())
fields = ['name','email','tel','kind']
This is my model:
class Lead(models.Model):
name = models.CharField(max_length=265)
email = models.EmailField(max_length=265)
tel = models.IntegerField()
kind = models.CharField(max_length=265)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('registrations')
This is my template:
<form class="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="hidden" name="kind" value="{{ form.kind.monthly }}" />
<input type="submit" name="" value="Submit" class="btn btn-info">
I have tried many options and spend 2 days using different solutions. But no matter what I do I can't seem to populate the kind field in the database.
I found the solution! Yeah! Please let me know if there is maybe a better or more correct solution!
This is my class View:
class Monthlypage(CreateView):
template_name = 'monthly.html'
model = models.Lead
form_class = forms.LeadForm
This is my model form:
class LeadForm(forms.ModelForm):
class Meta:
model = models.Lead
fields = ['name','email','tel','kind']
widgets = {
'kind':forms.HiddenInput()
}
This is my model:
class Lead(models.Model):
name = models.CharField(max_length=265)
email = models.EmailField(max_length=265)
tel = models.IntegerField()
kind = models.CharField(max_length=265)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('registrations')
This is my template:
<form class="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="hidden" name="kind" value="monthly">
<input type="submit" name="" value="Submit" class="btn btn-info">
Finally after 2 days of struggling, I hope this can help someone else out!

Accessing database Model from HTML Template in DJango

In the below code Instead of {{ i.user }} I want to access a value from another table with {{ i.user }} as matching value. How to done it within HTML
{% for i in obj reversed %}
<div class="container">
<blockquote>
<header> {{ i.topic }} {{ i.user }} </header>
<p> {{ i.desc }} </p>
<footer> {{ i.time }} </footer>
</blockquote>
{% endfor %}
</div>
Here are My Models
from django.db import models
class Accounts(models.Model):
name=models.CharField(max_length=30)
phone=models.CharField(max_length=20,unique=True)
mail=models.EmailField()
password=models.CharField(max_length=20)
def __str__(self):
return self.name
class BlogPost(models.Model):
user=models.CharField(max_length=30)
topic=models.CharField(max_length=100)
desc=models.CharField(max_length=1000)
likes=models.IntegerField(null=True,default=0)
time=models.DateTimeField(null=True)
def __str__(self):
return self.user
And I want to get value from Accounts using Blogspot.user i.e {{ i.user }} in template
Thanks in Advance...
from django.contrib.auth.models import AbstractBaseUser
class Accounts(AbstractBaseUser):
name = models.CharField(max_length=30)
phone = models.CharField(max_length=20,unique=True)
mail = models.EmailField()
password = models.CharField(max_length=20)
def __str__(self):
return self.name
class BlogPost(models.Model):
user = models.ForeignKey(Accounts, related_name='accounts')
topic = models.CharField(max_length=100)
desc = models.CharField(max_length=1000)
likes = models.IntegerField(null=True,default=0)
time = models.DateTimeField(null=True)
def __str__(self):
return self.user
Now, using foreign key you can access accounts model attributes in your template.

modelformset_factory with can_order

I am using modelformset_factory with can_order:
BrandFormSet = modelformset_factory(Brand, can_order=True, can_delete=True, extra=0)
And in my views I have:
<form ...>
{{ formset.management_form }}
{% for form in formset %}
{{ form.ORDER }}
{% endfor %}
</form>
It's showing correctly:
<input id="id_form-1-ORDER" name="form-1-ORDER" type="number" value="2" />
...
My Brand model looks like this:
class Brand(models.Model):
name = models.CharField(max_length=50)
order = models.SmallIntegerField()
def __unicode__(self):
return self.name
Now how can I tell Django that order field is where to save the ordering?

Categories

Resources