Mubasher Rehman
Mubasher Rehman

Reputation: 3

Add and Update Post from custom html forms in Django

I've created a custom HTML form for my model, just like I want to add a post from the front-end. I already created a page with the name add-post.html

add-post.html

<form method="POST" action="">
    {% csrf_token %}
        <input name="title" type="text">
        <textarea spellcheck="false" name="description"></textarea>
        <input type="file" name="image" @change="fileName" multiple />
        <select required name="priority">
           <option value="Low" selected>Low</option>
           <option value="Medium">Medium</option>
           <option value="High">High</option>
        </select>
        <input type="checkbox" name="on_hold">
        <button type="submit">Add ToDo</button>
    </form>

model.py

class Todo(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(null=True, blank=True, upload_to='todo/images/')
    description = RichTextField()
    Low, Medium, High = 'Low', 'Medium', 'High'
    priorities = [
        (Low, 'Low'),
        (Medium, 'Medium'),
        (High, 'High'),
    ]
    priority = models.CharField(
        max_length=50,
        choices=priorities,
        default=Low,
    )
    on_hold = models.BooleanField(default=False)

forms.py

class TodoCreationForm(forms.ModelForm):
    class Meta:
        model = Todo
        fields = ('title','image','description','priorities','priority','on_hold')

No, I want to use the above custom HTML form to post data and save it to this model database. instead of using {% form.as_p %}

And I also created a particular page to update this post from the front-end but don't know how to make it work.

Can you please guide me on how can I save data from the custom form and also update it from the custom form? Appreciate your response :)

Upvotes: 0

Views: 1158

Answers (2)

Max
Max

Reputation: 876

if you don't want to use form.py, you have do it on view.py

def addPost(request):
    template = 'todo/add-post.html'

    if request.method == 'GET':
        return render(request, template)
    
    Todo.objects.create(title = request.POST.get('title')
                        image = request.FILES.get('image')
                        ...................)

Upvotes: 0

unknown
unknown

Reputation: 321

You can use django form just fine

  1. In the forms.py you can write fields = '__all__' if you use all fields in the template.
  2. In html template you need to sub all inputs, select ad other fields to {{ form.as_p }} (for example)
  3. if you are load media, you need to write enctype=multipart/form-data in the form tag
  4. in views.py
...
if request.method == "POST":
  todo_form = TodoCreationForm(request.POST, request.FILES)
  if todo_form.is_valid():
    todo_form.save()

Upvotes: 1

Related Questions