Resetar senha pelo RG Django

Boa noite…estou tentando fazer a
recuperação de senha do usuario
atraves do RG…mas ao enviar o formulário com o RG…
ocorre esse erro..alguém poderia me ajudar?

form.py

class PasswordResetForm(forms.Form):

    nrg = forms.CharField(label='RG')

    def clean_nrg(self):
        nrg = self.cleaned_data('nrg')
        if User.objects.filter(nrg=nrg).exists():
            return nrg
        raise forms.ValidationError(
            'Nenhum usuário encontrado com esse RG'
        )

    def save(self):
        user = User.objects.get(nrg=self.cleaned_data('nrg'))
        key = generate_hash_key(user.username)
        reset = PasswordReset(key=key, user=user)
        reset.save()
        return reset

views.py

def password_reset(request):
    template_name = 'usuarios/password_reset.html'
    context = {}
    form = PasswordResetForm(request.POST or None)
    if form.is_valid():
        form.save()
        context('success') = True
    context('form') = form
    return render(request, template_name, context)


def password_reset_confirm(request, key):
    template_name = 'usuarios/password_reset_confirm.html'
    context = {}
    reset = get_object_or_404(PasswordReset, key=key)
    form = SetPasswordForm(user=reset.user, data=request.POST or None)
    if form.is_valid():
        form.save()
        context('success') = True
        return redirect('usuarios:login')
    context('form') = form
    return render(request, template_name, context)

urls.py

urlpatterns = (
    path('', views.index, name="index"),
    path('entrar/', LoginView.as_view(template_name='usuarios/login.html'), name="login"),
    path('sair/', LogoutView.as_view(template_name='usuarios/login.html'), name="logout"),
    path('cadastre-se/', views.register, name="register"),
    path('nova-senha/', views.password_reset, name="password_reset"),
    path('confirmar-nova-senha/(?P<key>w+)/$', views.password_reset_confirm, name="password_reset_confirm"),
    path('editar/', views.edit, name="edit"),
    path('editar-senha/', views.edit_password, name="edit_password"),
)

Mensagem do erro

Mensagem do erro

python – Django Test DoesNotExist : `matching query does not exist` error when testing functions in the models

I’m still new to the language so my implementations might not be correct. I get this error when testing the methods in my models in Django with Unit testing. The problem is that two different functions has the same implementation but only one of them triggers the error.

Can anyone explain why this happens and suggest any hints on how to resolve this?

Thank you

Here are the functions in models.py:

class Staff(models.Model):
    ------------------------
    # Get the current (latest) commission the staff has at the moment (Function 1)
    @property
    def current_commission(self):
        return Commission.objects.filter(staff=self).latest('date_applied').sale_commission

class Sale(models.Model):
    staff_id = models.ForeignKey(Staff, on_delete=models.CASCADE)
    product_id = models.ForeignKey(LemonadeProduct, on_delete=models.DO_NOTHING)
    quantity = models.IntegerField(default=1)
    date_sale = models.DateTimeField(auto_now=True)

    @property (Function 2)
    def get_staff_commission(self):
        commission = Commission.objects.filter(staff=self.staff_id, date_applied__lte=self.date_sale).latest('date_applied')
        return "%.2f" % (self.product_id.price * self.quantity * (commission.sale_commission / 100))

Here are my test cases in tests.py:

def create_commission(commission, days, staff):
    time = timezone.now() + datetime.timedelta(days=days)
    return Commission.objects.create(sale_commission=commission, date_applied=time, staff=staff)

# Create your tests here.
class StaffModelTestCase(TestCase):
    def test_current_commission(self):
        staff_1 = Staff(name='A', position='B')
        staff_1.save()

        com_1 = create_commission(10, 0, staff_1)
        com_1.save()

        # No errors in this line
        self.assertEqual(staff_1.current_commission, 10)


class SaleModelTestCase(TestCase):
    def setUp(self):
        --------------------------------

    def test_get_staff_commission(self):
        test_sale_1 = Sale.objects.get(quantity=1)
        test_sale_2 = Sale.objects.get(quantity=2)

        staff = Staff.objects.get(name="C")

        first_commission = create_commission(10, 0, staff)
        first_commission.save()

        # 'Commission matching query does not exist' Error
        self.assertEquals(test_sale_1.get_staff_commission, "2")

Search javascript en Django – Stack Overflow en español

