My model.py looks:
class VehicleInquiry(TimeStampedModel):
inquiry_status = models.PositiveSmallIntegerField(_("inquiry status"), choices=INQUIRY_STATUS_CHOICES, default=1)
ip = models.GenericIPAddressField(_("IP"), blank=True, null=True)
full_name = models.CharField(_("full name"), max_length=100)
address = models.CharField(_("address"), max_length=200)
phone_code = models.PositiveSmallIntegerField(_("phone code")
)
phone = models.CharField(_("phone"), max_length=20)
email = models.EmailField(_("email"))
is_subscribed = models.BooleanField(_("subscribed"), default=True)
vehicle = models.ForeignKey(VehicleStock, on_delete=models.SET_NULL, blank=True, null=True,
related_name="inquiries", verbose_name=_("vehicle")
)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, blank=True, null=True,
related_name="inquiries", verbose_name=_("country")
)
arrival_port = models.ForeignKey(CountryPorts, on_delete=models.SET_NULL, blank=True, null=True,
related_name="inquiries", verbose_name=_("arrival port")
)
current_price = models.PositiveIntegerField(_('current price'), null=True, blank=True)
inspection = models.BooleanField(_("pre-export inspection"), default=False)
insurance = models.BooleanField(_("insurance"), default=True)
total = models.PositiveIntegerField(_('total price'), null=True, blank=True)
my form.py:
class VehicleInquiryForm(forms.ModelForm):
country2 = forms.TypedChoiceField(
label=_("Country"),
choices=[('','Arrival Country')]+[(country.id, country.name) for country in Country.objects.all().filter(visible=True).order_by('name')],
required=True,
)
phone_code = ChoiceFieldWithTitles(
label=_("Country dialing code"),
choices=[('','Dailing Code', 'Dailing Code')]+[(country.id, '{} (+{})'.format(country.name, country.phone_code), '+{}'.format(country.phone_code)) for country in Country.objects.all().filter(visible=True).order_by('name')],
required=True,
)
arrival_port = forms.TypedChoiceField(
label=False,
widget=forms.RadioSelect
)
phone = forms.CharField(
label=_("Phone"),
max_length=20,
required=True,
validators=[phone_number_validator]
)
full_name = StrippedCharField(
label=_("Full name"),
max_length=30,
required=True,
validators=[full_name_validator]
)
address = StrippedCharField(
label=_("Address"),
max_length=200,
required=True
)
class Meta:
model = VehicleInquiry
exclude = ('inquiry_status', 'vehicle', 'current_price', 'total')
def clean_country2(self):
country_id = self.cleaned_data['country2']
try:
country = Country.objects.get(id=country_id)
except Country.DoesNotExist:
raise forms.ValidationError(_('Please select the country'))
return country_id
def clean(self):
cleaned_data = super(VehicleInquiryForm, self).clean()
dialing_code = cleaned_data['phone_code']
try:
dialing_country = Country.objects.get(id=dialing_code)
except Country.DoesNotExist:
raise forms.ValidationError(_('Please select the phone code'))
return self.cleaned_data
def __init__(self, *args, **kwargs):
dialing_code = kwargs.pop('phone_code', None)
super(VehicleInquiryForm, self).__init__(*args, **kwargs)
self.fields['is_subscribed'].label = _("Keep me updated with news, specials offers and more.")
self.helper = FormHelper()
self.helper.template_pack = "bootstrap3"
self.helper.form_method = "post"
self.helper.form_id = "vehicle-shipping-form"
self.helper.form_show_errors = True
self.initial['insurance'] = True
self.fields['phone_code'].initial = dialing_code
self.helper.add_input(
Submit('inquiry', _('Inquiry'), css_class='btn btn-default',)
)
self.helper.form_method = 'post'
self.helper.layout = Layout(
Fieldset(
_("1. Choose Your Final Destination"),
Div(
Field('country2', css_class="order-select-country"),
),
-- other fields --
)
view.py
class VehicleStockDetailView(FormView):
template_name = "site/product/vehicle-detail.html"
template_name_done = "site/contact/contact-us-done.html"
template_name_done_email = "site/contact/emails/contact-us-done.html"
form_class = VehicleInquiryForm
model = VehicleStock
def get(self, request, slug, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
vehicle = get_object_or_404(VehicleStock, slug=slug)
similar_vehicles = VehicleStock.objects.get_public_available().filter(model__id=vehicle.model.id).exclude(slug=slug)[:6]
page_title = vehicle.model
return render(request, self.template_name, {'page_title': page_title, 'similar_products': similar_vehicles, 'stock_product': vehicle, 'shipping_form': form})
def post(self, request, slug, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
vehicle = get_object_or_404(VehicleStock, slug=slug)
similar_vehicles = VehicleStock.objects.get_public_available().filter(model__id=vehicle.model.id).exclude(slug=slug)[:6]
page_title = vehicle.model
if form.is_valid():
form.save()
return render(self.request, self.template_name_done, {'full_name': request.POST['full_name'], 'email': request.POST['email']})
return render(self.request, self.template_name, {'page_title': page_title, 'similar_products': similar_vehicles, 'stock_product': vehicle, 'shipping_form': form})
url.py
url(r'^vehicle/(?P<slug>[-_\w]+)/$', VehicleStockDetailView.as_view(), name='vehicle-detail'),
Now, when I fill the form and send inquiry it is not showing any error but showing again the form with entered field values except phone_code (it is showing default value). No errors showing, but the form is not validated. I tried different ways with TemplateView and with FormView. But no success.Deadly need any help.
You haven't passed the POSTed data to the form anywhere.
This is one of the reasons why you should not be overriding the get and post methods. The point of the various class-based views is that they do almost all of this for you. You should be inheriting from CreateView, so that the form is saved when it is valid, and the extra logic you have added should be in get_context_data - as you can see, this avoids having to include the same code twice.
class VehicleStockDetailView(CreateView):
template_name = "site/product/vehicle-detail.html"
template_name_done = "site/contact/contact-us-done.html"
template_name_done_email = "site/contact/emails/contact-us-done.html"
form_class = VehicleInquiryForm
model = VehicleStock
def get_context_data(self, *args, **kwargs):
context = super(VehicleStockDetailView, self).get_context_data(*args, **kwargs)
context['vehicle'] = get_object_or_404(VehicleStock, slug=self.kwargs['slug'])
context['similar_vehicles'] = VehicleStock.objects.get_public_available().filter(model__id=vehicle.model.id).exclude(slug=slug)[:6]
context['page_title'] = vehicle.model
return context
def form_valid(self, form, *args, **kwargs):
obj = form.save()
return render(self.request, self.template_name_done, {'full_name': self.request.POST['full_name'], 'email': self.request.POST['email']})
Note also that you really should never directly render a template on success; you should always redirect. Again, the form view takes care of this for you.
Related
How implement that the user in the Model Entities add automatically the user that is authenticated in django?
now, returning the following error:
error
I have tried differents methods that i have founding in the internet but not function. all cases return error in the momento to record a row.
only, i need that, in the moment that create a row, the user field was the user that is authenticated.
My Model:
class Entities(models.Model):
#class Category(models.Model):
id = models.BigAutoField(primary_key=True)
code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True,
help_text='Codigo de entidad.')
name = models.CharField(max_length=150, verbose_name='Nombre', unique=True,
help_text='Nombre de la entidad.')
desc = models.CharField(max_length=500, null=True, blank=True, verbose_name='Descripción',
help_text='Descripción de la entidad.')
name_report = models.CharField(verbose_name='Nombre Reporte', max_length=100, blank=False, unique=True,
help_text='Rellenar para ACTIVAR el reporte')
long_desc = models.CharField(verbose_name='Descripción Larga', max_length=800, blank=True,
help_text='Descripción larga. Máximo 800 caracteres.')
language = models.CharField(verbose_name='Idioma', max_length=2, choices=languages, default='ES',
help_text='Idioma del reporte')
user = models.ForeignKey(User, default=0, verbose_name='Usuario', on_delete=models.DO_NOTHING)
date_created = models.DateTimeField(default=timezone.now, verbose_name='Creado', blank=False, unique=False)
date_updated = models.DateTimeField(default=timezone.now, verbose_name='Actualizado', blank=False, unique=False)
historical = HistoricalRecords()
def __str__(self):
return self.name
def toJSON(self):
item = model_to_dict(self)
return item
class Meta:
verbose_name = 'Entidad'
verbose_name_plural = 'Entidades'
ordering = ['id']
My CreateView:
class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Entities
form_class = EntitiesForm
template_name = 'Entities/create.html'
success_url = reverse_lazy('erp:entities_list')
permission_required = 'add_Entities'
url_redirect = success_url
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
form = self.get_form()
data = form.save()
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Creación de una Entidad'
context['entity'] = 'Entidades'
context['list_url'] = self.success_url
context['action'] = 'add'
return context
My Form:
class EntitiesForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# for form in self.visible_fields():
# form.field.widget.attrs['class'] = 'form-control'
# form.field.widget.attrs['autocomplete'] = 'off'
self.fields['code'].widget.attrs['autofocus'] = True
class Meta:
model = Entities
fields = '__all__'
exclude = ['user','date_created','date_updated']
widgets = {
'name': forms.TextInput(
attrs={
'placeholder': 'Ingrese un nombre',
}
),
'desc': forms.Textarea(
attrs={
'placeholder': 'Ingrese un nombre',
'rows': 3,
'cols': 3
}
),
}
def save(self, commit=True):
data = {}
form = super()
try:
if form.is_valid():
**self.instante.user = self.request.user**
form.save()
else:
data['error'] = form.errors
except Exception as e:
data['error'] = str(e)
return data
SOLVED.
Adding, in the view, the line :
form.instance.user = self.request.user
full Createview would be :
class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Entities
form_class = EntitiesForm
template_name = 'Entities/create.html'
success_url = reverse_lazy('erp:entities_list')
permission_required = 'add_Entities'
url_redirect = success_url
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
form = self.get_form()
form.instance.user = self.request.user <============================
data = form.save()
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Creación de una Entidad'
context['entity'] = 'Entidades'
context['list_url'] = self.success_url
context['action'] = 'add'
return context
If you want to save additional data into form you can commit=False for this...
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
form = self.get_form()
form = form.save(commit=False)
form.user = request.user
data = form.save()
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data)
I have a specific problem with my forms. I think it would be better to share my codes instead of explaining the problem in detail.
However, to explain in a nutshell; inside my model I have field OneToOneField and model of that field has inlineformset_factory form. My new model also has a form and I want to save both forms.
I get the following error when I want to save the offer update form:
TypeError at /ru/mytarget/offer-update/T2GTTT053E9/
AdminOfferUpdateView.form_invalid() missing 2 required positional arguments: 'request_form' and 'request_item_formset'
Models:
request.py
class RequestModel(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="customer_requests")
id = ShortUUIDField(primary_key=True, length=10, max_length=10, prefix="T", alphabet="ARGET0123456789", unique=True, editable=False)
status = models.BooleanField(default=True)
request_title = models.CharField(max_length=300)
......
updated_on = models.DateTimeField(auto_now=True)
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.request_title)
class Meta:
verbose_name_plural = "Requests"
verbose_name = "Request"
def get_absolute_url(self):
return reverse('mytarget:customer_request_details', kwargs={'pk': self.id})
class RequestItem(models.Model):
request_model = models.ForeignKey(RequestModel, on_delete=models.CASCADE, related_name="request_items")
product_name = models.CharField(max_length=300)
......
offer.py
class OfferModel(models.Model):
request_model_name = models.OneToOneField(RequestModel, on_delete=models.CASCADE, primary_key=True)
status = models.BooleanField(default=True)
offer_validity = models.CharField(max_length=50, blank=True)
......
updated_on = models.DateTimeField(auto_now=True)
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.request_model_name)
class Meta:
verbose_name_plural = "Offers"
verbose_name = "Offer"
def get_absolute_url(self):
return reverse('mytarget:admin_offer_update', kwargs={'pk': self.request_model_name})
Forms:
request_create_form.py
class CustomerRequestForm(forms.ModelForm):
disabled_fields = ("customer",)
class Meta:
model = RequestModel
fields = ("customer", "request_title", "delivery_time", "shipping_country", "shipping_address",
"preferred_currency", "shipping_term", "delivery_term")
widgets = {
'request_title': TextInput(attrs={'class': 'form-control tableFormInputs',
'placeholder': _('Example: Printers, Toner, and Cartridges')}),
......
}
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('customer')
super(CustomerRequestForm, self).__init__(*args, **kwargs)
self.fields['preferred_currency'].queryset = self.fields['preferred_currency'].queryset.translated().order_by("translations__currency_name")
self.fields['shipping_term'].queryset = self.fields['shipping_term'].queryset.translated().order_by("translations__shipping_term")
for field in self.disabled_fields:
self.fields[field].widget = forms.HiddenInput()
self.fields[field].disabled = True
class CustomerRequestItemForm(forms.ModelForm):
class Meta:
model = RequestItem
fields = ("product_name", "product_info", "target_price", "price", "quantity", "dimensions", "net_weight", "gross_weight",
"hs_or_tn_ved_code", "brand", "manufacturer", "origin_country", "manufacturer_address")
exclude = ()
widgets = {
'product_name': TextInput(attrs={'class': 'form-control tableFormInputs'}),
......
}
RequestItemInlineFormset = inlineformset_factory(RequestModel, RequestItem,
form=CustomerRequestItemForm,
extra=1,
can_delete=True
)
offer_update_form.py
class AdminOfferUpdateForm(forms.ModelForm):
disabled_fields = ()
hidden_fields = ("request_model_name",)
request_title = forms.CharField(required=False, widget=TextInput(attrs={'class': 'form-control tableFormInputs', 'placeholder': _('Example: Printers, Toner, and Cartridges')}))
......
class Meta:
model = OfferModel
fields = ("request_model_name", "offer_validity", ......
)
widgets = {'offer_validity': TextInput(attrs={'class': 'form-control tableFormInputs'}),
......
'is_detailed_offer': CheckboxInput(attrs={'class': 'form-check-input'}),
}
def __init__(self, *args, **kwargs):
super(AdminOfferUpdateForm, self).__init__(*args, **kwargs)
self.fields["preferred_currency"].choices = [(c.id, c.currency_name) for c in Currency.objects.all()]
self.fields["shipping_term"].choices = [(st.id, st.shipping_term) for st in ShippingTerm.objects.all()]
self.fields["delivery_term"].choices = [(dt.id, dt.delivery_term) for dt in DeliveryTerms.objects.all()]
self.fields["request_statuses"].choices = [(r.id, r.status) for r in RequestStatus.objects.all()]
for field in self.disabled_fields:
self.fields[field].disabled = True
for field in self.hidden_fields:
self.fields[field].widget = forms.HiddenInput()
Views:
offer_update_view.py
#method_decorator([login_required(login_url=reverse_lazy("accounts:signin")), user_is_superuser], name='dispatch')
class AdminOfferUpdateView(UpdateView):
model = OfferModel
form_class = AdminOfferUpdateForm
template_name = "mytarget/admin_offer_update.html"
def get_context_data(self, **kwargs):
context = super(AdminOfferUpdateView, self).get_context_data(**kwargs)
if self.request.POST:
context['request_form'] = AdminOfferUpdateForm(self.request.POST, instance=self.object.request_model_name)
context['request_item_formset'] = RequestItemInlineFormset(self.request.POST, instance=self.object.request_model_name)
else:
context['request_form'] = AdminOfferUpdateForm(instance=self.object.request_model_name)
context['request_item_formset'] = RequestItemInlineFormset(instance=self.object.request_model_name)
return context
def form_valid(self, form):
context = self.get_context_data()
request_form = context['request_form']
request_item_formset = context['request_item_formset']
with transaction.atomic():
self.object = form.save()
if request_form.is_valid() and request_item_formset.is_valid():
request_form.instance = self.object.request_model_name
request_form.save()
request_item_formset.instance = self.object.request_model_name
request_item_formset.save(commit=False)
for ri in request_item_formset:
ri.save(commit=False)
request_item_formset.save()
return super(AdminOfferUpdateView, self).form_valid(form)
def form_invalid(self, form, request_form, request_item_formset):
return self.render_to_response(
self.get_context_data(form=form, request_form=request_form, request_item_formset=request_item_formset)
)
def get_initial(self):
self.object = self.get_object()
if self.object:
return {"request_model": self.object.request_model_name, "request_item_formset": self.object.request_model_name}
return super().initial.copy()
def get_success_url(self):
return reverse('mytarget:admin_offer_update', kwargs={'pk': self.object.id})
I solved my problem. I created a button function that creates a new model with inheritance of other model fields. In this way, there is no need to edit the form of the other model inside the form of my current model.
In Django, I want to build a form that collects shipping addresses from users! Then save them to database
There is views.py starts with defining a function "is_valid_form(values)"
def is_valid_form(values):
valid = True
for field in values:
if field == '':
valid = False
return valid
class EnCheckoutView(View):
def get(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
form = CheckoutForm()
context = {
'form': form,
'couponform': CouponForm(),
'order': order,
'DISPLAY_COUPON_FORM': True
}
shipping_address_qs = Address.objects.filter(user=self.request.user, address_type='S', default=True)
if shipping_address_qs.exists():
context.update({
'default_shipping_address': shipping_address_qs[0]
})
return render(self.request, 'en-checkout-page.html', context)
except ObjectDoesNotExist:
messages.info(self.request, 'You do not have an active order.')
return redirect('core:en-checkout')
def post(self, *args, **kwargs):
try:
order = Order.objects.get(user=self.request.user, ordered=False)
except ObjectDoesNotExist:
messages.warning(self.request, 'You do not have an active order')
return redirect('core:en-order-summary')
form = CheckoutForm(self.request.POST or None)
if form.is_valid():
use_default_shipping = form.cleaned_data.get("use_default_shipping")
if use_default_shipping:
print('Using the default shipping address')
address_qs = Address.objects.filter(user=self.request.user, default=True)
if address_qs.exists():
shipping_address = address_qs[0]
order.shipping_address = shipping_address
order.save()
else:
messages.info(self.request, 'No default shipping address available')
return redirect('core:en-checkout')
else:
print('User is entering a new shipping address')
customer_name = form.cleaned_data.get('customer_name')
phone = form.cleaned_data.get('phone')
email = form.cleaned_data.get('email')
shipping_address1 = form.cleaned_data.get('shipping_address1')
shipping_address2 = form.cleaned_data.get('shipping_address2')
en_shipping_country = form.cleaned_data.get('en_shipping_country')
shipping_zip = form.cleaned_data.get("shipping_zip")
if is_valid_form([customer_name, phone, shipping_address1]):
shipping_address = Address(
user=self.request.user,
customer_name=customer_name,
phone=phone,
email=email,
street_address=shipping_address1,
apartment_address=shipping_address2,
country=en_shipping_country,
zip=shipping_zip,
address_type='S'
)
shipping_address.save()
order.shipping_address = shipping_address
order.save()
set_default_shipping = form.cleaned_data.get('set_default_shipping')
if set_default_shipping:
shipping_address.default = True
shipping_address.save()
else:
messages.info(self.request, 'Please ***fill in the required shipping address fields')
en_payment_option = form.cleaned_data.get('en_payment_option')
if en_payment_option == 'S':
return redirect('core:en-payment', en_payment_option='Pay with credit card')
elif en_payment_option == 'P':
return redirect('core:ar-delivery', en_payment_option='Cash on delivery')
else:
messages.warning(self.request, 'Invalid payment option selected')
return redirect('core:en/checkout')
Why this form does not save the address to the database?
I could have posted forms.py, html template, and models.py, but I guess that will explain the problem.
forms.py
EN_PAYMENT_CHOICES = (
('S', 'Pay with credit card'),
('P', 'Cash on delivery')
)
class CheckoutForm(forms.Form):
customer_name = forms.CharField(max_length=100, required=True)
phone = forms.IntegerField(required=True)
email = forms.EmailField()
shipping_address1 = forms.CharField(required=True)
shipping_address2 = forms.CharField(required=False)
ar_shipping_country = CountryField(blank_label='(اختار البلد)').formfield(
required=False,
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100',
}))
en_shipping_country = CountryField(blank_label='(Choose a country)').formfield(
required=False,
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100',
}))
shipping_zip = forms.CharField(required=False)
set_default_shipping = forms.BooleanField(required=False)
use_default_shipping = forms.BooleanField(required=False)
payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=PAYMENT_CHOICES)
en_payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=EN_PAYMENT_CHOICES)
models.py
class Address(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
customer_name = models.CharField(max_length=100, null=True)
phone = models.IntegerField(null=True)
email = models.EmailField(null=True)
street_address = models.CharField(max_length=250)
apartment_address = models.CharField(max_length=250)
country = CountryField(multiple=False, null=True)
zip = models.CharField(max_length=100)
address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES)
default = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural = 'Addresses'
I'm trying to make an editing page for the users to update an object data. However, form.is_valid() keeps failing, I have no idea why.
My model:
class Thread(models.Model):
title = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(max_length=10000)
USER_TYPES = (
('INI','Iniciante'),
('INT','Intermediário'),
('AVA','Avançado')
)
user_type = models.CharField(max_length=20, choices = USER_TYPES, default='INI')
category = models.ForeignKey(Category)
orcamento = models.IntegerField(default=0)
slug = models.SlugField(max_length=40, unique=True)
def get_absolute_url(self):
return "/%s/" % self.slug
def __str__(self):
return self.title
def save(self, **kwargs):
slug_str = "%s %s" % (self.category, self.title)
unique_slugify(self, slug_str)
super(Thread, self).save(**kwargs)
My view:
def edit_thread(request, thread_slug):
thread = Thread.objects.get(slug=thread_slug)
if request.method == 'POST':
form = EditThread(request.POST)
if form.is_valid():
thread.title = form.cleaned_data['title']
thread.orcamento = form.cleaned_data['orcamento']
thread.user_type = form.cleaned_data['experiencia']
thread.body = form.cleaned_data['pergunta']
thread.save()
return HttpResponseRedirect('/thread' + thread.get_absolute_url())
else:
data = {'title' : thread.title, 'experiencia':thread.user_type, 'orcamento' : thread.orcamento, 'pergunta': thread.body}
form = EditThread(initial=data)
return render(request, 'edit_thread.html', {
'form': form })
My form:
class EditThread(forms.ModelForm):
title = forms.CharField(label='Título', max_length=200, error_messages=my_default_errors)
orcamento = forms.IntegerField(label='Preço máximo', error_messages=my_default_errors)
experiencia = forms.ChoiceField(label='Você é um usuário...', choices=Thread.USER_TYPES, error_messages=my_default_errors)
pergunta = forms.CharField(label='Pergunta', widget=forms.Textarea, error_messages=my_default_errors)
class Meta:
model = Thread
def __init__(self, *args, **kwargs):
super(EditThread, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Div('title',
'experiencia',
PrependedAppendedText('orcamento', 'R$', ',00', active=True),
'pergunta',
FormActions(
Submit('save', 'Salvar alterações'),
)))
When accessing the page, the form gets pre-populated with the object's data as it should.
Your form should be inherited from the simple forms.Form instead of the forms.ModelForm:
class EditThread(forms.Form):
...
I would suggest you look at django's class based UpdateView. It can generate an update form for you or you could give it a custom ModelForm by overriding the form_class attribute on your view. When using a ModelForm, you also have to specify which model the form is for eg:
class EditThread(forms.ModelForm):
"field definitions ..."
class Meta:
model = Thread
fields = ['my_field_1', 'my_field_2']
Can I get the value of the field which I am not showing in form? I want to pass ref_id in session.
This is my model:
def _createId():
"""
"""
return hexlify(os.urandom(4))
class jobpost(models.Model):
item_types = (
('Full Time','Full Time'),
('Part Time','Part Time'),
('Contract','Contract'),
)
posttype= (
('Job','Job'),
('Classified','Classified'),
('Project/Task','Project/Task'),
('Internship','Internship'),
)
#user = models.ForeignKey(User)
job_id = models.AutoField(primary_key=True)
country= models.ForeignKey(Country,to_field = 'country_name', null=True)
#user = models.ForeignKey(User, editable = False)
post_type = models.CharField(max_length=255,null=True, choices=posttype,default='Job')
job_type = models.CharField(max_length=255,null=True, choices=item_types,default='Full Time')
job_location = models.CharField(max_length=255,null=True)
job_title = models.CharField(max_length=255,null=True)
job_description = models.TextField(null=True)
start_date = models.DateField(null=True, help_text="mm/dd/yyyy")
end_date = models.DateField(null=True, help_text="mm/dd/yyyy")
how_to_apply = models.CharField(max_length=255,null=True)
ref_id = models.CharField(max_length=32, default=_createId)
def __unicode__(self):
return unicode(self.country)
return self.post_type
return self.job_location
return self.job_type
return self.job_title
return self.job_description
return self.start_date
return self.end_date
return self.how_to_apply
return self.ref_id
means i am not displaying it in my form and i want to pass this value in session in next form..
can anyone tell me how can i do this? and how can i pass the primary key of the form in next form ?
forms.py
class JobPostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(JobPostForm, self).__init__(*args, **kwargs)
self.fields['ref_id'].widget = forms.HiddenInput()
class Meta:
model = jobpost
views.py
def your_view(request):
if request.method == 'POST':
form = JobPostForm(request.POST)
if form.is_valid():
request.session['ref_id'] = form.cleaned_data.get('ref_id')
pk = form.save()
request.session['pk'] = pk.id
else:
form = JobPostForm()
return render(request, page.html,{'form': form})