python – Cannot connect to celery signals from django

I have the default django integration from the celery docs.

Also just added

@before_task_publish.connect(weak=False)
def before_task_publish_handler(*args, **kwargs):
    logger.error(f'Args {args}')
    logger.error(f'Kwargs {kwargs}')

Running in the shell:

debug_task.delay()

There is no logging or breakpoint catching in pycharm. I do not think it connects to celery, but I do not know how to check. What am I missing?

python – No Django como restringir alteração de apenas um field do model após ter inserido um valor?

Exemplo.:

class Cadastro(models.Model):

    class Tipos(models.TextChoices):
        PERFIL_A = 'perfil B', 'Perfil A'
        PERFIL_B = 'perfil B', 'Perfil B'

    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    nome = models.CharField(max_length=100)
    tipo_perfil = models.CharField(max_length=30, choices=Tipos.choices)'

o field ‘tipo_perfil’ não quero que altere após ter escolhido, é possível?
Tem algum recurso do django ou precisaria fazer uma logica no model?

python – ¿Cuando usar has_permission y has_object_permission? Django Rest Framework

estuve revisando un rato la doc. de drf y creo entender por fin el proposito de has_permission y has_object_permission. Sin embargo, tengo la siguiente duda:
¿Cuando se supone que hay que usar has_permission y has_object_permission?
Es decir, no hacen lo mismo las siguientes clases?

class IsSelfMember(BasePermission):
"""
Allow access only to the owner of the invitations.
"""

def has_permission(self, request, view):
    """
    Check if the obj owner are the same that the requesting user.
    """
    obj = view.get_object()

    return request.user == obj.user #Bool

#-----------------------------------------------------------


class IsSelfMember(BasePermission):
"""
Allow access only to the owner of the invitations.
"""

def has_permission(self, request, view):
    """
    Get the object and then call to `has_object_permission`.
    """
    obj = view.get_object()

    return self.has_object_permission(self, request, view, obj)


def has_object_permission(self, request, view, obj):
    """
    Check if the obj owner are the same that the requesting user.
    """
    return request.user == obj.user

python – Alterar formato de data no Django para dd/mm/yy

Olá! Eu to tentando criar uma aplicação com Django Rest para um desafio de estágio. Mas eu me deparo com um problema que não será tolerado. Preciso que a data inserida no DateField responda ao padrão brasileiro DD/MM/YYYY, mas só consigo alterá-lo para MM/DD/YY no máximo.

Meu models da app core:

from django.db import models
from organizadores.models import Organizadore


# Create your models here.
class Evento(models.Model):
    nome = models.CharField(max_length=100)
    organizadores = models.ManyToManyField(Organizadore)
    data_inicio = models.DateField(null=False)
    data_fim = models.DateField(null=False)
    confirmado = models.BooleanField(default=False)

    def __str__(self):
        return self.nome

Settings do projeto:

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-@0z5o*9z7hd6@b-=_3w!x+i)bg^0*q#q!qw258wvsp(jq(2-r$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ('*')


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'core',
    'organizadores'
)

MIDDLEWARE = (
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'eventos.urls'

TEMPLATES = (
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': (),
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': (
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ),
        },
    },
)

WSGI_APPLICATION = 'eventos.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = (
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
)


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = False

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

DATE_INPUT_FORMATS = ('%d/%m/%Y')

Como está nas configurações, já tentei usar o DATE_INPUT_FORMATS, USE_L1ON = False e não consigo de jeito nenhum achar como editar isso. Já vi pessoas sugerindo usar DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS), mas essas kwargs não existem e apontam erro no código:
widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS

Não sei mais o que fazer, já tentei mudar a linguagem pra pt-br, en-uk e en-GB, mas em nenhum caso funciona. Alguém consegue ter uma ideia?

¿Como paso una función de python atraves de django? / how do I run a python script in django?

Soy nuevo en la programacion, y me he visto envuelto en una tutoria de desarrollo web en django, poseo conocimientos intermedios de python y algunas GUIS como tkinter. Quiero hacer una página web donde el usuario intruzca datos y estos sean enviados a un script de python que los procese para luego retornar la respuesta, intente de varios metodos, desde usar js hasta php, tambien usando los {{}} pero no logro entender como pasar datos desde in input HTML y estos datos procesarlos con python y luego retornarlos hacia html para asi tambien darles un estilo usando css, adjunto un video que use como referencia, que funciona pero no del todo, los datos se quedan estancados sin importar cuantas veces refresque la pagina, y me gustaria saber si hay otros metodos de hacerlo. Adjunto el video:

Presento un ejemplo usando tkinter de como, según yo, podria funcionar, cabe destacar que es solo a manera de representación.

principal.py

import tkinter as tk
from otroarchivo import ask, boton

root=tk.Tk()
ask(root)

btn=tk.Button(root, text=’soy un boton’, command=boton)
btn.pack()

root.mainloop()

otroarchivo.py

import tkinter as tk