tengo el siguiente código javascript para hacer una búsqueda (search con botón en la barra) en una página en Django 2.2, funciona pero me lo resalta por menos de 1 segundo, es decir encuentra la palabra la resalta y ya no la resalta más, como dije lo hace menos de 1 segundo y la idea es que quede marcada y en lo posible que siga mostrando otras coincidencias como hace CTRL + F en los navegadores. Alguien puede ayudarme con un código que sí funcione bien? Gracias.

<script type="text/javascript">
  function FindNext () {
    var str = document.getElementById ("findInput").value;
    if (str == "") {
      alert ("Por favor, introduzca un texto para buscar!");
      return;
    }

    if (window.find) {        // Firefox, Google Chrome, Safari
      var found = window.find (str);
      if (!found) {
        alert ("No se encontró el siguiente texto:n" + str);
      }
    }
    else {
      alert ("Su navegador no es compatible!");
    }
  }
</script>

python 3.x – Error got an unexpected keyword argument ‘auto_id’ en formset Django

Soy muy nuevo en desarrollo y mas aún en Django.
He creado una tabla persona, (matricula, nombre e email) y una tabla peticionario (jefe, peticionario, resp_servicio y resp_aplicacion cada uno de estos es una persona a través de clave foranea).Como los dos últimos son opcionales (el rs y ra) quiero trabajar con FormSet.
El caso es que al cargar este formset de la clase persona me da el siguiente error “Persona() got an unexpected keyword argument ‘auto_id'”.
He buscado pero no encuentro una solución que entienda (repito, estoy muy perdido), el código es el siguiente:
models.py:`

from django.db import models
from recogidaDatos import choices


class Persona(models.Model):
    matricula = models.CharField(max_length=7, verbose_name='Matrícula', unique=True)
    nombre = models.CharField(max_length=100, verbose_name='Nombre')
    email = models.EmailField(max_length=150,verbose_name='Email')    

    class Meta:
        verbose_name = 'persona'
        verbose_name_plural = 'personas'
        ordering = ('nombre')

    def __str__(self):
        return self.nombre

class Solicitantes(models.Model):
    jefe = models.ForeignKey(Persona, related_name='jefe', verbose_name="Jefe", on_delete=models.PROTECT)
    peticionario = models.ForeignKey(Persona, related_name='peticionario', verbose_name="Jefe", on_delete=models.PROTECT)
    ra = models.ForeignKey(Persona, related_name='ra', on_delete=models.PROTECT, null=True, blank=True, verbose_name="Responsable aplicación")
    rs = models.ForeignKey(Persona, related_name='rs', on_delete=models.PROTECT, null=True, blank=True, verbose_name="Responsable Servicio")

    class Meta:
        verbose_name = 'Solicitantes'
        verbose_name_plural = 'Solicitantes'
        ordering = ('jefe')

    def __str__(self):
        return self.jefe + self.peticionario + self.ra + self.rs`

forms.py:

    from django import forms
from .choices import *
from .models import *


class FormPersona(forms.ModelForm):

    class Meta:
        model = Persona
        exclude = ()

views.py:

from django.shortcuts import render
from django.forms import formset_factory
from .models import *
from .forms import *

# Create your views here.

def recogidaDatos(request):

    PersonasFormset = formset_factory(Persona, extra=4 ,max_num=4)
    personas = PersonasFormset()



    if request.method =='POST':
        personas = PersonasFormset(data=request.POST)
        if  personas.is_valid():   
            pass         
    return render(request,'recogidaDatos/formulario2.html',{'personas':personas})

template.py:

<form action="" method="POST">
  {% csrf_token %}

    {{personas.management_form}}
    <table>
        {% for persona in personas.forms %}
            {{ persona }}
        {% endfor %}
    </table>


    <input name="" id="" class="btn btn-primary" type="submit" value="Enviar">
  </form>

error:

