python – Django shape with several models

I am new to programming and I am trying to create a form using multiple templates in Django.
I even managed to list the forms.py fields, but when asked to back it up, it only writes the data from the first template.
The error it gives is "Failed to NOT NULL constraint: Geral_usuario.colaboradorId_id", which, in my opinion, does not recover the identifier of the employee who is coming to be registered.
How could I solve this problem?

I've redid a "mini code" to give you an idea of ​​my condition.

models.py:

from django.db import models

class Colaborador(models.Model):
    nome = models.CharField()

class Usuario(models.Model):
    user = models.CharField(unique=True)
    senha = models.CharField()
    colaboradorId = models.OneToOneField('Colaborador', on_delete=models.CASCADE)

class Email(Contato):
    email = models.CharField()
    colaboradorId = models.ForeignKey('Colaborador', on_delete=models.CASCADE)

forms.py:

from django.forms import ModelForm
from django import forms
from .models import Colaborador, Usuario, Email

class FormUsuario(ModelForm):
    class Meta:
        model = Usuario
        fields = ('user', 'senha')

class FormColaborador(ModelForm):
    class Meta:
        model = Colaborador
        fields = ('nome')

class FormEmail(ModelForm):
    class Meta:
        model = Colaborador
        fields = ('nome')

views.py:

from django.shortcuts import render, redirect
from .forms import FormUsuario, FormColaborador, FormEmail

def Cadastro(request):
    data = {}

    if request.method == "POST":
        data('colaborador') = FormColaborador(request.POST, None)
        data('usuario') = FormUsuario(request.POST, None)
        data('email') = FormEmail(request.POST, None)

        if data('colaborador').is_valid():
            colaborador = data('colaborador').save(commit=False)
            id = colaborador.id
            if data('usuario').is_valid():
                usuario = data('usuario')
                usuario.colaboradorId = id
                if data('email').is_valid():
                    email = data('email')
                    email.colaboradorId = id
                    colaborador.save()
                    usuario.save()
                    email.save()
                    return redirect('lista')
    else:
        data('colaborador') = FormColaborador()
        data('usuario') = FormUsuario()
        data('email') = FormEmail()

    return render(request, 'cadastro.html', data)

registration.html:

{% csrf_token %} {{ colaborador.as_p }} {{ usuario.as_p }} {{ email.as_p }}

The delete () method of a template in Django is not executed

I am about to write the method delete() of my model to perform an action before disappearing.

def delete(self, using=None, keep_parents=False):
    print('ejecutando metodo delete')

    producto_detallado = ProductoDetallado.objects.get(id=self.producto_detallado.id)

    # El eliminado de producto venta incrementa el numero de unidades, a el numero de productos disponibles
    producto_detallado.unidades_disponibles += self.unidades_vendidas
    producto_detallado.save()

    super(ProductoVenta, self).delete()

But when removing an object ProductoVenta You do not perform the expected action.

I put a prin() to be able to see in the console if it is running, but in fact I have no messages there.

python – Error ImproperlyConfigured Unable to resolve the URL of a hyperlinked relationship using the name of the view, Django

I am creating an application in django-REST, in which a company can have several workshops. The problem is that when I create a company and then try to enter the shop view, the following error message is displayed:

django.core.exceptions.ImproperlyConfigured: Unable to resolve the URL of the hyperlinked relationship with the enterprise-detail view name. You may have failed to include the associated template in your API or incorrectly configured it lookup_field attribute on this field.

Someone knows how to solve this problem ?, This only happens when there are companies created, if there are not any, let me enter the workshop view, here is the code:

Models.py:

#modelo para empresas
class Enterprise(models.Model):
   nit = models.CharField(db_column='NIT', primary_key=True, max_length=12)  
   name = models.CharField(max_length=50)
   type = models.CharField(max_length=8)

   def __str__(self):
      return self.name

   class Meta:
      db_table = 'enterprise'