def ask(master=None):
global dato, pregunta
info=tk.Label(master, text=’Ingrese su nombre’)
info.pack()
pregunta=tk.Entry(master)
pregunta.pack()

def boton():
dato=pregunta.get()
print(dato)

Al correrlo, pide los datos desde un archivo y los presenta desde otro que manda a llamar a ese archivo, no es algo necesario al momento de usar tkinter pero algo asi me gustaria hacer en django, espero se comprendiera.

De antemano muchas gracias por ayudar a un novato 😀

Cita en bloque

Cita en bloque

python – Django CreateView not creating a new user from 3 related models through ModelForm

I’ve created models in a Django project, one of which is an extended User model. Initially, I was creating a user through 2 forms, UserCreationForm and EmployeeForm based of a ModelForm, then using a function based view to validate the data and save it. It all worked fine until I tried to introduce the third form and wanted to use the CreateView.

Here are the models:

class Employee(models.Model):
SENIOR = 'Sr'
JUNIOR = 'Jr'
FIRST = 'I'
SECOND = 'II'
THIRD = 'III'

GENERATIONAL_SUFFIX = (
    (SENIOR, 'Senior'),
    (JUNIOR, 'Junior'),
    (FIRST, 'First'),
    (SECOND, 'Second'),
    (THIRD, 'Third'),
)

MALE = 'male'
FEMALE = 'female'
OTHER = 'other'

SEX = (
    (MALE, 'Male'),
    (FEMALE, 'Female'),
    (OTHER, 'Other'),
)

user = models.OneToOneField(User, on_delete=models.CASCADE)
phone_regex = RegexValidator(regex=r'^d{11}$', message="Phone number must be entered in the format: '09151234567'.")
phone_number = models.CharField(validators=(phone_regex), max_length=11, blank=True)
middle_name = models.CharField(max_length=20, blank=True)
sex = models.CharField(max_length=6, choices=SEX, blank=True)
suffix = models.CharField(max_length=3, choices=GENERATIONAL_SUFFIX, blank=True)
birthday = models.DateField(null=True, blank=True)
hire_date = models.DateField(null=True, blank=True)
image = models.ImageField(blank=True, default='blank_profile_picture.jpg')
slug = models.SlugField(max_length=60, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)

@property
def get_full_name(self):
    first_name = self.user.first_name
    middle_name = self.middle_name
    last_name = self.user.last_name

    if middle_name is None:
        full_name = f'{first_name}{" "}{last_name}'
        return full_name
    else:
        full_name = f'{first_name}{" "}{middle_name}{" "}{last_name}'
        return full_name

def save(self, *args, **kwargs):
    self.slug = slugify(self.get_full_name)
    super().save(*args, **kwargs)

def __str__(self):
    return self.get_full_name


class EmployeePosition(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    position = models.ForeignKey(Position, on_delete=models.CASCADE)
    position_change_reason = models.ForeignKey(PositionChangeReason, on_delete=models.CASCADE, default='Hired As')
    effective_date = models.DateField()

    def __str__(self):
        return str(self.position)

Here are the 3 forms:

class EmployeeRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'class': 'form-control mb-2',
                                                                           'placeholder': 'juandelacruz@email.com'}))
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Juan'}))
    last_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Dela Cruz'}))

    password1 = None
    password2 = None

    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name')

    def clean(self):
        password = User.objects.make_random_password(length=10,
                                                  allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
        self.cleaned_data('password1') = password
        self.cleaned_data('password2') = password

        return super().clean()

    def save(self, commit=True):
        user = super().save(commit=False)

        user.email = self.cleaned_data('email')
        user.first_name = self.cleaned_data('first_name')
        user.last_name = self.cleaned_data('last_name')
        user.is_active = False
        if len(user.first_name.split()) and len(user.last_name.split()) > 1:
            username = f'{"".join(user.first_name.split()(:2))}{"."}{"".join(user.last_name.split())}'
        elif len(user.first_name.split()) > 1:
            username = f'{"".join(user.first_name.split()(:2))}{"."}{user.last_name}'
        elif len(user.last_name.split()) > 1:
            username = f'{user.first_name}{"."}{"".join(user.last_name.split())}'
        else:
            username = f'{user.first_name}{"."}{user.last_name}'
        username = username.lower()
        user.username = username
        user.set_password(self.cleaned_data('password1'))

        if commit:
            user.save()
        return user


class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = ('phone_number', 'middle_name', 'sex', 'suffix', 'birthday', 'hire_date')
        widgets = {
            'phone_number': forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': '09151234567'}),
            'middle_name': forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Rodriguez'}),
            'suffix': forms.Select(attrs={'class': 'form-select mb-2'}),
            'sex': forms.Select(attrs={'class': 'form-select mb-2'}),
            'birthday': forms.DateInput(attrs={'type': 'date', 'class': 'form-control mb-2'}, format='%m/%d/%Y'),
            'hire_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control mb-2'}, format='%m/%d/%Y'),
        }

