Проблемы с ответом в API REST django - PullRequest
0 голосов
/ 07 июля 2019

Я пытаюсь связать django API-REST с формой, с которой связана модель.Все работает хорошо, пока я не сделаю:

return response.Response (serializer.data, status = status.HTTP_201_CREATED)

JavaScript

    // To Save the Suggestion
    let ajax_suggestion_save = function (type, url, data, context) {
        let name_dm = $('#name-db-saved').val();
        $.ajax({
            type: type,
            url: url,
            data: data,
            context: context,
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            success: function (response) {
                $.niftyNoty({
                    type: "success",
                    container: 'floating',
                    title: 'Your information was saved successfully.',
                    message: 'We much appreciate your interest of contact us, part of the growth of this platform it is base on your collaboration through your ideas.',
                    closeBtn: true,
                    timer: 4000
                });
            },
            error: function (response) {
                if (Object.keys(response.responseJSON).length >= 1) {
                    $.each(response.responseJSON, function (key, value) {
                        $.niftyNoty({
                            type: 'danger',
                            container: 'floating',
                            title: 'Ups, apparently we have problems saving your information.',
                            message: 'Please check the following ' +
                                'Error in  <strong> ' + key + ' </strong>, with the following error <strong> ' + value + ' </strong>.',
                            closeBtn: true,
                            timer: 4000
                        });
                    });
                } else {
                    $.niftyNoty({
                        type: 'danger',
                        container: 'floating',
                        title: 'Ups, apparently we have problems saving your information.',
                        message: 'Ups, apparently we have problems saving your suggestion. ' +
                            'If the problem persists, notify the system administrator in the help section.' +
                            'You suggestion <strong> ' + name_dm + ' </strong> not will be saved.',
                        closeBtn: true,
                        timer: 4000
                    });
                }
            }
        });
    };

    $('#contactus').on('click', function (type, url, data, context) {
        ajax_suggestion_save('POST', '/miscellaneous/api/contactus/create/', $("#contactus_form").serializeArray(), this);
    });


Модель

class DimContactUs(Model):
    class Meta:
        order_with_respect_to = 'email'
        verbose_name = 'Contact'
        verbose_name_plural = 'Contact'

    id_contact_us = UUIDField(primary_key=True, default=uuid.uuid4, editable=False,
                              help_text='Universally unique identifier of a Contact')

    name = CharField(max_length=100, help_text='Name of the Contact')

    email = EmailField(max_length=70, help_text='Email of these Contact')

    # id_user = ForeignKey(User, on_delete=CASCADE, help_text='Foreign Key of the User that made this Contact')

    title = CharField(max_length=100, help_text='Title of the Contact')

    message = TextField(
        help_text='Short description of this Contact, e.g. : We want to include ...!')

    url = URLField(null=True, blank=True,
                   help_text='Please copy the url associated to this Contact')

    active = BooleanField(default=True, help_text='Do you want to make public this Contact?')

    time_create = DateTimeField(auto_now=True, auto_now_add=False, editable=False, help_text='Time it was created')

    time_stamp = DateField(auto_now=True, auto_now_add=False, help_text='Time of last modification')

    def __str__(self):
        return self.title

Сериализаторы

class DimContactUsSer(serializers.ModelSerializer):
    class Meta:
        model = DimContactUs
        fields = '__all__'

Представление


class ContactUsCreate(CreateAPIView):
    queryset = DimContactUs.objects.all()
    serializer_class = DimContactUsSer

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        try:
            if request.method == 'POST':
                form = DimContactUsForm(request.POST, request.FILES)
                serializer = DimSuggestionSer(data=request.data)
                if form.is_valid() and serializer.is_valid():
                    serializer.save()
                    return response.Response(serializer.data, status=status.HTTP_201_CREATED)
                else:
                    return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        except Exception as exception:
            return response.Response(exception.args, status=status.HTTP_400_BAD_REQUEST)

Здесь ответ отправляет меня на страницу API REST вместо того, чтобы оставаться на текущей.

...