S
S
SuperiorAId2021-06-16 20:40:34
Django
SuperiorAId, 2021-06-16 20:40:34

How can I add a field to an existing model object using a form?

Need help writing Views and the form itself.

We have two models

class Sensors(models.Model):
    name = models.CharField(max_length=150)

class Rooms(models.Model):
    name = models.CharField(max_length=150, blank=False)
    x = models.SmallIntegerField()
    y = models.SmallIntegerField()
    h = models.SmallIntegerField()
    sensors = models.ManyToManyField(Sensors, blank=True)

urls:
path('sensortoroom/<int:room_id>', sensortoroom, name='sensortoroom'),


views to be added
def sensortoroom(request, room_id):
    room = Rooms.objects.filter(id=room_id)
    form = Addsensortoroom()

    return render(request, 'room/addsensortoroom.html')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Melnikov, 2021-06-16
@SuperiorAId

About forms, read here
From it we will learn what we need to do

class SensorForm(ModelForm):
    class Meta:
        model = Sensors
        fields = ['name ', 'x', 'y', 'h','sensors ']

In view.py
from .forms import SensorForm

def sensortoroom(request, room_id):
    room = Rooms.objects.filter(id=room_id)
    form = SensorForm()
    if request.POST:
         pass

    return render(request, 'room/addsensortoroom.html', {'form': form})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question