#modelo para talleres
class Workship(models.Model):
   idworkship = models.AutoField(primary_key=True)
   name = models.CharField(max_length=128)
   description = models.TextField()
   type_service = models.CharField(db_column='type_Service', max_length=45)  
   stars = models.PositiveIntegerField(default=0)
   votes = models.PositiveIntegerField(default=0)
   email = models.CharField(max_length=254)
   field_bahias_quant = models.PositiveIntegerField(db_column='_bahias_quant')
   #clave foránea a Enterprise
   enterprise_nit = models.ForeignKey(Enterprise, models.DO_NOTHING, db_column='enterprise_NIT') 

   def __str__(self):
    return self.name

   class Meta:
      db_table = 'workship'
      unique_together = (('idworkship', 'enterprise_nit'),)

Serializers.py:

class EnterpriseSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
       model = models.Enterprise
       fields = ('nit', 'name', 'type',)

class WorkshipSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
       model = models.Workship
       fields = ('name','ubication', 'description', 'type_service', 'stars', 'votes', 'email' , 'field_bahias_quant', 'enterprise_nit',)

views.py:

class EnterpriseViewSet(viewsets.ModelViewSet):
   queryset = models.Enterprise.objects.all()
   serializer_class= serializers.EnterpriseSerializer

class WorkshipViewSet(viewsets.ModelViewSet):
   queryset = models.Workship.objects.all()
   serializer_class = serializers.WorkshipSerializer

urls.py:

router = routers.DefaultRouter()
router.register('Enterprise', views.EnterpriseViewSet, base_name = 'Enterprise')
router.register('Workship', views.WorkshipViewSet, base_name = 'Workship')
urlpatterns = (
   path('admin/', admin.site.urls),
   path('', include(router.urls)),
   path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)

Python / Django Import Agreement – Code Review Stack Exchange

If I'm not mistaken, it's the convention of writing generally followed importin a Django project.

# Standard Library Imports
import os, time, json

# Third Party Library Imports
from django.db.models import Q, Max, Min, Count, Sum, Prefetch
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.postgres.fields import JSONField, ArrayField

# External App Imports
from OtherApp.utils import foo_i_need()
from SomeOtherApp.utils import bar_i_need()

# Local App Imports
from constants import NON_EXISTENT_USER, INVALID_PASSWORD

I try to follow this convention as much as I can, but while working on a fairly large project, how can I handle some imports that are outdated by others?

For example, let's say that I have in models.py in App1

import datetime

In managers.py in App2, I have this –

from datetime import datetime

App2_model.objects.filter(created_on__gte=datetime.now())

But sometime after, I need something from App1, so I'm doing a import this application, following the aforementioned convention –

from datetime import datetime
from App1.models import App1_model

App2_model.objects.filter(created_on__gte=datetime.now())

datetime.now() would not work now, because import datetime of App1 replace now from datetime import datetime earlier than written from App1.models import App1_model.

This problem is greatly exaggerated when working in a team of more than 70 people. I've seen a lot of people in my company write imports INSIDE their functions or methods to avoid the risk of unintentional imports.

What I wanted to know, is there a way to avoid this, apart from a rigorous test or revision of the code?

javascript – Explanation needed with Django and AMP logic using 1 URL

I'm using AMP in one of my parts of the website with the Django model and the python. My question is what will happen to a page (* in terms of SEO) if I take and break an AMPed page (only on the desktop) and leave the page. AMPED on mobile ?!

To be more specific, I've created a complete AMP page for mobile and desktop that uses the URL (/ example-amp-url) and I now have to add a widget to the page, which is restored with js and not AMPed. but make it only on the desktop.

Someone knows what impact it would have on my SEO? Because for the moment in my site-map, this page is optimized on both the mobile search and on the desktop page (if I lose the AMP on the desktop, it's okay but if I lose at once, it's a huge problem, that's why I'm afraid to test it)

python – django apps updating another apps data model

I know that django apps need to be designed to be more or less reusable and not be closely associated with other apps … But I have a hard time finding the best practices for having an application set up. day the data in another application

Example with the 2 applications given.

  1. Albums (manages a user who uploads photos to an album and displays)
  2. Profile (manages some basic statistics for each user: badges, number of album views, etc.)

When a user downloads an album or that an album is viewed (Album application), I have to update some data in the Profile application. Does the Album application need to update this data directly?

albums / views.py

from profile.models import Profile
profile = Profiles.objects.filter(user_id = user_id)
profile.update(views=F('views')+1)

