Django ModelForm not saving data to database

前端 未结 6 2077
温柔的废话
温柔的废话 2021-02-10 05:53

A Django beginner here having a lot of trouble getting forms working. Yes I\'ve worked through the tutorial and browsed the web a lot - what I have is mix of what I\'m finding h

6条回答
  •  臣服心动
    2021-02-10 06:23

    Wherever you try to submit a form data to your Django code, then the Django will createan object to entire form data. The object is look like this form_obj = request.method_name. Here method_name is the form method that is (POST or GET) ex:- form_obj = request.POST

    If you want to get the form data then use a function request.method_name.get(name) here name is form attribute assign value

    ex:-

    {% csrf_token %} {form}

    in view :-

    import statements as you required
    def your_function(request):
      # you can creat a object to the form by
      form_obj = myform()
      if request.method =="POST":
        form_obj = myform(request.POST)
        if form_obj.is_valid():
    
          # you can directly save by use commit()
          form_obj.save(commit=True)
           #   or
          form_obj1 = form_obj.save(commit=False)
          #which  do you want to save in database ,those fields you need to specify like below 
          form_obj1.attribute1 = form_obj.cleaned_data["name of form field"]
            '
            '
          form_obj1.save()
    

    and in Myform.py file

    import statments    
    class myform(forms.ModelForm):
        class meta():
            model = your_models_name
            fields =("attribute1","attribute2".....) # included attribute of your_model
    

提交回复
热议问题