System check identified no issues (0 silenced).
May 20, 2020 - 15:57:38
Django version 3.0.5, using settings 'ComunicacionesApp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /
Traceback (most recent call last):
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 828, in _resolve_lookup   
    current = current(bit)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 74, in __getitem__       
    return self.forms(index)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoutilsfunctional.py", line 48, in __get__
    res = instance.__dict__(self.name) = self.func(instance)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 137, in forms
    return (
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 138, in <listcomp>       
    self._construct_form(i, **self.get_form_kwargs(i))
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 175, in _construct_form  
    form = self.form(**defaults)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangodbmodelsbase.py", line 500, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Persona() got an unexpected keyword argument 'auto_id'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangocorehandlersexception.py", line 34, in inner    
    response = get_response(request)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangocorehandlersbase.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangocorehandlersbase.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:EscritorioComunicaciones_AppComunicacionesApprecogidaDatosviews.py", line 19, in recogidaDatos
    return render(request,'recogidaDatos/formulario2.html',{'personas':personas})
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoshortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplateloader.py", line 62, in render_to_string 
    return template.render(context, request)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebackendsdjango.py", line 61, in render  
    return self.template.render(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 171, in render
    return self._render(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 903, in render_annotated  
    return self.render(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatedefaulttags.py", line 161, in render     
    values = self.sequence.resolve(context, ignore_failures=True)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 670, in resolve
    obj = self.var.resolve(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 795, in resolve
    value = self._resolve_lookup(context)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangotemplatebase.py", line 836, in _resolve_lookup   
    current = getattr(current, bit)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoutilsfunctional.py", line 48, in __get__
    res = instance.__dict__(self.name) = self.func(instance)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 137, in forms
    return (
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 138, in <listcomp>       
    self._construct_form(i, **self.get_form_kwargs(i))
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangoformsformsets.py", line 175, in _construct_form  
    form = self.form(**defaults)
  File "C:UsersvmorenogMiniconda3envswebProfesionallibsite-packagesdjangodbmodelsbase.py", line 500, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Persona() got an unexpected keyword argument 'auto_id'
(20/May/2020 15:57:44) "GET / HTTP/1.1" 500 180395

error en el navegador:introducir la descripción de la imagen aquí La linea 23 aque se refiere el pantallazo es {% for persona in personas.forms %}
Necesito una explicación para niños, jeje.
Gracias de antemano

django rest framework – Mutliple syndicates with established APIs to connect to our point of sale

We have a point of sale system for our tour business which has a REST API to allow syndicates to get tour dates, prices, products and to make bookings. There are four syndicates that make and cancel bookings thru our system, and I have been able to communicate directly with each of the syndicate’s developers who have been flexible and worked with me to test and implement the API. The API does behave slightly differently depending on who is calling, but the system is manageable.

Now we are looking at taking other big name syndicates on board such as Trip Advisor, who don’t communicate well, and are inflexible. They require their endpoints on our system to behave a certain way, some using different protocols (such as gRPC) and ports. Getting our existing application to cater to them will cause the API to be too complicated to test and maintain. The only solution I can think of is to write a separate application for each syndicate with its own hostname dedicated to taking their API calls, and acting as an intermediary to forward the calls. I envisage that I would likely have to overcome latency and use caching using this method, but instinctively that seems easier than maintaining one system to work with all syndicates. I would like some feed back from the community as to whether there is a better way of doing this.

html – Quiero ver una webcam conectada a un servidor django desde un cliente web

Lo único que consigo es ver la webcam del propio cliente con un codigo HTML y JS que lo que hago es acceder a la webcam y proyectarla en un canvas cuando pulsas un botón.

La única forma que encuentro de acceder a la webcam con python es con este código. Pero usa una ventana del sistema… Yo quiero mostrarla en un canvas de HTML (o un div, cualquier cosa me vale).

import sys
import cv2

from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication

# IMPORTAMOS LA INTERFACE .PY
from Interfaces import Principal

# CLASE HEREDADA DE QMAINWINDOW(CONSTRUCTOR DE VENTANAS)


class Camara(QMainWindow):
    # METODO CONSTRUCTOR DE LA CLASE
    def __init__(self, parent=None):
        # INICIAR EL OBJETO QMAINWINDOW
        QMainWindow.__init__(self, parent)

        # CARGAR LA CONFIGURACION DE EL ARCHIVO GRAFICO EN SELF.UI
        self.ui = Principal.Ui_MainWindow()
        self.ui.setupUi(self)

        # CREAMOS UNA VARIABLE DONDE SE VA A GUARDAR LA IMAGEN
        self.imagen = None

        # INICIAMOS LA CAMARA WEB
        # SE UTILIZA LA 0 YA QUE ES LA QUE CORRESPONDE A LA WEBCAM
        # SI QUIEREN USAR OTRA SOLO INVESTIGUEN QUE INDICE TIENE
        # Y CAMBIENLA EN cv2.VideoCapture(?)
        self.captura = cv2.VideoCapture(0)

        # DEFINIMOS EL TAMAÑO DONDE SE VA A MOSTRAR LA IMAGEN
        # ESOS VALORES YO LOS TOME DE EL TAMAÑO DE EL QLABEL EN QUE SE MUESTRA
        self.captura.set(cv2.CAP_PROP_FRAME_HEIGHT, 451)
        self.captura.set(cv2.CAP_PROP_FRAME_WIDTH, 711)

        # SE CREA UN TIMER PARA QUE VAYA ACTUALIZANDO LA IMAGEN EN EL QLABEL
        self.timer = QTimer()

        # SE MANDA A LLAMAR EL METODO PARA MANDAR LA IMAGEN
        self.timer.timeout.connect(self.actualizar)
        self.timer.start(1)

        # CONECTAMOS LOS ELEMENTOS GRAFICOS CON LOS METODOS
        self.ui.MenuSalir.triggered.connect(self.salir)
        self.ui.Capturar.clicked.connect(self.click)

    # METODO PARA ACTUALIZAR LA IMAGEN
    def actualizar(self):
        ret, self.imagen = self.captura.read()
        self.imagen = cv2.flip(self.imagen, 1)

        # SE MANDA A LLAMAR EL METODO MOSTRAR IMAGEN PASANDO 2 PARAMETROS
        self.mostrar_imagen(self.imagen, 1)

    # METODO PARA MOSTRAR LA IMAGEN EN EL QLABEL
    def mostrar_imagen(self, imagen, ventana=1):
        formato = QImage.Format_Indexed8

        if len(imagen.shape) == 3:
            if imagen.shape == 4:
                formato = QImage.Format_RGBA8888
            else:
                formato = QImage.Format_RGB888

        salida = QImage(imagen, imagen.shape(1), imagen.shape(0), imagen.strides(0), formato)
        salida = salida.rgbSwapped()

        if ventana == 1:
            self.ui.Mostrar.setPixmap(QPixmap.fromImage(salida))
            self.ui.Mostrar.setScaledContents(True)

    def click(self):
        cv2.imwrite("prueba.png", self.imagen)

    # METODO PARA SALIR
    def salir(self):
        self.close()


# codigo para lanzar aplicacíon
if __name__ == "__main__":
    # instancia para iniciar una plicacíon
    app = QApplication(sys.argv)
    # crear un objeto de la clase
    ventana = Camara()
    # mostrar la ventana
    ventana.show()
    # ejecutamos la aplicacion
    sys.exit(app.exec())

Así que había pensado acceder a la webcam con python y proyectarla en un canvas. Pero no se como se hace 🙁
Me encantaría que alguien me echase una mano. Muchísimas gracias.

Django: Tengo un wizard NamedUrlSessionWizardView y necesito en uno de los pasos mostrar un formset

En models.py:

class Solicitud143_Step7(ModeloBaseRegistro):
# Formulario Documentación para el proyecto (Step 30)
contribuyente = models.ForeignKey(Contribuyente, on_delete=models.CASCADE, help_text='Contribuyente', verbose_name='Contribuyente')
#num_expediente=models.ForeignKey(Solicitud143_Step1, on_delete=models.CASCADE, help_text='Numero de Expediente', verbose_name='Numero de Expediente')
def Incrementar():
    ultimo = Solicitud143_Step1.objects.all().order_by('num_expediente').last()
    start = 80000
    if not ultimo:
            return int(start)
    registro = ultimo.num_expediente
    registro_int = ultimo.num_expediente
    nuevo_registro_int = registro_int + 1
    return nuevo_registro_int
def get_expediente_url(self, filename): 
    return "Expedientes/%(numero_expediente)s/%(filename)s" % {
        'numero_expediente': self.num_expediente,
        'filename': filename,
    }
num_expediente=models.BigIntegerField(default=Incrementar, verbose_name='Numero de Expediente',primary_key=True)

documentacion_tipo_documento=models.ForeignKey(Tipo_DocumentoPresentar, on_delete=models.CASCADE, verbose_name='Tipo de Documento a Presentar')
documentacion_descripcion=models.CharField(max_length=200, verbose_name='Descripción')
documentacion_documento=models.FileField(verbose_name='Documentos',null=True, blank=True,upload_to=get_expediente_url)

class Meta:
    verbose_name = 'Formulario Documentación para el proyecto'
    verbose_name_plural = 'Formulario Documentación para el proyecto'
    unique_together = ('contribuyente','num_expediente', 'documentacion_tipo_documento', 'documentacion_descripcion')

def __str__(self):
    return self.contribuyente + ' / ' + self.num_expediente + ' / ' + self.documentacion_tipo_documento + ' / ' + self.documentacion_descripcion

En forms.py:

class SolicitudesStep7_Form(forms.ModelForm):
class Meta:
    model=Solicitud143_Step7
    fields = '__all__'
    exclude = ('estado','uc','um',)
    verbose_name='Solicitudes: Step 7'
    label='Solicitudes: Step 7'

def __init__(self, *args, **kwargs):
    super(SolicitudesStep7_Form,self).__init__(*args, **kwargs)
    self.helper = FormHelper(self)
    self.helper.form_tag = False
    self.helper.layout = Layout(
        Fieldset('Documentos del Proyecto',
        #HTML('<legend class="w-auto">Datos Básicos del Proyecto</legend>'),
        Row(
            Column('contribuyente', css_class='form-group col-md-2 mb-0'),
            Column('num_expediente', css_class='form-group col-md-2 mb-0'),
            Column('documentacion_tipo_documento', css_class='form-group col-md-3 mb-0'),
            Column('documentacion_descripcion', css_class='form-group col-md-2 mb-0'),
            Column('documentacion_documento', css_class='form-group col-md-3 mb-0'),
            css_class='form-row'
        ),css_class="border p-2"),            
    )

SolicitudesStep7_FormSet = forms.modelformset_factory(Solicitud143_Step7, SolicitudesStep7_Form, extra= 2, can_delete=True)

En views.py:

class SolicitudFormWizardView(LoginRequiredMixin, NamedUrlSessionWizardView):
template_name = "solicitudes.html"
form_list = (SolicitudesStep1_Form, SolicitudesStep1b_Form, SolicitudesStep2_Form, SolicitudesStep2b_Form, SolicitudesStep2c_Form, SolicitudesStep2d_Form, SolicitudesStep2e_Form, SolicitudesStep2f_Form, SolicitudesStep3_Form, SolicitudesStep4a_Form, SolicitudesStep4b_Form, SolicitudesStep4c_Form, SolicitudesStep4d_Form, SolicitudesStep4e_Form, SolicitudesStep4f_Form, SolicitudesStep4g_Form, SolicitudesStep4h_Form, SolicitudesStep4i_Form, SolicitudesStep4j_Form, SolicitudesStep4k_Form, SolicitudesStep4l_Form, SolicitudesStep4m_Form, SolicitudesStep4n_Form, SolicitudesStep4o_Form, SolicitudesStep4p_Form, SolicitudesStep4q_Form, SolicitudesStep4r_Form, SolicitudesStep5_Form, SolicitudesStep6a_Form, SolicitudesStep6b_Form, ('30',forms.modelformset_factory(Solicitud143_Step7, SolicitudesStep7_Form, extra= 2, can_delete=True)))
login_url = "Usuarios:Login"
file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'media'))

instance = None

def get_step_url(self, step):
    return reverse('Solicitudes:Solicitudes_step', kwargs={'step':step})

def get_form_initial(self, step):
    initial = {}
    usuario = self.request.user
    t = Contribuyente.objects.get(identificador_id=usuario) # Get the list of objects of my database
    if step == '0': 
        initial = {'contribuyente': t.id,'estado_solicitud':'Pendiente',}
    if step == '1': 
        initial = {'contribuyente': t.id,}
    if step == '2': 
        initial = {'contribuyente': t.id,}
    if step == '3': 
        initial = {'contribuyente': t.id,}
    if step == '4': 
        initial = {'contribuyente': t.id,}
    if step == '5': 
        initial = {'contribuyente': t.id,}
    if step == '6': 
        initial = {'contribuyente': t.id,}
    if step == '7': 
        initial = {'contribuyente': t.id,}
    if step == '8': 
        initial = {'contribuyente': t.id,}
    if step == '9': 
        initial = {'contribuyente': t.id,}
    if step == '10':    
        initial = {'contribuyente': t.id,}
    if step == '11':    
        initial = {'contribuyente': t.id,}
    if step == '12':    
        initial = {'contribuyente': t.id,}
    if step == '13':    
        initial = {'contribuyente': t.id,}
    if step == '14':    
        initial = {'contribuyente': t.id,}
    if step == '15':    
        initial = {'contribuyente': t.id,}
    if step == '16':    
        initial = {'contribuyente': t.id,}
    if step == '17':    
        initial = {'contribuyente': t.id,}
    if step == '18':    
        initial = {'contribuyente': t.id,}
    if step == '19':    
        initial = {'contribuyente': t.id,}
    if step == '20':    
        initial = {'contribuyente': t.id,}
    if step == '21':    
        initial = {'contribuyente': t.id,}
    if step == '22':    
        initial = {'contribuyente': t.id,}
    if step == '23':    
        initial = {'contribuyente': t.id,}
    if step == '24':    
        initial = {'contribuyente': t.id,}
    if step == '25':    
        initial = {'contribuyente': t.id,}
    if step == '26':    
        initial = {'contribuyente': t.id,}
    if step == '27':    
        initial = {'contribuyente': t.id,}
    if step == '28':    
        initial = {'contribuyente': t.id,}
    if step == '29':    
        initial = {'contribuyente': t.id,}
    if step == '30':    
        initial = {'contribuyente': t.id,}
    return self.initial_dict.get(step, initial)

def get_template_names(self):
    return ('solicitudes{0}.html'.format(self.steps.current))

#def done(self, form_list, **kwargs):
def done(self, form_list, form_dict, **kwargs):
    for form in form_list:
        form.save(commit=False)
        form.instance.uc = self.request.user
        #form.instance.contribuyente = self.request.user
        form.save()
    self.instance_dict = None
    self.storage.reset()

    return render(self.request, 'solicitud_ok.html', {
        'form_data': (form.cleaned_data for form in form_list),
    })

En urls.py:

form_list = (SolicitudesStep1_Form, SolicitudesStep1b_Form, SolicitudesStep2_Form, SolicitudesStep2b_Form, SolicitudesStep2c_Form, SolicitudesStep2d_Form, SolicitudesStep2e_Form, SolicitudesStep2f_Form, SolicitudesStep3_Form, SolicitudesStep4a_Form, SolicitudesStep4b_Form, SolicitudesStep4c_Form, SolicitudesStep4d_Form, SolicitudesStep4e_Form, SolicitudesStep4f_Form, SolicitudesStep4g_Form, SolicitudesStep4h_Form, SolicitudesStep4i_Form, SolicitudesStep4j_Form, SolicitudesStep4k_Form, SolicitudesStep4l_Form, SolicitudesStep4m_Form, SolicitudesStep4n_Form, SolicitudesStep4o_Form, SolicitudesStep4p_Form, SolicitudesStep4q_Form, SolicitudesStep4r_Form, SolicitudesStep5_Form, SolicitudesStep6a_Form, SolicitudesStep6b_Form, formset_factory(SolicitudesStep7_Form))

cond_dict = {‘4′: show_ministerioMEF_form_condition,’5′:show_ministerioMIEM_form_condition,’6′:show_ministerioMINTUR_form_condition,’7′:show_ministerioMGAP_form_condition,’9′:show_IndicadorEmpleo_form_condition,’10’:show_IndicadorExportaciones_form_condition,’11’:show_IndicadorDescentralizacion_form_condition,’12’:show_IndicadorTL_form_condition,’13’:show_IndicadorTL_form_condition,’14’:show_IndicadorIDi_form_condition,’15’:show_IndicadorIDi_form_condition,’16’:show_IndicadorSectFCC_form_condition,’17’:show_IndicadorSectFCC_form_condition,’18’:show_IndicadorSectDPP_form_condition,’19’:show_IndicadorSectERV_form_condition,’20’:show_IndicadorSectDMC_form_condition,’21’:show_IndicadorSectNTPE_form_condition,’22’:show_IndicadorSectSTE_form_condition,’23’:show_IndicadorSectSIN_form_condition,’24’:show_IndicadorSectSI_form_condition,’25’:show_IndicadorSectCES_form_condition,’26’:show_IndicadorSectACC_form_condition}

urlpatterns = (




url('solicitudes/(?P<step>.+)/$', Vistas_Solicitudes.SolicitudFormWizardView.as_view(form_list, url_name='Solicitudes_step', done_step_name='SolicitudesStep7_FormSet', condition_dict=cond_dict), name='Solicitudes_step'),
url('solicitudes/$', Vistas_Solicitudes.SolicitudFormWizardView.as_view(form_list, url_name='Solicitudes_Step', done_step_name='SolicitudesStep7_FormSet'), name='Solicitudes'),

)

El error que me da es el siguiente:

Request Method:     GET

Request URL: http://127.0.0.1:28582/solicitudes/30/
Django Version: 2.2.9
Exception Type: KeyError
Exception Value:

0

Exception Location: c:DjangoSTS_COMAP_CONTROLEntorno_STS_COMAP_CONTROLlibsite-packagesdjangoformsformsets.py in _construct_form, line 164
Python Executable: c:DjangoSTS_COMAP_CONTROLEntorno_STS_COMAP_CONTROLScriptspython.exe
Python Version: 3.8.1
Python Path:

(‘c:DjangoSTS_COMAP_CONTROL’,
‘C:Program Files (x86)Python38-32’,
‘C:Program Files (x86)Python38-32Scripts’,
‘c:DjangoSTS_COMAP_CONTROL’,
‘C:Program Files (x86)Python38-32python38.zip’,
‘C:Program Files (x86)Python38-32DLLs’,
‘C:Program Files (x86)Python38-32lib’,
‘c:DjangoSTS_COMAP_CONTROLEntorno_STS_COMAP_CONTROL’,
‘c:DjangoSTS_COMAP_CONTROLEntorno_STS_COMAP_CONTROLlibsite-packages’)

Server time: Vie, 15 May 2020 20:24:58 -0300

No entiendo porque no muestra en el paso 30 del wizard el formset y si puede mostrar el form individualmente.
Probe varias alternativas de internet y lamentablemente no funciono ninguna, ademas que la documentación de la libreria es muy escueta al respecto.

Django – Reportlab – Does not display a PDF image

Does not display the image (logo.png) in REPORTLAB when generating the PDF:

def some_view(request):
    buffer = io.BytesIO()
    p = canvas.Canvas(buffer)
    archivo_imagen = 'img/logo.png'
    p.drawImage(archivo_imagen, 40, 750, 120, 90,preserveAspectRatio=True)
    p.showPage()
    p.save()
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='incidencias.pdf')

The static base is configured. For example, an image is displayed in Django (not as a PDF, but on the Internet) when I do this:


How to change data in Model1 while saving data in Model2 to Django

models.py

class EquipmentWorker(models.Model):
date = models.DateField()
count = models.IntegerField()

class Admission(models.Model):
    name = models.CharField(max_length=100,db_index=True)
    date = models.DateField()
    in_stock = models.IntegerField(null=True, blank=True)
    out_of_stock = models.IntegerField(null=True, blank=True)

forms.py

 class AdmissionForm(forms.ModelForm):
   class Meta:
     model = Admission
     fields = ('date', 'name', 'admission', 'id_type', 'in_stock', 'out_of_stock')
class EquipmentWorkersForm(forms.ModelForm):
    class Meta:
        model = EquipmentWorkers
        fields = ('date', 'equipment', 'type', 'id_workers', 'id_room')

views.py

class AssignToWorker(View):
def get(self, request, admission_id):
    admission = Admission.objects.get(id=admission_id)
    form = EquipmentWorkersForm(instance=admission)
    return render(request, 'inventory/assignToWorker.html', context={'form': form, 'admission': admission})

def post(self, request, admission_id):
    admission = Admission.objects.get(id=admission_id)
    admission_form = AdmissionForm()
    form = EquipmentWorkersForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect(equipments_list)

Class AdmissionCreate (View):
def get (self, request):
form = AdmissionForm ()
return render (request, & # 39; inventory / addAdmissions.html & # 39 ;, context = {& # 39; form & # 39 ;: form})

def post(self, request):
    form = AdmissionForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect(admission_list)

it is necessary that the value of the out_of_stock Field of Admission Model is updated when the value is saved in the count Field of EquipmentWorker Model, e.g. B. out_of_stock = 0 After the value has been saved in the field count = 2, the field out_of_stock is updated (out_of_stock = 2).

view AssignToWorker accepted admission_id to identify the value in Admission.objects.get() that needs to be updated

bringfik – django cookiecutter error "bringfik_1 ACME certificate for domains /" xxxx "cannot be obtained"

Basically, I'm trying to use Docker to serve the web I've worked with in Django, but I'm getting this error … I really don't know what to do I've tried different things but they don't work for me I get always the same mistake … I know that it is something to deploy because everything works perfectly locally.