class EmployeePositionForm(forms.ModelForm):
    position_change_reason = forms.Select()
    effective_date = forms.DateField()

    class Meta:
        model = EmployeePosition
        fields = ('employee', 'position', 'position_change_reason', 'effective_date')
        widgets = {
            'position': forms.Select(attrs={'class': 'form-select mb-2', 'id': 'position'}),
        }

    def check_position_change_reason(self):
        position_change_reason = self.cleaned_data('position_change_reason')
        if not position_change_reason:
            position_change_reason = EmployeePosition.position_change_reason.get_default()
        return position_change_reason

    def check_effective_date(self):
        effective_date = self.cleaned_data('effective_date')
        if not effective_date:
            effective_date = Employee.hire_date
        return effective_date

    def save(self, commit=True):
        position = super().save(commit=False)
        position.position_change_reason = self.cleaned_data('position_change_reason')
        position.effective_date = self.cleaned_data('effective_date')
        position.position = self.cleaned_data('position')
        return position

In the third form, I tried to set default values for two fields in case user doesn’t enter them.

Here’s how the view looks like:

class RegisterEmployeeView(LoginRequiredMixin, CreateView):
    model = User
    form_class = EmployeeRegistrationForm
    profile_form_class = EmployeeForm
    position_form_class = EmployeePositionForm
    template_name = 'accounts/register.html'
    success_url = '/'

    def get(self, request, *args, **kwargs):
        form = self.form_class(**self.get_form_kwargs())
        profile_form = self.profile_form_class(prefix='profile_form')
        position_form = self.position_form_class(prefix='position_form')
        return render(request, self.template_name,
                      {'form': form, 'profile_form': profile_form, 'position_form': position_form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        profile_form = self.profile_form_class(request.POST)
        position_form = self.position_form_class(request.POST)

        if form.is_valid() and profile_form.is_valid() and position_form.is_valid():
            user = form.save()
            profile = profile_form.save(commit=False)
            position_profile = position_form.save(commit=False)
            profile.user = user
            position_profile.employee = profile.employee
            profile.save()
            position_profile.save()
            messages.success(self.request, f'{User.first_name}{" "}{User.last_name}{" was registered successfully."}')
            return HttpResponseRedirect(self.get_success_url())
        else:
            context = {'form': form, 'profile_form': profile_form, 'position_form': position_form}
        return render(request, self.template_name, context)

I’ve read dozens of articles here and other sites that have similar issues, but couldn’t work it out. It seems similar to what Risadinha said here: “it’s not saving and not redirecting” := that is what happens when there is a validation error. But I can’t wrap my head around this as I’m still learning Django.

Como evitar el resubmit de formulario al refrescar la pagina en django

buenas estoy haciendo una pequeña app de notas al guardar el formulario el views.py me devuelve a la misma pagina hasta hay todo bien, pero cuando actualizo la pagina me aparece un mensaje diciendo que el formulario sera enviado nueva mente

def guardar(request):
        notas = noteblock.objects.all()

        note = formularionotes(request.POST)
        if note.is_valid():
            note.save()
            return render(request,'notes.html',{'notas':notas})

alquien porfavor me explica como hago que esto no pase

python – Selecionando o nome da planilha excel ao carregar um arquivo excel com tablib – Django

Tenho um arquivo excel para carregar com 4 planilhas. Quero carregar uma planilha específica. Como posso escolher o nome da planilha? Isso é possível com tablib?

Isso não ajuda. Não consigo escolher uma aba específica.

imported_data= dataset.load(file.read( ), format= 'xlsx')

Desta forma, não estou selecionando nenhuma aba específica no arquivo xlsx

OBS: É possível ler o nome da primeira aba com imported_data.title

python – Agregar Tablas existentes al Panel Admin en Django

resulta que estoy migrando a Django, tengo mi base de datos en Mysql.
El problema es que cuando realizo un nueva tabla desde mi modelo en django, todo indica y se me muestra en el panel admin sin problemas.

El problema está cuando intento agregar esta tabla en mi panel Admin de django. Realizo las migraciones y me resultan correctas.

Muestro mi código de la tabla que si se muestra:

class CategoryEmployee(models.Model):
    name = models.CharField(max_length=150, verbose_name='Nombre')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Categoria Empleado'
        verbose_name_plural = 'Categorias Empleados'
        db_table = 'empleadocategoria'
        ordering = ('id')

Y este es mi codigo de la tabla que no se muestra:

class Categorias(models.Model):
    cat_id = models.AutoField(primary_key=True)
    nombre = models.CharField(max_length=45, db_collation='latin1_swedish_ci')
    statusinterno = models.IntegerField(db_column='statusInterno')  # Field name made lowercase.
    fechaalta = models.DateTimeField(db_column='fechaAlta')  # Field name made lowercase.
    fechaedit = models.DateTimeField(db_column='fechaEdit', blank=True, null=True)  # Field name made lowercase.
    parent_pk = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Categoria'
        verbose_name_plural = 'Categorias'
        ordering = ('cat_id')
        db_table = 'categorias'

Espero puedan apoyarme a solucionar este inconveniente, ya he consultado pero no he tenido exito.
Saludos!