[Python] How should I define redirect request properly

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have a social network project for users to share their recipes. The Recipe objects managed by a ViewSet, which has Serializer, where create and update recipes operations defined, via POST and PATCH methods at same address (ie /recipes/<pk>). So when recipe is posted by user, frontend designed as user is seeing the result form, and there is a button 'update recipe' which leads to /recipes/<pk>/edit address. The problem is this page does not exist and I get 404 error. I assumed I should add some redirect to a ViewSet, but whatever i tried didn't work. so I thought I should add to a ViewSet something like:

    def edit_redirect(self, request, pk):
    if self.request.url == '/<int:pk>/edit':
    return (
    redirect('recipes/<int:pk>'),
    self.request.method == 'patch'
    )


    but I'm not sure is it correct at all and how to write properly.

    PS. my container terminal also returns error from nginx when click "update recipe" and get 404:

    gateway-1 | 2025/06/18 14:40:33 [error] 36#36: *20 open() "/staticfiles/recipes/1/edit" failed (2: No such file or directory), client: 172.19.0.1, server: , request: "GET /recipes/1/edit HTTP/1.1", host: "localhost:8800", referrer: "http://localhost:8800/recipes/1"


    and backend container doesnt send any response at all. Might it cause all this trouble? Most of other project functions work normally, as favorites, subscriptions, shopping list.. but this 404 i cant resolve..

    ViewSet looks like:

    class RecipeViewSet(viewsets.ModelViewSet):
    """Управление рецептами."""

    queryset = Recipe.objects.all()
    filter_backends = (DjangoFilterBackend,)
    filterset_class = RecipeFilter
    pagination_class = PageLimitPaginator

    def get_permissions(self):
    if self.action in ('list', 'retrieve', 'get_link'):
    return (AllowAny(),)
    return (IsAuthenticated(), OwnerOnly())

    def get_serializer_class(self):
    if self.action in ('list', 'retrieve'):
    return RecipeGetSerializer
    if self.action in ['create', 'update', 'partial_update']:
    return RecipePostSerializer
    return super().get_serializer_class()


    and Serializer is like

    class RecipePostSerializer(serializers.ModelSerializer):
    """Создание рецепта."""

    tags = serializers.PrimaryKeyRelatedField(
    queryset=Tag.objects.all(),
    many=True,
    required=True,
    allow_null=False,
    allow_empty=False,
    )
    ingredients = RecipeIngredientSerializer(
    many=True,
    required=True,
    allow_null=False,
    allow_empty=False,)
    author = serializers.HiddenField(
    default=serializers.CurrentUserDefault())
    image = Base64ImageField(required=True, allow_null=False, use_url=True)
    name = serializers.CharField(required=True, max_length=MAX_LENGTH_LONG)
    cooking_time = serializers.IntegerField(
    max_value=MAX_AMOUNT, min_value=MIN_AMOUNT)

    class Meta:
    model = Recipe
    fields = ('ingredients', 'tags', 'image', 'name', 'text',
    'cooking_time', 'author')

    # here goes some validators etc

    def create(self, validated_data):
    """Создание рецепта."""
    tags = validated_data.pop('tags')
    ingredients = validated_data.pop('ingredients')
    recipe = Recipe.objects.create(**validated_data)
    self.add_tags_ingredients(recipe, tags, ingredients)
    return recipe

    def update(self, instance, validated_data):
    """Изменение рецепта."""
    recipe = instance
    recipe.tags.clear()
    recipe.ingredients.clear()
    tags = validated_data.pop('tags')
    ingredients = validated_data.pop('ingredients')
    self.add_tags_ingredients(recipe, tags, ingredients)
    recipe.save()
    return recipe

    def to_representation(self, instance):
    return RecipeGetSerializer(instance).data

    Continue reading...

Compartilhe esta Página