im having a problem with a with a post request of a form, this is how the models.py is:
class Invitaciones(models.Model):
class Meta:
verbose_name_plural = "Invitaciones"
tipos_cedula = (
("Venezolano", "Venezolano"),
("Extranjero", "Extranjero"),
)
estados = (
("Disponible", "Disponible"),
("Usado", "Usado"),
)
def random_string():
return str(random.randint(10000, 99999))
año = int(datetime.datetime.now().year)
nombre = models.CharField(max_length=300, null=False, blank=False)
apellido = models.CharField(max_length=300, null=False, blank=False)
tipo_cedula = models.CharField(choices=tipos_cedula, max_length=50, null=False, blank=False)
cedula = models.PositiveIntegerField(null=False, blank=False)
codigo = models.CharField(max_length=99999999, default = random_string, null=False, blank=False, editable=False)
usuario = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False)
estado = models.CharField(max_length=250, choices=estados, default="Disponible", null=False, blank=False)
fecha = models.DateField(default=timezone.now, validators=[validators.MaxValueValidator(datetime.date(año, 12, 31),message="No puedes elegir una fecha que este mas alla de este año"), validators.MinValueValidator(datetime.date.today(),message="No puedes elegir una fecha anterior a la de hoy")])
envio = models.DateField(auto_now=True)
def __str__(self):
return '%s %s %s %s %s' % (self.usuario, self.nombres, self.apellidos, self.cedula, self.codigo,)
And this is how the views.py is:
from cuentas.models import Invitaciones
from cuentas.forms import InvitacionesForm
from django.views.generic import TemplateView
from django.contrib import messages
from django.shortcuts import render, redirect, HttpResponse, render_to_response
class InvitacionesView(TemplateView):
template_name = 'socios/pases.html'
def get(self, request):
form = InvitacionesForm()
invitaciones = Invitaciones.objects.all()
args = {'form': form, 'titulo': 'Pases de Invitación', 'invitaciones': invitaciones}
return render(request, self.template_name, args)
def post(self, request):
form = InvitacionesForm(request.POST)
if form.is_valid():
nombre = form.cleaned_data['nombre']
apellido = form.cleaned_data['apellido']
tipo_cedula = form.cleaned_data['tipo_cedula']
cedula = form.cleaned_data['cedula']
fecha = form.cleaned_data['fecha']
post = form.save(commit=False)
post.user = request.user
post.usuario_id = post.user.id
post.save()
form = InvitacionesForm()
messages.success(request, 'El pase de invitación a sido registrado.')
return redirect('pases')
else:
messages.error(request, 'Por favor, verifica tus datos')
form = InvitacionesForm()
return redirect('pases')
args = {'form': form, 'nombre': nombre, 'apellido': apellido, 'tipo_cedula': tipo_cedula, 'fecha': fecha, 'cedula': cedula, 'estado': estado,}
return render(request, self.template_name, args)
And this is the error I get:
Traceback (most recent call last):
File "C:\Users\Kuipumu\Envs\py1\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\Kuipumu\Envs\py1\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Kuipumu\Envs\py1\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Kuipumu\Envs\py1\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Kuipumu\Envs\py1\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Kuipumu\Envs\py1\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Kuipumu\Desktop\Oricao\dist\cuentas\views.py", line 122, in post
args = {'form': form, 'nombre': nombre, 'apellido': apellido, 'tipo_cedula': tipo_cedula, 'fecha': fecha, 'cedula': cedula, 'estado': estado,}UnboundLocalError: local variable 'nombre' referenced before assignment
I can't find why im getting this error, i made the model, view, and form based on another model, view and form that is already perfectly working. The object can be registered thought the admin view, but not trought the user view. ¿Why im getting this local variable error?.
you cant access the fields inside the
form.valid()
like that outside,