Django Form-Model issue;

Viewed 62

I am having trouble working with models and forms in Django. A little clarification and help will be highly appreciated!

I am really confused because I do not see the form in my html url page. I see everything else but not the form. I assume, I'm missing something.

This is my forms.py

from django import forms
from .models import TwitterContainer

class TwitterUpdateForm(forms.ModelForm):
    class Meta:
        model = TwitterContainer
        fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"]
    

This is my models.py

from django.db import models
from django.contrib.auth.models import User

class TwitterContainer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    Twitter_API_key = models.fields.CharField(max_length=100)
    Twitter_API_key_secret = models.fields.CharField(max_length=100)
    Twitter_API_token = models.fields.CharField(max_length=100)
    Twitter_API_token_secret = models.fields.CharField(max_length=100)
    
    def __str__(self):
        return f'{self.user.username} Twitter Container'

This is my views.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import TwitterUpdateForm


@login_required
def twitter(request):
    tw = TwitterUpdateForm(request.POST, instance=request.user)
    
    if tw.is_valid():
        tw.save()
        messages.success(request, f'NICE!')
        return redirect ('home')
    else:
        tw = TwitterUpdateForm(request.POST, instance=request.user)
        
    context = {'tw': tw}
    
    return render(request, 'twitter_container/twitter_container.html', context=context)

And last but not least, this is my html file.

{% extends 'home/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
    <div class="content-section">
        </div>
        <form method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <fieldset="form-group">
                <legend class="border-bottom mb-4">Profile Information</legend>
                {{ u_form|crispy }}
                {{ p_form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Update</button>
            </div>
        </form>
    </div>
{% endblock content %}

Oh, and my urls.py as well.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home.urls')),
    path('register/', user_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('profile/', user_views.profile, name='profile'),
    path('twitter/', twitter_views.twitter, name='twitter'),
]

The issue, I'm facing is that I'm unable to display the form fields from the model to the html. I want to be able to import information into the fields and update it to the database.

Please, do not judge me hard, I am completely newbie.

Thanks in advance.

1 Answers

First of all, you need to add action attribute in your form tag to call the view function when form gets submitted.

It should be like this:

<form method="POST" action ="{% url 'twitter'  %}" enctype="multipart/form-data">

Second thing that i found wrong in your html code is, why did you use u_form and p_form as a context variable? it should be 'tw' as per your view.

Try it out with above changes, it might help you out with your requirements.

Related