I am making a shopping website, I am trying to initialize my products update form with the product information but I cant get the information from the model into the form.
models function
def get_product_details(product_id):
product_details = Products.objects.filter(name=rproduct_id).select_related('name', 'description','price','qty')
return product_details
form.py
class UpdateProductForm(forms.Form):
name = forms.CharField(
max_length=200,
required=True,
label="* name:",
widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
)
description = forms.CharField(
max_length=200,
required=True,
label="* description:",
widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
)
price = forms.IntegerField(
label="* price:",
widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
)
qty = forms.IntegerField(
label="* Qty:",
widget=TextInput(attrs={'class' : 'span6 small-margin-top small-margin-bottom'}),
)
view.py
def update_risk(request,product_id):
product_details = get_product_details(product_id)
name = form.cleaned_data['name']
description = form.cleaned_data['description']
price = form.cleaned_data['price']
qty = form.cleaned_data['qty']
form = UpdateProductForm(product_details)
return render(
request,
template_name = 'products/forms/update_product_form.html',
dictionary = {
'form':form,
'instr_text':instr_text
}
)
update form
<form method="POST" action="{% url 'products:update'%}">
{% csrf_token %}
{{ form.name }}
{{ form.description }}
{{ form.price }}
{{ form.qty }}
</form>
You could use ModelForms, which are designed not only to match the fields of the model, but also can easily be initialized with the data from a model.
See here for a general description: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/
Specifically, if the form is a ModelForm, you can do this:
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)
Related
Trying to save the below form, but it's not saving.
The traceback doesn't identify any problem, and print(form.errors) doesnt not return any issue.
I have the exact same code working for another page. So I am not sure what I am missing here. There has to be a typo, I cannot find it.
You will notice that I have an autocomplete function in my template. I initially thought autocomplete was not returning data in all the fields, so also tried to input data manually but not luck either.
Also tried with and without is_ajax but same result.
models.py:
class Venue(models.Model):
name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True)
address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True)
town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True)
county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True)
post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True)
country_1 = models.CharField(verbose_name="Country1",max_length=100, null=True, blank=True)
country_2 = models.CharField(verbose_name="Country2",max_length=100, null=True, blank=True)
longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True)
latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True)
phone = models.CharField(max_length=120)
web = models.URLField('Website Address')
email_address = models.EmailField('Venue Email Address')
def __str__(self):
return str(self.name) if self.name else ''
forms.py:
class VenueForm(ModelForm):
name = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"name"}))
address = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'id':"address"}))
town = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"town"}))
county = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"county"}))
post_code = forms.CharField(max_length=8, required=True, widget = forms.TextInput(attrs={'id':"post_code"}))
country_1 = forms.CharField(max_length=40, required=True, widget = forms.TextInput(attrs={'id':"country_1"}))
country_2 = forms.CharField(max_length=40, required=True, widget = forms.TextInput(attrs={'id':"country_2"}))
longitude = forms.CharField(max_length=50, required=False, widget = forms.TextInput(attrs={'id':"longitude"}))
latitude = forms.CharField(max_length=50, required=False, widget = forms.TextInput(attrs={'id':"latitude"}))
phone = forms.CharField(max_length=120,required=False)
web = forms.URLField(max_length=120,required=False)
email_address = forms.CharField(max_length=120, required=False)
class Meta:
model = Venue
fields = ['name', 'address', 'town', 'county', 'post_code','country_1','country_2','longitude','latitude','web', 'phone', 'email_address']
views.py:
def google_api_test(request):
submitted = False
form = VenueForm()
if is_ajax(request) and request.method =="POST":
form = VenueForm(data = request.POST)
if form.is_valid():
form.save()
messages.success(request,("Success!"))
return redirect('home')
else :
print(form.errors)
context = {
'form' : form,
'submitted' : submitted,
'google_api_key' : settings.GOOGLE_API_KEY,
'base_country' : settings.BASE_COUNTRY,
}
return render(request,"main/google_api_test.html", context)
html file:
<div class = "form-group">
<input id="autocomplete" style ="width: 500px "placeholder="Enter your address">
<form id="venueform" method="POST" action="">
{% csrf_token %}
{{ form|as_crispy_errors }}
<td class="label">Name (Name)</td>
{{form.name| as_crispy_field}}
</br>
<td class="label">Street Number + Street Name (Address)</td>
{{form.address| as_crispy_field}}
</br>
<td class="label">Town (town)</td>
{{form.town | as_crispy_field}}
</br>
<td class="label">Country(country_1)</td>
{{form.country_1| as_crispy_field}}
</br>
<td class="label">Post Code (post_code)</td>
{{form.post_code| as_crispy_field}}
</br>
<td class="label">Country(country_2)</td>
{{form.country_2| as_crispy_field}}
</br>
<td class="label">Country(longitude)</td>
{{form.longitude| as_crispy_field}}
</br>
<td class="label">Country(latitude)</td>
{{form.latitude| as_crispy_field}}
</br>
<td class="label">phone(phone)</td>
{{form.phone| as_crispy_field}}
</br>
<td class="label">web(web)</td>
{{form.web| as_crispy_field}}
</br>
<td class="label">email_address(email_address)</td>
{{form.email_address| as_crispy_field}}
</br>
<button type="submit" value="Submit" id="profile-btn">Validate</button>
</form>
</div>
Firstly, I'd recommend you to check whether the form even goes to the POST method of google_api_view or not since you mentioned form.errors prints nothing.
Remove the empty action="" from the html form, since Django always takes current page route or url, so it is unnecessary.
Also suggest not to use is_ajax(request) only for one time to check(I think it's depreciated).
So, try this view:
def google_api_test(request):
submitted = False
form="" # for the error - local variable 'form' referenced before assignment if occurs.
if request.method == 'POST':
print("POST method") # check it prints it or not.
form = VenueForm(request.POST)
if form.is_valid():
form.save()
messages.success(request,"Success!")
return redirect('home')
else:
print(form.errors)
else: # GET request
form = VenueForm()
context = {
'form' : form,
'submitted' : submitted,
'google_api_key' : settings.GOOGLE_API_KEY,
'base_country' : settings.BASE_COUNTRY,
}
return render(request,"main/google_api_test.html", context)
Also share Ajax and jQuery code.
county is missing in your template. It's weird that your print(form.errors) did not show up in your terminal - it should have
def google_api_test(request):
submitted = False
if is_ajax(request) and request.method == 'POST':
print(request.POST) # Check--Are you getting form data
form = VenueForm(data = request.POST)
if form.is_valid():
form.save()
messages.success(request,("Success!"))
return redirect('home')
else :
print(form.errors)
else:
form = VenueForm() #Changes in here.
context = {
'form' : form,
'submitted' : submitted,
'google_api_key' : settings.GOOGLE_API_KEY,
'base_country' : settings.BASE_COUNTRY,
}
return render(request,"main/google_api_test.html", context)
Not sure my title is fully representing my problem.
I thought I would put a screenshot of the problem (admin panel), so it's clearer for everyone
It looks like the form is savings, but nothing goes inside.
Here is the models code:
class Venue(models.Model):
name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True)
address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True)
town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True)
county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True)
post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True)
country = models.CharField(verbose_name="Country",max_length=100, null=True, blank=True)
longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True)
latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True)
city = models.CharField(max_length=120)
def __str__(self):
return str(self.name) if self.name else ''
Obviously, I am aware I have asked to return '' if self.name wasnt there. The reason why I did it, is because initially, the models was visible on the admin panel under "-" but was throwing an error message when clicking on it.
Considering I am working with a form, here is the form code:
class VenueForm(forms.ModelForm):
name = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
address = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
town = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
county = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput())
post_code = forms.CharField(max_length=8, required=True, widget = forms.HiddenInput())
country = forms.CharField(max_length=40, required=True, widget = forms.HiddenInput())
longitude = forms.CharField(max_length=50, required=True, widget = forms.HiddenInput())
latitude = forms.CharField(max_length=50, required=True, widget = forms.HiddenInput())
phone = forms.CharField(max_length=120)
web = forms.URLField(max_length=120)
email_address = forms.CharField(max_length=120)
class Meta:
model = Venue
fields = ['name', 'address', 'town', 'county', 'post_code','country','post_code','latitude','city', 'web', 'phone', 'email_address']
the views
def add_venue(request):
submitted = False
form = VenueForm()
if is_ajax(request) and request.method =="POST":
form = VenueForm(data = request.POST)
if form.is_valid():
form.save()
messages.success(request,("Success!"))
return HttpResponseRedirect('/add_venue?submitted=True')
context = {
'form' : form,
'submitted' : submitted,
'google_api_key' : settings.GOOGLE_API_KEY,
'base_country' : settings.BASE_COUNTRY,
}
return render(request,"main/add_venue.html",context)
and finally the html file
<div class="form-group">
<input type="text" placeholder="*Begin typing address" id="id-google-address" name="google_address">
<form id="venueform" method="POST" action="{% url 'add_venue'%}">
{% csrf_token %}
<label for="name" class="hidden-el" hidden>Name</label>
{{form.name}}
<label for="address" class="hidden-el" hidden>Address</label>
{{form.address}}
<label for="town" class="hidden-el" hidden>Town/City</label>
{{form.town}}
<label for="county" class="hidden-el" hidden>County</label>
{{form.county}}
<label for="post_code" class="hidden-el" hidden>Postal Code</label>
{{form.post_code}}
<label for="country" class="hidden-el" hidden>Country</label>
{{form.country}}
<label for="longitude" class="hidden-el" hidden>Longitude</label>
{{form.longitude}}
<label for="latitude" class="hidden-el" hidden>Latitude</label>
{{form.latitude}}
<h4>Phone</h4>
<label for="phone" class="hidden-el" hidden>Phone</label>
{{form.phone}}
<h4>WebSite</h4>
<label for="web" class="hidden-el" hidden>Website</label>
{{form.web}}
<h4>Email Address</h4>
<label for="email_address" class="hidden-el" hidden>Email Address</label>
{{form.email_address}}
<button type = "submit" class="btn btn-secondary">Add Venue</button>
</form>
</div>
{% endblock %}
{% block extend_footer %}
<script type="text/javascript">
var google_api_key = "{{google_api_key|safe}}";
var base_country = "{{base_country|safe}}";
</script>
<script src="{% static 'google_places.js' %}"></script>
{% endblock %}
def add_venue(request):
submitted = False
form = VenueForm()
venue = Venue.objects.create() # <- This line is the issue.
You are creating an empty venue, and not going anything with the variable.
Then, you are saving the form
data = form.save(commit = False)
data.name = form.cleaned_data['name']
data.address = form.cleaned_data['address']
data.town = form.cleaned_data['town']
data.county = form.cleaned_data['county']
data.post_code = form.cleaned_data['post_code']
data.country = form.cleaned_data['country']
data.longitude = form.cleaned_data['longitude']
data.latitude = form.cleaned_data['latitude']
data.city = form.cleaned_data['city']
data.phone = form.cleaned_data['phone']
data.web = form.cleaned_data['web']
data.email_address = form.cleaned_data['email_address']
data.save()
Without having validated the form first.
You need to call form.is_valid() before any of this.
Then, you are validating the form, and saving the form again.
You are trying a single object, 3 times. 2 of which are executed wrong.
Then, you are not instantiating your form in the
else:
form = VenueForm
if 'submitted' in request.GET:
submitted = True
And on top of that, you should return the form POSTed, so you can send back the form.errors().
else:
form = VenueForm()
if 'submitted' in request.GET:
submitted = True
If this is a ModelForm, all that is needed is:
def add_venue(request):
submitted = False
form = VenueForm()
if is_ajax(request) and request.method =="POST":
form = VenueForm(data = request.POST)
if form.is_valid():
form.save()
messages.success(request,("Success!"))
return HttpResponseRedirect('/add_venue?submitted=True')
context = {
'form' : form,
'submitted' : submitted,
'google_api_key' : settings.GOOGLE_API_KEY,
'base_country' : settings.BASE_COUNTRY,
}
return render(request,"main/add_venue.html",context)
I have been struggling over this for days diving down stackoverflow rabbit holes, documentation, and youtube tutorials. I'm just running in circles at this point. So...
I have two models Variables and Entry. The daily inputs for Entry are to be recordings associated with a given Variable. Ex. I want to track daily sleep as a variable. Then, using that variable, have daily data entry associated with that variable using the Entry model.
My models are below... (I suspect my schema is a mess as well, but it's generally working. This is my first time)
class Variables(models.Model):
ENTRY_TYPE_CHOICES = [
('numeric', 'enter a daily number'),
('scale', 'rate daily on a scale of 1-10'),
('binary', "enter daily, 'yes' or 'no' "),
]
id = models.IntegerField(primary_key=True)
dep_var = models.CharField(max_length=50, default='')
dv_reminder = models.CharField(max_length=50, choices=ENTRY_TYPE_CHOICES, default="numeric")
# id current user
evoler = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE)
def __str__(self):
return self.dep_var
def get_absolute_url(self):
return reverse('entry_new')
class Entry(models.Model):
id = models.AutoField(primary_key=True)
evoler = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) # id the active user
dep_variables = models.CharField(max_length=50, default = '')
data = models.FloatField(default=0.0)
date = models.DateField(default=datetime.date.today)
I've tried writing a function that would identify the most recent variable from a given user and to use that as the default value in the Entry.dep_variables model. That works in the local environment but causes issues when I try to migrate the database.
Views...
def daily_entry(request):
''' page to make daily entries '''
if request.method != 'POST':
# No data submitted. GET submitted. Create a blank form
form = DailyEntryForm()
else:
#POST data submitted. Process data
form = DailyEntryForm(data=request.POST)
if form.is_valid():
data = form.save(commit=False)
data.evoler = request.user
data.save()
return HttpResponseRedirect(reverse('entry_new'))
context = {'form': form}
return render(request, 'entry_new.html', context)
Forms...
class VariablesForm(forms.ModelForm):
class Meta:
model = Variables
fields = ['dep_var', 'dv_reminder' ]
labels = {'dep_var':'Dependent variable to track', 'dv_reminder': 'Type of measure'}
class DailyEntryForm(forms.ModelForm):
class Meta:
model = Entry
var = Variables.dep_var
fields = ['dep_variables', 'data', 'date']
labels = {'dep_variables': 'Dependent variable you are tracking',
'data': 'Daily entry', 'date': 'Date'}
and template.html...
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<br>
<h1>New Entry</h1>
<form class="" action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" name="" value="Save" />
</form>
{% endblock content %}
Any and all assistance would be infinitely appreciated.
I have a form that requires a URL as input. I would like to check if the URL begins with http:// or https://.
If it doesn't have one of these two 'stings' in the beginning, the form submission should give an error.
I don't have any clue on how to get started with this and could not find any info based on my limited knowledge of django and I have no clue what search terms to look up.
A basic hint would be a great help.
Thanks!
My current forms.py has a form based on a model:
class AddUrlForm(forms.ModelForm):
class Meta:
model = forwards
# fields = '__all__'
exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"]
models.py:
class forwards(models.Model):
uniqueid = models.AutoField(primary_key=True)
user = models.CharField(max_length = 150)
urlA = models.CharField(verbose_name="URL Version A", max_length = 254)
counterA = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0'))
urlB = models.CharField(verbose_name="URL Version B",max_length = 254)
counterB = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0'))
timestamp = models.DateTimeField('date created', auto_now_add=True)
shortcodeurl = models.CharField(max_length = 254)
html segment where that shows how the form is integrated:
<form method="post">
{% csrf_token %}
{% for field in forwardform %}
<span>{{ field.label_tag }} </span>
<p style="color: black">{{ field }} </p>
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
{% endfor %}
<button class="btn btn-outline btn-xl type="submit">Generate URL</button>
</form>
views.py:
def forwardthis(request):
forwardform = AddUrlForm(request.POST or None)
if forwardform.is_valid():
forward = forwardform.save(commit=False)
forward.user = request.user.username
forward = forwardform.save()
uniqueid_local = forward.uniqueid
uniqueid_local_bytes = uniqueid_local.to_bytes((uniqueid_local.bit_length() + 7) // 8, byteorder='little')
shortcodeurl_local = urlsafe_base64_encode(uniqueid_local_bytes)
forward.shortcodeurl = shortcodeurl_local
forward.save()
return HttpResponseRedirect('/forwardthis')
query_results = forwards.objects.filter(user=request.user.username)
query_results_qty = query_results.count()
click_results = clickstats.objects.filter(user=request.user.username)
template = loader.get_template('forwardthis.html')
context = {
'forwardform': forwardform ,
'query_results':query_results,
'query_results_qty': query_results_qty
}
return HttpResponse(template.render(context,request))
You can create a validation method for each form field. def clean_FIELDNAME(). I supose the url field is shortcodeurl:
class AddUrlForm(forms.ModelForm):
def clean_shortcodeurl(self):
cleaned_data = self.clean()
url = cleaned_data.get('shortcodeurl')
if not is_valid_url(url): # You create this function
self.add_error('shortcodeurl', "The url is not valid")
return url
class Meta:
model = forwards
# fields = '__all__'
exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"]
For anyone coming here in 2021.
Nowadays Django provides the tools to achieve this kind of validation.
Based on Django 3.2 documentation
from django import forms
from django.core.exceptions import ValidationError
class AddUrlForm(forms.ModelForm):
class Meta:
model = forwards
# fields = '__all__'
exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"]
def clean_shortcodeurl(self):
data = self.cleaned_data['shortcodeurl']
if "my_custom_example_url" not in data:
raise ValidationError("my_custom_example_url has to be in the provided data.")
return data
Following the ModelForm docs and using this model:
class ShippingLabel(models.Model):
"""Record what shipping lables were printed list"""
class Meta:
db_table = 'shipping_labels'
ordering = ('client',)
verbose_name = _('shipping label')
verbose_name_plural = _('shipping labels')
LAYOUT_LASER_2x2 = "1"
LAYOUT_TICKET = "2"
LAYOUT_LASER_1x1 = "3"
LAYOUT_CHOICES = (
( LAYOUT_LASER_1x1, _("Laser (1x1 sheet)") ),
( LAYOUT_LASER_2x2, _("Laser (2x2 sheet)") ),
( LAYOUT_TICKET, _("Ticket (3-inch wide)") ),
)
client = models.ForeignKey(Company, blank=False, null=False, unique=True, help_text=_("Which Client to ship to?"), verbose_name=_("client") )
store = models.ForeignKey(Store, blank=False, null=False, help_text=_("What store info should be used? (address, logo, phone, etc)"), verbose_name=_("store") )
packages = models.CharField(_("Packages"), max_length=30, blank=False, null=False, help_text=_("Total number of packages. One label printed per package.") )
preprinted_form = models.BooleanField(_("Pre-Printed Form"), default=False, help_text=_("Are you using pre-printed shipping label stickers?"), )
layout = models.CharField(_("Record Type"), max_length=10, blank=False, null=False, choices=LAYOUT_CHOICES, default=LAYOUT_LASER_1x1, help_text=_("Print on large labels (4 per Letter page), Laser large labels (1 per page), or ticket printer?") )
added_by = models.CharField(_("Added By"), max_length=30, blank=True, null=True, help_text=_("The User that created this order.") )
date_added = models.DateTimeField(_('Date added'), auto_now_add=True)
date_modified = models.DateTimeField(_('Date modified'), auto_now=True)
def get_absolute_url(self):
return reverse('shipping:printship', args=[str(self.id)])
def __unicode__(self):
return unicode(self.client)
I made this form template following their example (manual_label.html):
{% extends "admin/base_site.html" %}
{% load i18n %}
{% load staticfiles %}
{% block extrahead %}
{{ block.super}}
<script src="{{ STATIC_URL }}js/jquery-1.11.1.js"></script>
{% endblock %}
{% block content %}
<form id="manual_label" method="post" action="">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="generar etiquetas autoadhesivas"/>
</form>
<p>
</p>
{% endblock %}
My app urls.py:
from django.conf.urls import patterns, url
from shipping.views import printship, pcustomer, manual_label
urlpatterns = patterns('',
url(r'pcust/', pcustomer, name='pcustomer'),
url(r'mlabel/([0-9]+)/$', manual_label, name='manual_label'),
url(r'printlabel/([0-9]+)/$', printship, name='printship'),
)
My view (with lots of diagnostic logging):
#login_required()
def manual_label(request, id):
logger.debug("SHIPPING.VIEWS.manual_label")
if request.method == 'POST':
logger.debug("SHIPPING.VIEWS.manual_label: POST!")
client = get_object_or_404(Company, pk=id)
labelset = ShippingLabel.objects.filter(client=client)
if len(labelset)>0:
# Pre-existing label, update it:
logger.debug("SHIPPING.VIEWS.manual_label.POST: Update a label!")
label = labelset[0]
form = ShipLabelForm(request.POST, instance=label)
else:
# New label:
logger.debug("SHIPPING.VIEWS.manual_label.POST: Save New label!")
form = ShipLabelForm(request.POST)
if form.is_valid():
logger.debug("SHIPPING.VIEWS.manual_label.POST: form is valid")
label = form.save(commit=True)
logger.debug("SHIPPING.VIEWS.manual_label.POST: label pk: " + str(label.id) )
logger.debug("SHIPPING.VIEWS.manual_label.POST: label client name: " + str(label.client.name) )
logger.debug("SHIPPING.VIEWS.manual_label: post return")
return HttpResponseRedirect(reverse('shipping:printship', args=[str(label.id)]))
else:
logger.debug("SHIPPING.VIEWS.manual_label: GET!")
client = get_object_or_404(Company, pk=id)
labelset = ShippingLabel.objects.filter(client=client)
if len(labelset)>0:
# Pre-existing label, load it:
logger.debug("SHIPPING.VIEWS.manual_label: Pre-Existing label, load it...")
label = labelset[0]
form = ShipLabelForm(instance=label)
else:
# New label:
label = ShippingLabel(client=client,
store=request.user.employee.store,
added_by=request.user.get_username())
form = ShipLabelForm(instance=label)
logger.debug("SHIPPING.VIEWS.manual_label: get return")
return render(request, 'shipping/manual_label.html', {
'title': u"Creación de etiquetas Manual Envios",
'form': form,
})
My forms.py definition:
class ShipLabelForm(ModelForm):
class Meta:
model = ShippingLabel
localized_fields = '__all__'
fields = '__all__'
widgets = {
'added_by': HiddenInput,
'id': HiddenInput,
}
I added 'id': HiddenInput, to try and "force" record ID number to get sent out to the form, in the theory that my error occurs because without the ID number, Django will validate in "ADD" mode which will certainly trigger the "unique" flag I have on clients.
The manual_label view is called by a customer selection form, passing in the client id. The goal is to generate an ADD form if there is currently no shipping label for this client defined - which works.
And if a shipping label already exists, I pre-load the form with its data. The idea being I thought the form system would automatically do an UPDATE on the existing record.
In either case, the saved shipping label record is used to generate the shipping labels desired.
This works in the admin view (using view on site). But I wanted to give the users a simpler system. This works fine for ADDing new labels. But when I try to EDIT an existing label, I get a form validation error "client already exists".
It seemed like such an easy thing to do....
So, what am I missing tor doing wrong?
You should be using the instance argument when initializing the form, both in the POST and GET blocks.