or should there be an API between the two applications to allow Albums to tell Profiles that it needs to update its data?

(suggestions of tags welcome)

django – How to display the object in the registry fields to which I want to apply updateView?

I want to edit the information in a raw instance, but for the moment, it does not show me the information that I had previously inserted in the create view and I do not understand how to display it. I've tried with the arguments: form.cleane_data, 'form', but still does not show me the data that's in the fields, but that's can already be seen in a list view, that I have in the house of the application.

This is my point of view.py

def update_permisos(request, pk):
if request.method == 'POST' and request.is_ajax():
    form = permiForm(request.POST, instance=request.user)
    if form.is_valid():
        permiso = form.save(commit=False)
        permiso.usuario = request.user
        permiso.save()
        permiso.usuario.status = request.POST('status':'Aceptado')
        permiso.usuario.d_pendientes = request.POST('d_pendientes')#valores, que van al campo
        permiso.usuario.h_pendientes = request.POST('h_pendientes')#valores, que van al campo
        permiso.usuario.save()
        return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole 
    else:
        return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole
else:
    form = permiForm(instance=request.user)
    args = {'form':form.data}
    return render(request, 'plantillas/permisos.html', args)


forms.py

class permiForm(forms.ModelForm):

class Meta:

    model = permiso

    fields = (

        'disponer',
        'razon',
        'periodo_i',
        'periodo_f',
        'dias_disponer',
        'horas_disponer',


    )

Si necesitan, que muestre algo mas, me comentan por favor

Can I name a template using a field from another template in Django admin?

Such as…

class firstModel(models.Model)
    name = models.CharField()

    def __str__(self):
        return self.name


class secondModel(models.Model)
    paragraph = models.TextField()

    def __str__(firstModel):
         return firstModel.name

I have basically two standard forms that the user fills – the user fills firstModelForm on page 1, then page 2 is secondModelForm.

In Django admin, I want secondModel to display the name entered in firstModel, instead of the secondModel (1) object.

I know that the code above is not the solution to achieve this, but I thought it illustrates what I'm trying to achieve.

Thank you.

Django rest_framework does not return json

Hello, I have a problem with rest_framework:

class FrutaSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Fruta
        fields = ('id', 'nombre', 'fecha_entrada', 'cantidad', 'precioUnitario',) 

class FrutaGet(generics.ListCreateAPIView):
    serializer_class = FrutaSerializer
    def get(self, request, pk, format=None):
        obj = Fruta.objects.get(pk=pk)
        serializer = FrutaSerializer(obj)
        return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)

urlpatterns = (
    path('fruta/', FrutaList.as_view(), name='frutas'),
    path('fruta/', FrutaGet.as_view(), name='frutasUnica'),
    path('fruta/', FrutaUptdate.as_view(), name='frutasActualizar'),
)

The problem that I have is that when I want to change the format to JSON.

enter the description of the image here

and in the url the? format = json does not appear

enter the description of the image here

I'm using this API in javascript and this shows me this error

SyntaxError: Unexpected end of JSON input
    at script.js:22

Django template design in OneToOneField and ManyToManyField

I am writing a movie about Seat Booking Django App, I can not conceive of a simple model.

First of all, here are my current models:

from django.db import models
from django.contrib.auth import get_user_model

class Seats(models.Model):
    seat_choice = (
        ('AA', 'AA'),
        ('AB', 'AB'),
        ('BA', 'BA'),
        ('BB', 'BB'),
        ('CA', 'CA'),
        ('CB', 'CB')
    )
    name = models.CharField(choices=seat_choice, max_length=2)

    def __str__(self):
        return self.name


class Booking(models.Model):
    hall = models.OneToOneField(Seats)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

I wish that a user could buy / reserve one or more seats, but the same user or another user can not buy a seat already reserved by someone or by himself.

But the problem is that my current models do not work as I want …
Currently, it works as if a user bought a ticket, the same user could not buy the ticket that he had already bought! but the problem is, now another user can buy the ticket already booked by someone a and I do not want that at all.

I want that if a place has already been booked by someone, no one can book it later, but it can be canceled by the user who has reserved!

Can someone help me to achieve this?