I am trying to manually render options for a select filed in a django template. When I submit the form I get an error: "Select a valid choice. That choice is not one of the available choices." The error message also asks for required fields which I have provided.
locations models.py
class Location(models.Model):
name = models.CharField(max_length=20)
is_source = models.BooleanField(default=False)
is_destination = models.BooleanField(default=False)
def __str__(self):
return self.name
orders models.py
class Order(models.Model):
order_number = models.IntegerField(unique=True)
order_date = models.DateField(auto_now_add=True)
type = models.CharField(max_length=15, choices=TYPES)
source = models.ForeignKey(Location, default=1, on_delete=models.SET_DEFAULT, related_name='ordered_here')
destination = models.ForeignKey(Location, default=1, on_delete=models.SET_DEFAULT, related_name='delivered_here')
items = models.TextField()
assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders_to_serve')
customer = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders_made')
status = models.CharField(max_length=15, choices=STATUSES)
orders forms.py
class OrderForm(ModelForm):
source = forms.ModelChoiceField(queryset=Location.objects.filter(is_source=True))
destination = forms.ModelChoiceField(queryset=Location.objects.filter(is_destination=True))
class Meta:
model = Order
fields = ['source', 'destination', 'items']
def save(self, commit=True):
instance = super().save(commit=False)
instance.order_number = math.floor(time.time())
instance.type = 'Purchase'
instance.customer = self.context.get('request').user
instance.status = 'New'
if commit:
instance.save()
return instance
orders create.html
<form class="" method="POST">
{% csrf_token %}
<h1 class='text-center'>Make an order</h1>
<div class='row'>
<div class='col-md-6 px-2'>
<span class="fw-bold mx-2">Buy from</span>
<div class="control-container border-primary d-flex align-items-center">
<i class="fa fa-map"></i>
<select class="control ms-1 flex-grow-1" type="text" name="{{form.source.html_name}}" required >
{% for value,label in form.source.field.choices %}
<option value="{{value}}">{{label}}</option>
{% endfor %}
</select>
</div>
</div>
<div class='col-md-6 px-2'>
<span class="fw-bold mx-2">Receive in</span>
<div class="control-container border-primary d-flex align-items-center">
<i class="fa fa-map"></i>
<select class="control ms-1 flex-grow-1" type="text" name="{{form.destination.html_name}}" required >
{% for value,label in form.destination.field.choices %}
<option value="{{value}}">{{label}}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class='row'>
<div class='col-12 px-2'>
<span class="fw-bold mx-2">List items (e.g. 2 X Luxaire Double Bed matress)</span>
<div class="control-container border-primary d-flex align-items-center">
<textarea class="control ms-1 flex-grow-1" rows="10" name="{{form.items.html_name}}" placeholder='e.g. 2 X Luxaire Double Bed matress' required></textarea>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary w-100 ">Order</button>
</form>
orders view.py
class OrderUpdateView(generic.edit.UpdateView):
model = Order
template_name = 'orders/update.html'
context_object_name = 'order'
form_class = OrderForm
I have eventually solved the problem by making the customer field in the order model nullable. I also had given my textarea in the order create template a wrong field name. All is well now.
you cannot do this even if you managed to make the form ignore this error the model will raise the same error elso because you just tell him to select a value from given values ... if you wanna make it dynammic then make it as noraml CharFied()
I have looked at all answer and nothing quite helps me. I have a model Group
class Group(models.Model):
group_num = models.CharField(max_length=100)
group_name = models.CharField(max_length=200)
type = models.CharField(max_length=200)
def __str__(self):
return self.group_name
and a model Subgroup group
class Subgroup(models.Model):
sub_group_num = models.CharField(max_length=100)
sub_group_name = models.CharField(max_length=200)
group_number = models.ForeignKey(Group, on_delete=models.CASCADE,
related_name='group_numbers', verbose_name="Group Number")
group_in_name = models.ForeignKey(Group, on_delete=models.CASCADE,
related_name='group_names', verbose_name="Group Name")
def __str__(self):
return self.sub_group_name
when I reference the group_number and group_in_name from subgroup they give the same value in the template
The template is
<div class="col-md-2">
<label>Group Number</label>
</div>
<div class="col-md-10 form-group">
{{ form.group_number }}
</div>
<div class="col-md-2">
<label>Group Name</label>
</div>
<div class="col-md-10 form-group">
{{ form.group_in_name }}
</div>
<div class="col-sm-12 d-flex justify-content-end">
<button type="submit" class="btn btn-primary me-1 mb-1">Add Sub Group</button>
</div>
And view is
class AddSubGroupView(CreateView):
model = Subgroup
form_class = AddSubgroupForm
template_name = 'lookups/add_subgroup.html'
def form_valid(self, form):
return super().form_valid(form)
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field.
views.py
# Create
class FileUploadCreateView(BSModalCreateView):
template_name = 'fileupload/create-file.html'
form_class = FileUploadModelForm
success_message = 'Success: File was uploaded.'
success_url = reverse_lazy('files_list')
# Add required field my_user prior to posting form
def form_valid(self, form):
form = FileUploadModelForm(self.request.POST, self.request.FILES)
self.object = form.save(commit=False)
self.object.my_user = self.request.user
self.object.file_status = 'ready'
return super().form_valid(form)
forms.py
class FileUploadModelForm(BSModalModelForm):
class Meta:
model = FileUpload
fields = ['file_name', 'file_description', 'file_date_from', 'file_date_to','file_upload']
widgets = {
'file_name': forms.TextInput(attrs={'class':'form-control mb-3', 'id':'ruleset_name'}),
'file_description': forms.Textarea(attrs={'rows':5}),
'file_date_from': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_date_to': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_upload': forms.FileInput(attrs={'class':'form-control-file mb-3', 'id':'file_upload', 'type':'file', }),
}
html
{% load widget_tweaks %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" style="color:#7a7a7a;">
<i class="fas fa-plus-square fa-med pr-2 align-middle"></i>
<span class="align-middle">ADD File</span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" style="font-size: small; color:#7a7a7a;">{{ field.label }}</label>
{% render_field field class="form-control" %}
<div class="{% if field.errors %} invalid{% endif %}">
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="submit-btn btn btn-primary pr-4 pl-4">Save</button>
</div>
</form>
model.py
class FileUpload(models.Model):
"""
Class for the creation of file uploads
"""
id = models.AutoField(primary_key=True)
my_user = models.ForeignKey('users.MyUser', on_delete=models.CASCADE, related_name='file_uploads', default=None)
file_name = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Name')
file_description = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Description')
file_date_from = models.DateField(default=None, null=True, blank=False, verbose_name='File Date From')
file_date_to = models.DateField(default=None, null=True, blank=False, verbose_name='File Date To')
STATUS_CHOICES = (
('ready','Ready'),
('processed', 'Processed'),
('archived','Archived'),
)
file_status = models.CharField(max_length=9, choices=STATUS_CHOICES, default=None, blank=False, verbose_name='File Status')
file_create_date = models.DateTimeField(verbose_name='File Create Date', auto_now_add=True)
file_upload = models.FileField(upload_to='uploads/%Y/%m/%d/', default=None, verbose_name='File Upload', blank=True)
class Meta:
ordering = ['-file_create_date']
constraints = [
models.UniqueConstraint(fields=['my_user','file_name'], name='Unique MyUser File')
]
def __str__(self):
return self.file_name
Pretty sure you forgot to add the enctype="multipart/form-data" data attribute to the form tag in your template.
To be sure, you would have to provide us with the Model, the Form and the template code.
after working on the view for some time, I was able to get the file to post via the following, using cleaned_data.
# Add required fields prior to posting form
def form_valid(self, form):
self.instance = form.save(commit=False)
self.instance.my_user = self.request.user
self.instance.file_status = 'ready'
self.instance.file_upload = form.cleaned_data['file_upload']
return super().form_valid(form)
I have created small stock web app.
I created a stock model with unique part_number field. In my update template I send all item information to be displayed. Then I get an error in the part_number field that it is already there.
How can I avoid this validation for that part_number only?
I mean for same part_number suppose validation will not work. But if I modified to another part_number that already exists I get an error that it's being duplicated.
Model:
class Stock(models.Model):
part_number = models.CharField(max_length=30, blank=False, unique=True)
part_name = models.CharField(max_length=70)
quantity = models.IntegerField(blank=False)
location = models.CharField(max_length=3, blank=True)
model = models.CharField(max_length=40, blank=True, null=True, default="")
min_quantity = models.IntegerField(unique=False, blank=True, default=0)
max_quantity = models.IntegerField(unique=False, blank=True, default=0)
class Meta:
ordering = ['part_number']
def clean(self):
self.part_number = self.part_number.upper()
def __str__(self):
return self.part_number
Form.py:
class StockUpdateModelForm(forms.ModelForm):
class Meta:
model = models.Stock
fields = ['part_name', 'quantity', 'location','part_number']
views.py:
def stock_update_form_view(request, part_id):
item = Stock.objects.get(id=part_id)
item_id = Stock.objects.get(id=part_id).pk
form = StockUpdateModelForm({
'part_number' : item.part_number,
'part_name' : item.part_name,
'quantity' : item.quantity,
'location' : item.location
})
if request.method == 'POST':
form = StockUpdateModelForm(request.POST)
if form.is_valid():
s = Stock.objects.get(pk=item_id)
s.part_name = form.cleaned_data['part_name']
s.part_number = form.cleaned_data['part_number']
s.quantity = form.cleaned_data['quantity']
s.location = form.cleaned_data['location']
print("form is valid")
s.save()
return redirect('/stock/')
return render(request, 'stock/stock_update.html', {'form': form, 'pn': item.part_number})
html:
<form class="bg-light shadow" method="POST">
<div style="margin-left:10%; margin-top:30px">
<h4>Part Number : {{ pn }}</h4>
</div>
<hr style="width:100%">
{% csrf_token %}
<div class="row" style="margin-left:30px; margin-top:40px ">
<div class="col-sm-4" style="margin-left:6%">
{{ form.part_name|as_crispy_field }}
</div>
<div class="col-sm-4" style="margin-left:15%">
{{ form.part_number|as_crispy_field }}
</div>
<div class="col-sm-4" style="margin-left:6%">
{{ form.quantity|as_crispy_field }}
</div>
<div class="col-sm-4" style="margin-left:15%">
{{ form.location|as_crispy_field }}
</div>
<div class="col-sm-4" style="height: 100px; margin-top:30px ; margin-left:6%">
<hr style="width:100%">
<input class="btn btn-primary" type="submit" value="Save"
style="width: 150px;">
</div>
</div>
</form>
try this
if request.method == 'POST':
form = StockUpdateModelForm(request.POST, instance=item)
if form.is_valid():
form.save()
I have created two models w_orders(workorders) and tobjects. I have two templates, one is only for creating a workorder and this works fine and one other template which contains data of both workorders and objects. tobjects is related to the table w_orders and I want to be able to create x number of objects for a workorder. For every workorder an object is created automatically. So far I have created the template and I can't quite figure how to display only the related objects for a certain workorder. For example for workorder no 1 I get the objects that are created for other workorders. As well I cannot add or edit an object related to the workorder. This is my code:
models.py
class w_orders(models.Model):
Id = models.BigAutoField(primary_key=True)
datedefwo = models.DateField(default=datetime.now)
datesched = models.DateField(blank=True, null=True)
datefinished = models.DateField(blank=True, null=True)
sign = models.BigIntegerField(blank=True, null=True)
statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES)
typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES)
comments = models.CharField(max_length=254, blank=True, null=True)
navid = models.BigIntegerField(blank=True, null=True)
navkonsid = models.CharField(max_length=12, blank=True, null=True)
navname = models.CharField(max_length=254, blank=True, null=True)
navcustadr = models.CharField(max_length=254, blank=True, null=True)
navdebt = models.FloatField(blank=True, null=True)
navpropcode = models.CharField(max_length=254, blank=True, null=True)
navdepcode = models.CharField(max_length=254, blank=True, null=True)
navphoneno = models.CharField(max_length=254, blank=True, null=True)
navreasoncomp = models.CharField(max_length=254, blank=True, null=True)
nightshift = models.BooleanField(default=False)
priority = models.BigIntegerField(blank=True, null=True)
stid = models.BigIntegerField(blank=True, null=True)
mapurl = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.Id
class tobjects(models.Model):
oid = models.BigAutoField(primary_key=True)
wid = models.ForeignKey(w_orders, on_delete=models.CASCADE)
objtypegisid = models.BigIntegerField(blank=True, null=True, default=1)
objgisid = models.BigIntegerField(blank=True, null=True, default=1)
condgenid = models.BigIntegerField(blank=True, null=True, default=1)
condriskid = models.BigIntegerField(blank=True, null=True, default=1)
condratsid = models.BigIntegerField(blank=True, null=True, default=1)
condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1)
condmhwallid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydrsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydreid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvolsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvoleid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconssid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconseid = models.BigIntegerField(blank=True, null=True, default=1)
txt = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.oid
#receiver(post_save, sender=w_orders)
def ensure_order_exists(sender, **kwargs):
if kwargs.get('created', False):
tobjects.objects.get_or_create(wid=kwargs.get('instance'))
workorder_edit.html
{% extends 'workorders/base.html' %}
{% block jumbotron2 %}
<div class="jumbotron">
<h1>Navbar example</h1>
<p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p>
<a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs »</a>
</div>
{% endblock %}
{% load static %}
{% block content %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{{ formset.management_form }}
{% for form in formset %}
{{ form.as_p }}
{% endfor %}
<input type="submit" value="Save">
</form>
workorder_create.html
{% extends 'workorders/base.html' %}
{% block jumbotron2 %}
<div class="jumbotron">
<h1>Navbar example</h1>
<p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p>
<a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs »</a>
</div>
{% endblock %}
{% load static %}
{% block content %}
<form method="POST" action="">
{% csrf_token %}
<div class="page-header">
<h2> Create Workorder </h2>
</div>
{{ form.non_field_errors }}
<div class="row">
<div class="col-md-4">
{{ form.datedefwo.errors }}
<label for="{{ form.datedefwo.id_for_label }}">Defined:</label>
{{ form.datedefwo }}
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
{{ form.typeid.errors }}
<label for="{{ form.typeid.id_for_label }}">Order type:</label>
{{ form.typeid }}
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
{{ form.datesched.errors }}
<label for="{{ form.datesched.id_for_label }}">Date Scheduled:</label>
{{ form.datesched }}
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
{{ form.statusid.errors }}
<label for="{{ form.statusid.id_for_label }}">Status:</label>
{{ form.statusid }}
</div>
</div>
<br>
<div class="row">
<div class="col-md-4">
{{ form.navreasoncomp.errors }}
<label for="{{ form.navreasoncomp.id_for_label }}">Request:</label>
{{ form.navreasoncomp }}
</div>
</div>
<div class="row">
<div class="col-md-4">
{{ form.navcustadr.errors }}
<label for="{{ form.navcustadr.id_for_label }}">Address:</label>
{{ form.navcustadr }}
</div>
</div>
<div class="row">
<div class="col-md-4">
{{ form.navname.errors }}
<label for="{{ form.navname.id_for_label }}">Customer:</label>
{{ form.navname }}
</div>
</div>
<div class="row">
<div class="col-md-4">
{{ form.navphoneno.errors }}
<label for="{{ form.navphoneno.id_for_label }}">Tel No:</label>
{{ form.navphoneno }}
</div>
</div>
<div class="row">
<div class="col-md-4">
{{ form.mapurl.errors }}
<label for="{{ form.mapurl.id_for_label }}">Map:</label>
{{ form.mapurl }}
</div>
</div>
<br>
<input type="submit" value="Save">
</form>
{% endblock %}
views.py
def workorders_list(request):
workorders_all = w_orders.objects.all().values_list('Id', flat=True)
return render(request, "workorders_list.html")
def home_page(request):
return render(request, "home_page.html")
def workorder_create(request):
if request.method == "POST":
form = CreateWorkorder(request.POST)
if form.is_valid():
CreateWorkorder_item = form.save(commit=False)
CreateWorkorder_item.save()
return redirect('/workorder/' + str(CreateWorkorder_item.Id) + '/')
else:
form = CreateWorkorder()
return render(request, 'workorders/workorder_create.html', {'form': form})
tobjectsFormSet = modelformset_factory(tobjects, fields=['wid', 'objtypegisid', 'objgisid', 'condgenid', 'condriskid', 'condratsid', 'condmhcoverid', 'condmhwallid', 'condpipehydrsid', 'condpipehydreid', 'condpipedepvolsid', 'condpipedepvoleid', 'condpipedepconssid', 'condpipedepconseid', 'txt'])
def workorder_edit(request, id=None):
item = get_object_or_404(w_orders, Id=id)
form = CreateWorkorder(request.POST or None, instance=item)
if form.is_valid():
new_order=form.save()
new_order.save()
formset = tobjectsFormSet(request.POST or None, request.FILES or None, extra=0)
if formset.is_valid():
formset.save()
return redirect('/workorder/' + str(item.Id) + '/')
else:
formset = tobjectsFormSet(request.POST or None, request.FILES or None)
return render(request, 'workorders/workorder_edit.html', {'formset': formset, 'form': form})
forms.py
class DateInput(forms.DateInput):
input_type = 'date'
class CreateWorkorder(forms.ModelForm):
navreasoncomp = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
navcustadr = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
navname = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
navphoneno = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
mapurl = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
class Meta:
model = models.w_orders
fields = ['Id', 'datedefwo', 'datesched', 'datefinished', 'statusid', 'sign', 'typeid', 'comments', 'navid', 'navkonsid', 'navdebt', 'navpropcode', 'navdepcode', 'nightshift', 'priority', 'stid', 'datesched', 'statusid', 'navreasoncomp', 'navcustadr', 'navname', 'navphoneno', 'mapurl']
widgets = {
'datedefwo': DateInput(attrs={'class':'datepicker'}),
'datesched': DateInput(attrs={'class':'datepicker'}),
'datefinished': DateInput(attrs={'class':'datepicker'}),
'navreasoncomp': forms.Textarea(attrs={'rows':3, 'cols':42}),
}
class createobject(forms.ModelForm):
wid = forms.IntegerField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
txt = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
class Meta:
model = models.tobjects
fields = ['wid', 'objtypegisid', 'objgisid', 'condgenid', 'condriskid', 'condratsid', 'condmhcoverid', 'condmhwallid', 'condpipehydrsid', 'condpipehydreid', 'condpipedepvolsid', 'condpipedepvoleid', 'condpipedepconssid', 'condpipedepconseid', 'txt']
urls.py
urlpatterns = [
url(r'^workorder/create/$', views.workorder_create, name='create_workorder'),
url(r'^workorder/edit/(?P<id>\d+)/$', views.workorder_edit, name='edit_workorder'),
url(r'^workorder/(?P<id>\d+)/$', views.workorder, name='workorder'),
url(r'^home/$', views.home_page, name='home_page'),
url(r'^workorders/$', views.workorders_list, name='workorders_list'),