Home > other >  How to autofill user and slug fields in django form
How to autofill user and slug fields in django form

Time:12-24

I need two of the three form fields to be filled in automatically before submitting to the database. Slug is supposed to be filled based on test_name, and user have to be filled based on data about the current user.

Now I can submit the form, but the database entry will not be created.

models.py

class Test(models.Model): 
    test_name = models.CharField(max_length=100, db_index=True, verbose_name='Test name') 
    slug = models.SlugField(max_length=100, unique=True, verbose_name='URL') 
    author = models.ForeignKey(User, db_column="user", on_delete=models.PROTECT) 

forms.py

class AddTestForm(forms.ModelForm): 
    class Meta: 
        model = Test 
        fields = ['test_name', 'slug', 'author'] 

views.py

def ask_test_name(request): 
    form = AddTestForm(request.POST) 
 
    if form.is_valid(): 
        test = form.save(False) 
        test.slug = slugify(test.test_name) 
        test.author = request.user 
        test.save() 
 
    return render(request, 'app/ask_test_name.html', {'form': form}) 

ask_test_name.html

<form action="{% url 'ask_test_name' %}" method="post"> 
    {% csrf_token %} 
    <p><input type="text" name="test_name" required></p> 
    <p><input type="hidden" name="slug"></p> 
    <p><input type="hidden" name="author"></p> 
    <p><button type="submit">Create</button></p> 
</form>

Updated

It seems to me the problem is that the html does not see what model I want to use, but I don't know how to solve it here, I need two fields to be hidden

CodePudding user response:

Remove slug and author from the fields in forms.py and don't include them in your HTML form. That should do the trick. You're only hitting the DB after already assigning values to slug and author, so that shouldn't throw an error.

  • Related