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)
Related
I am new using Django and I want to save 4 different forms using CreateView. I am able to save 3 of them:
Product Form
Product Cost Form
Product Prices Form
But with Product inventory Form, I am getting this error: form_valid() takes 2 positional arguments but 5 were given.
Product inventory Form:
class ProdInvForm2(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Row(
Column('invmax', css_class='form-group col-md-6 mb-0'),
Column('invmin', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
)
class Meta:
model = ProdInv
# fields = ('invmin', 'invmax')
widgets = {
'invmax': NumberInput(
attrs={
'placeholder': 'Inventario Maximo',
}
),
'invmin': NumberInput(
attrs={
'placeholder': 'Inventario Minimo',
}
),
}
# esto es para excluir campos que no quieres que aparezcan
#, 'invact', 'invord', 'invres'
exclude = ['user_updated', 'user_creation', 'prod', 'invact', 'invord', 'invres']
Product Inventory Models:
class ProdInv(BaseModel):
prod = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Producto')
invact = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Actual')
invres = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Reservado')
invord = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Ordenado')
invmax = models.IntegerField(default=0, blank=True, verbose_name='Inventario Maximo')
invmin = models.IntegerField(default=0, blank=True, verbose_name='Inventario Minimo')
def toJSON(self):
item = model_to_dict(self, exclude=['user_creation', 'user_updated'])
item['prod'] = self.prod.toJSON()
return item
def __str__(self):
return self.prod.name
class Meta:
verbose_name = 'Inventario de Producto'
verbose_name_plural = 'Inventario de Productos'
ordering = ['id']
CreateView:
class ProductCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Product
form_class = ProductForm
template_name = 'product/create.html'
success_url = reverse_lazy('erpInv:product_list')
permission_required = 'erpAdm.add_product'
url_redirect = success_url
#method_decorator(csrf_exempt)
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':
AttrValueFormSet = formset_factory(AttrValueForm, can_delete=True, extra=1)
formprod = ProductForm(request.POST)
formcost = ProdCostForm(request.POST)
formprice = ProdPriceForm(request.POST)
formprodinv = ProdInvForm2(request.POST)
AV_formset = AttrValueFormSet(request.POST)
with transaction.atomic():
if formprod.is_valid() and formcost.is_valid() and formprice.is_valid() \
and formprodinv.is_valid():
return self.form_valid(formprod, formcost, formprice, formprodinv)
else:
return self.form_invalid(formprod, formcost, formprice, formprodinv)
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
# acuerdate cuando es coleccion de elementos, hay que serializar con safe=flase
return JsonResponse(data, safe=False)
def form_valid(self, formprod, formcost, formprice, formprodinv):
# hubo que cmentar e save del form, para que funcione el save()
with transaction.atomic():
prod = formprod.save(commit=True)
print(prod.pk)
price = formprice.save(commit=False)
price.prod_id = prod.pk
cost = formcost.save(commit=False)
cost.prod_id = prod.pk
print(cost)
inv = formprodinv.save(commit=False)
inv.prod_id = prod.pk
print(inv)
inv.save()
cost.save()
price.save()
return super().form_valid(formprod, formcost, formprice, formprodinv)
def form_invalid(self, formprod, formcost, formprice, formprodinv):
return self.render_to_response(
self.get_context_data(formprod=formprod.errors, formcost=formcost.errors, formprice=formprice.errors,
formprodinv=formprodinv.errors))
# Dont Know which one to use as return statement
# return super().form_invalid(formprod=formprod.errors, formcost=formcost.errors, formprice=formprice.errors,
# formprodinv=formprodinv.errors)
def get_context_data(self, **kwargs):
# AVForm = AttrValueForm(prefix='avprefix')
AttrValueFormSet = formset_factory(AttrValueForm, can_delete=True, extra=1)
context = super().get_context_data(**kwargs)
context['title'] = 'Creación un Producto'
context['entity'] = 'Productos'
context['list_url'] = self.success_url
context['action'] = 'add'
context['formcost'] = ProdCostForm()
context['formprice'] = ProdPriceForm(prefix='precio')
context['formprodinv'] = ProdInvForm2(prefix='invent')
# Next step try to use formset to save product attributes
# context['AV_formset'] = AttrValueFormSet(prefix='avprefix')
# context['avHelper'] = AVHelper()
return context
I did the test and comment "transaction.atomic()". I was able to save to other forms, but do not know why I am having this problem with the Product Inventory Form.
Hope someone can highlight what I am doing wrong.
Cheers and Happy New Year
To solve my problem I saved the forms inside de def POST. Instead of using the form_valid().
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
AttrValueFormSet = formset_factory(AttrValueForm, can_delete=True, extra=1)
formprod = ProductForm(request.POST)
formcost = ProdCostForm(request.POST)
formprice = ProdPriceForm(request.POST)
formprodinv = ProdInvForm2(request.POST)
AV_formset = AttrValueFormSet(request.POST)
with transaction.atomic():
if formprod.is_valid() and formcost.is_valid() and formprice.is_valid() and formprodinv.is_valid():
print('los form son validos')
prod = formprod.save(commit=True)
print(prod.pk)
price = formprice.save(commit=False)
print('precio')
print(formprice.cleaned_data)
price.prod_id = prod.pk
cost = formcost.save(commit=False)
print('costo')
cost.prod_id = prod.pk
inv = formprodinv.save(commit=False)
print('Inventario')
print(formprodinv.cleaned_data)
inv.prod_id = prod.pk
inv.save()
cost.save()
price.save()
else:
print('los forms NO son validos')
return formprod.errors, formprice.errors, formcost.errors, formprodinv.errors
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
# acuerdate cuandp es coleccion de elementos, hay que serializar con safe=flase
return JsonResponse(data, safe=False)
When i edit formset the ModelChoiceField don't show initial value (it show the empty label). I use this example
https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html
demande\forms.py
class LinkForm(forms.Form):
etabz = forms.ModelChoiceField(empty_label="Choisir un établissement",\
queryset=Etablissement.objects.all().order_by('univ','etablissement').distinct(),
)
# etabz = forms.CharField()
def __init__(self, *args, **kwargs):
dbz = kwargs.pop("dbz", None)
super(LinkForm, self).__init__(*args, **kwargs)
if dbz:
self.fields["etabz"].queryset = Etablissement.objects.filter(univ__corps=dbz)
class BaseLinkFormSet(BaseFormSet):
def clean(self):
if any(self.errors):
return
anchors = []
urls = []
duplicates = False
for form in self.forms:
if form.cleaned_data:
dona = form.cleaned_data.get('etabz')
anchor = dona.etablissement
if anchor :
if anchor in anchors:
duplicates = True
anchors.append(anchor)
if duplicates:
raise forms.ValidationError(
'Vous ne pouvez choisir le même établissement plusiuers fois.',
code='duplicate_etab'
)
def __init__(self, *args, **kwargs):
super(BaseLinkFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
Demande\views.py
#login_required
def demande(request):
user = request.user
corpsorigine = user.profile.corps
uz = get_object_or_404(session, active=True, destine = user.profile.corps)
choice_links = choix.objects.filter(demandeur = user, session = uz )
link_data = [{'etabz': l}
for l in choice_links]
LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet, extra=1)
if request.method == 'POST':
link_formset = LinkFormSet(request.POST,form_kwargs={'dbz':corpsorigine })
if link_formset.is_valid():
new_links = []
for link_form in link_formset:
dona = link_form.cleaned_data.get('etabz')
try:
univ = dona.univ
etablissementa = dona.etablissement
except:
messages.error(request, 'Une exception à provoqué une erreur. veuillez ré-essayer ultérieurement')
return redirect(reverse('blog:post_list'))
if etablissementa and univ:
new_links.append(choix(demandeur = user,session=uz.annee_session, etablissement_demande=etablissementa, universite_demande=univ))
try:
with transaction.atomic():
UserLink = choix.objects.all()
UserLink.filter(session= uz.annee_session,demandeur = user).delete()
UserLink.bulk_create(new_links)
messages.success(request, 'Votre demande à été correctement saisie/mis à jour.')
return redirect(reverse('blog:post_list'))
except IntegrityError: # If the transaction failed
messages.error(request, 'Une exception à provoqué une erreur. veuillez ré-essayer ultérieurement')
return redirect(reverse('blog:post_list'))
else:
link_formset = LinkFormSet(initial=link_data,form_kwargs={'dbz':corpsorigine })
context = {
'uz':uz,
'link_formset': link_formset,
'choice_links':choice_links
}
return render(request, 'edit_pro.html', context)
Account\Models.py
class universite (models.Model):
gouvernorat= models.CharField(max_length=250)
universite = models.CharField(max_length=250)
corps = models.CharField(max_length=20, choices=corps_CHOICES)
class Meta:
unique_together = ('gouvernorat', 'universite')
def __str__(self):
return self.universite
class etablissement(models.Model):
etablissement = models.CharField(max_length=250)
univ = models.ForeignKey(universite, related_name='etab_universites')
def __unicode__(self):
return "{} de l'universite {}".format(self.etablissement,self.univ)
Demande\models.py
class choix(models.Model):
demandeur = models.ForeignKey(User, related_name='user_choice')
# universite_demande = models.ForeignKey(universite, related_name='universite_choice')
session = models.CharField(max_length=250)
universite_demande = models.CharField(max_length=250)
etablissement_demande = models.CharField(max_length=250)
class Meta:
unique_together = ('demandeur', 'session','etablissement_demande')
def __unicode__(self):
return "{} de l'universite {}".format(self.etablissement_demande, self.universite_demande)
In demande\forms.py If i change forms.ModelChoiceField... to forms.CharField it works perfectly. How it can works on ModelChoiceField ?
I am setting up a djangos channel and I am receiving the following error when I visit Threadview at the url below. It seems that it can't query the user? The user is "dominic" and I am signed in, but the view doesn't seem to be able to request.user.. See error message referencing line 99 below.
http://127.0.0.1:8000/portal/messages/dominic/
Error:
Exception Type: TypeError
Exception Value:
'NoneType' object is not iterable
Exception Location: /home/dominic/Desktop/Projects/robobud/web/robobud/portal/views.py in get_object, line 99
Python Executable: /home/dominic/Desktop/Projects/robobud/web/env/bin/python3
Line 99 from views.py:
def get_object(self):
...
obj, created = Thread.objects.get_or_new(self.request.user, other_username) #Line99
Urls.py:
#channels
path("messages/", InboxView.as_view()),
#url(r"^messages/(?P<username>[\w.#+-]+)", ThreadView.as_view(), name='thread'),
path('messages/<username>/', ThreadView.as_view(), name='thread'),
Views.py:
class InboxView(LoginRequiredMixin, ListView):
template_name = 'portal/inbox.html'
def get_queryset(self):
return Thread.objects.by_user(self.request.user)
class ThreadView(LoginRequiredMixin, FormMixin, DetailView):
template_name = 'portal/thread.html'
form_class = ComposeForm
success_url = './'
def get_queryset(self):
return Thread.objects.by_user(self.request.user)
def get_object(self):
other_username = self.kwargs.get("username")
obj, created = Thread.objects.get_or_new(self.request.user, other_username)
if obj == None:
raise Http404
return obj
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = self.get_form()
return context
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
thread = self.get_object()
user = self.request.user
message = form.cleaned_data.get("message")
ChatMessage.objects.create(user=user, thread=thread, message=message)
return super().form_valid(form)
models.py
class ThreadManager(models.Manager):
def by_user(self, user):
qlookup = Q(first=user) | Q(second=user)
qlookup2 = Q(first=user) & Q(second=user)
qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct()
return qs
def get_or_new(self, user, other_username): # get_or_create
username = user.username
if username == other_username:
return None
qlookup1 = Q(first__username=username) & Q(second__username=other_username)
qlookup2 = Q(first__username=other_username) & Q(second__username=username)
qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct()
if qs.count() == 1:
return qs.first(), False
elif qs.count() > 1:
return qs.order_by('timestamp').first(), False
else:
Klass = user.__class__
user2 = Klass.objects.get(username=other_username)
if user != user2:
obj = self.model(
first=user,
second=user2
)
obj.save()
return obj, True
return None, False
class Thread(models.Model):
first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first')
second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second')
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = ThreadManager()
#property
def room_group_name(self):
return 'chat_{self.id}' #Removed f
def broadcast(self, msg=None):
if msg is not None:
broadcast_msg_to_chat(msg, group_name=self.room_group_name, user='admin')
return True
return False
class ChatMessage(models.Model):
thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL)
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='sender', on_delete=models.CASCADE)
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
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.
i have these models, states and cities,
class State(models.Model):
name = models.CharField(max_length=255)
shortname = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=255)
state = models.ForeignKey(State)
def __unicode__(self):
return self.name
and im getting a "IntegrityError (1048, "Column 'state_id' cannot be null")" when i save the form, the weird thing is that the state are created, this is what im doing
def form_valid(self, form):
city = form.cleaned_data['city_name']
state = form.cleaned_data['state_name']
m = State.objects.get_or_create(name=state)
state_id = m[0].id
City.objects.get_or_create(name=state, id=state_id)
form.save()
what can i do?
class StoreForm(ModelForm):
class Meta:
model = Store
fields = '__all__'
class StoreGoogleMapForm(StoreForm):
city_name = forms.CharField(
widget=forms.TextInput(
attrs={'readonly': 'readonly'}
)
)
state_name = forms.CharField(
widget=forms.TextInput(
attrs={'readonly': 'readonly'}
)
)
class Meta(StoreForm.Meta):
exclude = (
'state', 'city'
)
widgets = {
'retailer': forms.HiddenInput(),
'lon': forms.HiddenInput(),
'lat': forms.HiddenInput(),
}
def clean(self):
cleaned_data = super(StoreGoogleMapForm, self).clean()
city_name = cleaned_data.get("city_name")
state_name = cleaned_data.get("state_name")
return cleaned_data
class NewStore(LoginRequiredMixin, CreateView):
model = Store
template_name = "new_store.html"
form_class = StoreGoogleMapForm
def get_context_data(self, **kwargs):
ctx = super(NewStore, self).get_context_data(**kwargs)
ctx['cobrand'] = self.retailer
return ctx
def get(self, request, *args, **kwargs):
self.retailer = get_object_or_404(Cobrand, pk=kwargs['pk'])
self.object = Store(retailer=self.retailer)
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
def form_valid(self, form):
city = form.cleaned_data['city_name']
state = form.cleaned_data['state_name']
m = State.objects.get_or_create(name=state)
City.objects.get_or_create(name=city, state=m[0])
form.save()
messages.add_message(
self.request,
messages.SUCCESS,
'The store was successfuly created!',
extra_tags='success'
)
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse_lazy('store_list', kwargs={'pk': self.kwargs['pk']})
def post(self, request, *args, **kwargs):
self.retailer = get_object_or_404(Cobrand, pk=kwargs['pk'])
self.object = Store(retailer=self.retailer)
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
fix the line as
City.objects.get_or_create(name=city, state=m[0])
you don't need form.save().
Anyway this code is a bit strange, what about your Form?
get_or_create returns two parameters https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.get_or_create and you can then pass the object straight into the next statement.
state, created = State.objects.get_or_create(name=state)
City.objects.get_or_create(name=state, state=state)
suspect you shouldn't be doing this in form_valid but without rest of your code, can't be sure.