Noszo
Noszo

Reputation: 19

Problem with React Form and passing information to backend in Django

I have a view in Django that is responsible for booking a user a training session with a personal trainer. This view wants a full Trainer object, but the react form only passes the trainer ID to Django, despite the PrimaryKeyRelatedField attribute being set in the serializer.

This is error which i got:

Error: Cannot assign "'2'": "TrainingSession.trainer" must be a "Trainer" instance.
@api_view(["POST"])
@permission_classes([IsAuthenticated])
def create_training_session(request):
    data = request.data

    # Check require information
    if "trainer" not in data or "date" not in data or "duration" not in data:
        return Response(
            {"detail": "Brak wymaganych pól."}, status=status.HTTP_400_BAD_REQUEST
        )

    try:
        session = TrainingSession.objects.create(
            trainer=data["trainer"],
            client=request.user,
            date=data["date"],
            duration=data["duration"],
        )
        serializer = TrainingSessionSerializer(session, many=False)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    except Exception as e:
        return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
class TrainingSessionSerializer(serializers.ModelSerializer):
    trainer = serializers.PrimaryKeyRelatedField(queryset=Trainer.objects.all())
    client = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())

    class Meta:
        model = TrainingSession
        fields = ["id", "trainer", "client", "date", "duration", "status"]
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {Button, Form, FloatingLabel} from "react-bootstrap";
import { bookTrainingSession, listTrainers } from '../actions/serviceActions';

const BookTrainingSessionForm = () => {
    const [trainer, setTrainer] = useState('');
    const [date, setDate] = useState('');
    const [duration] = useState(60);

    const dispatch = useDispatch();

    const trainerList = useSelector((state) => state.trainerList);
    const { loading: loadingTrainers, error: errorTrainers, trainers } = trainerList;

    const sessionTrainingBook = useSelector((state) => state.sessionTrainingBook);
    const { loading, error, success } = sessionTrainingBook;

    useEffect(() => {
        dispatch(listTrainers());
    }, [dispatch]);

    const submitHandler = (e) => {
        e.preventDefault();
        dispatch(bookTrainingSession({ trainer, date, duration }));
    };

    return (
        <form onSubmit={submitHandler}>
            <div>
                <FloatingLabel>Trener</FloatingLabel>
                {loadingTrainers ? (
                    <p>Loading trainers...</p>
                ) : errorTrainers ? (
                    <div>Error: {errorTrainers}</div>
                ) : (
                    <Form.Select value={trainer} onChange={(e) => setTrainer(e.target.value)} required>
                        <option value="">Wybierz trenera</option>
                        {trainers.map((trainer) => (
                            <option key={trainer.id} value={trainer.id}>
                                {trainer.name}
                            </option>
                        ))}
                    </Form.Select>
                )}
            </div>
            <div>
                <FloatingLabel>Data</FloatingLabel>
                <input type="datetime-local" value={date} onChange={(e) => setDate(e.target.value)} required />
            </div>
            <Button className='mt-3' type="submit" disabled={loading} variant="primary">
                {loading ? 'Booking...' : 'Book Session'}
            </Button>
            {error && <div>Error: {error}</div>}
            {success && <div>Session booked successfully!</div>}
        </form>
    );
};

export default BookTrainingSessionForm;

Upvotes: -1

Views: 107

Answers (1)

user27133686
user27133686

Reputation: 1

  • name: Copy scripts folder to target hosts and track changes hosts: all become: yes gather_facts: yes # Ensure ansible_date_time is available

    tasks:

    • name: Get current script versions (if exist) ansible.builtin.shell: "find /app/PEV/UBS/scripts -type f -exec sha256sum {} + 2>/dev/null | sort" register: old_checksums changed_when: false ignore_errors: true

    • name: Copy updated scripts ansible.builtin.copy: src: "/app/PEV/UBS/scripts/" dest: "/app/PEV/UBS/scripts/" mode: '0755' remote_src: false register: copy_result

    • name: Get new script versions after deployment ansible.builtin.shell: "find /app/PEV/UBS/scripts -type f -exec sha256sum {} + 2>/dev/null | sort" register: new_checksums changed_when: false

    • name: Identify changed files ansible.builtin.shell: | diff <(echo "{{ old_checksums.stdout | default('') }}") <(echo "{{ new_checksums.stdout | default('') }}") | grep '^>' | awk '{print $2}' register: changed_files changed_when: false ignore_errors: true

    • name: Ensure log directory exists ansible.builtin.file: path: "/var/log" state: directory mode: '0755'

    • name: Log only changed files ansible.builtin.lineinfile: path: "/var/log/script_deployments.log" line: | Host: {{ inventory_hostname }} Timestamp: {{ ansible_date_time.iso8601 }} Changed Files: {{ changed_files.stdout | default('No changes detected') }} create: yes

Upvotes: 0

Related Questions