Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7081921
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:58:53+00:00 2026-05-28T06:58:53+00:00

I have a form created in mysite/new_player.html. It accepts 3 fields, user_name, real_name, and

  • 0

I have a form created in mysite/new_player.html. It accepts 3 fields, user_name, real_name, and site_played that correspond to the Player table in the database.

<h1> New Player </h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/stakeme/new/" method="post">
{% csrf_token %}
User Name: <input type="text" name="user_name" id="user_name"/><br>
Real Name: <input type="text" name="real_name" id="real_name"/><br>
Site Played: <input type="text" name="site_played" id="site_played"/><br><br>
<input type="submit" value="New Player" />
</form>

I am stuck on how to add this to my mysite/views.py file. I have gone through the polls tutorial, but the only form that is used in the tutorial is a multiple choice “choice” of the “poll” and I can’t seem to adapt that to text fields.

def new_player(request):
    return render_to_response('stakeme/new_player.html',
                           context_instance=RequestContext(request))

So as I understand it, I would need to create something like def add(request): return render_to_response('stakeme/new/'.. etc and add the POST data in here, but that’s where I am lost. I am not sure how to get the data into the database.

I am reading the Django docs, but I feel like I am just compounding something that I do not understand. If someone could point me in the right direction, I would really appreciate it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:58:54+00:00Added an answer on May 28, 2026 at 6:58 am

    Firstly, you don’t need to define a new view to process the form data. Also, you are creating your form directly in HTML – it’s possible to work this way (see later section of post) but it’s better (easier) to use the Django Forms library.

    Using Django Forms

    The documentation (v1.3 forms documentation) from the start up to and including ”Displaying a form using a template” explains the basics of using the forms library, so I’ll copy & paste liberally from there. I’ll also assume that you’re familiar with basic python constructs & have Django 1.3 installed. Without further ado, here’s my adhoc forms tutorial.

    Start a new django project:

    $ django.admin.py startproject mysite
    

    Add a new app:

    $ ./mysite/manage.py startapp myapp
    

    Lets create our contact form (modified from example in Django forms doc). Create a file in side the myapp/ directory called called forms.py and put the following in it:

    from django import forms
    
    class ContactForm(forms.Form):
        subject = forms.CharField(max_length=100)
        message = forms.CharField()
        sender = forms.EmailField(max_length=100)
    

    Next, since you mentioned storing data from received contact forms in a database, we’ll add a model, Feedback, to track received contact forms. In your models.py file, add the following:

    class Feedback(models.Model):
        subject = models.CharField(max_length=100)
        message = models.TextField()
        sender = models.CharField(max_length=100)
    
        def __unicode__(self):
            return "Subject:{subject}\nSender:{sender}\n{msg}".format(subject=self.subject,
                                                                    sender=self.sender,
                                                                    msg=self.message)
    

    (You may notice this is very similar to the form we defined earlier; normally in a scenario like this, one would use Django model forms to create a form directly from a model, but we are building our forms by hand as a learning experience)

    We also need to get Django to create the required table in our database for this Feedback model, so at the top of your settings.py insert the following useful code:

    import os
    PROJECT_DIR = os.path.dirname(__file__)
    

    And change the DATABASES setting in settings.py to the following to use a sqlite database:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': os.path.join(PROJECT_DIR, "sqlite.db").replace('\\', '/'),   # Or path to database file if using sqlite3.
            'USER': '',                      # Not used with sqlite3.
            'PASSWORD': '',                  # Not used with sqlite3.
            'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
            'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        }
    }
    

    Finally, change the INSTALLED_APPS setting to the following to include our recently created application myapp in the list of installed applications for mysite:

    INSTALLED_APPS = (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'myapp',
        # Uncomment the next line to enable the admin:
        # 'django.contrib.admin',
        # Uncomment the next line to enable admin documentation:
        # 'django.contrib.admindocs',
    )
    

    Now run the syncdb command to get Django to create the tables in your sqlite database (which, since it’s sqlite, will be created if it doesn’t exist yet):

    $ ./mysite/manage.py syncdb
    

    (Django will prompt you to create a superuser as well: you don’t have to create a superuser now since we don’t need it and you can use django-admin.py createsuperuser to create one when you need it, but you can create now now if you like)

    Now we need a view to display the contact form, and a view to thank people for submitting it. In your views.py file, add the following (modified slightly from Django forms docs):

    from django.core.urlresolvers import reverse
    from django.http import HttpResponseRedirect
    from django.shortcuts import render_to_response
    from django.template import RequestContext
    from myapp.forms import ContactForm
    from myapp.models import Feedback
    
    def thanks(request):
        return render_to_response('thanks.html')
    
    def contact(request):
        if request.method == 'POST': # If the form has been submitted...
            form = ContactForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass
                subject = form.cleaned_data['subject']
                message = form.cleaned_data['message']
                sender = form.cleaned_data['sender']
    
                feedback = Feedback(subject=subject, message=message, sender=sender)
                feedback.save()
    
                return HttpResponseRedirect(reverse('thanks')) # Redirect after POST
        else:
            form = ContactForm() # An unbound form
    
        return render_to_response('contact.html', {
            'form': form,
        }, context_instance=RequestContext(request))
    

    Now we need to map URLs to views. Open mysite/urls.py and make it look like the following

    from django.conf.urls.defaults import patterns, include, url
    
    # Uncomment the next two lines to enable the admin:
    # from django.contrib import admin
    # admin.autodiscover()
    
    urlpatterns = patterns('',
        # Examples:
        url(r'^thanks/$', 'myapp.views.thanks', name='thanks'),
        url(r'^$', 'myapp.views.contact', name='contact'),
        # url(r'^mysite/', include('mysite.foo.urls')),
    
        # Uncomment the admin/doc line below to enable admin documentation:
        # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    
        # Uncomment the next line to enable the admin:
        # url(r'^admin/', include(admin.site.urls)),
    )
    

    Now we need some templates to display the contact form & the thankyou page. Create a directory mysite/templates/, create a file contact.html inside it, and put the following in it:

    <html>
        <head>
            <title>Contact Us</title>
        </head>
        <body>
            <p>Please fill out the following information and click submit:</p>
    
            <form action="{% url contact %}" method="post">{% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>
    

    Also create a thanks.html page for the thank you page, and put the following in it:

    <html>
        <head>
            <title>Thanks</title>
        </head>
        <body>
            <p>Thank you. Your feedback is important to us</p>
    
            <p>Please leave some more feedback at the <a href="{% url contact %}">Contact page</a></p>
        </body>
    </html>
    

    Next, we need to make sure Django can find our templates, so modify the TEMPLATE_DIRS in mysite/settings.py setting to the following:

    TEMPLATE_DIRS = (
        # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
        os.path.join(PROJECT_DIR, "templates").replace('\\', '/'),
    )
    

    Now, (finally!), you can run the debug server and test that everything works:

    $ ./mysite/manage.py runserver 8080
    

    Go to http://localhost:8080/ and try to enter some feedback. When you click Submit, it should put your entered details into the database & show the thank you page. You can check the details are entered into the database:

    $ ./mysite/manage.py shell
    

    Into the shell, type:

    >>> from myapp.models import Feedback
    >>> for f in Feedback.objects.all(): print f
    

    (note that you need to press enter twice after entering the last line)

    You should see the feedback entries you have created.

    Creating forms manually in HTML

    If you insist on doing this, you can access the form’s request variables directly in your view using the request.POST dictionary, and then instantiating a model of your object manually & calling save (like in the contact() view function above).

    I would not recommend doing this, because you lose a whole bunch of nice features that Django Forms provides (CSRF protection, validation, etc).

    Other Tutorials

    Since the original form of this question asked for some tutorials: the official Django wiki has a page listing some tutorials, some of which deal with forms. Be aware that a lot of those tutorials are quite old (mostly from 2007-2009).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When you have an ASP.Net MVC form created by Html.BeginForm(), how do fields inside
I have created a form that is used for both adding and editing a
if i have created a view model and have a partial form that is
I have created a non-form c# program that uses the NotifyIcon class. The text
I have created an form validation using ajax/php. Each text box is validated using
I have a form with 3 panels, the panels are created because at certain
I created a form using Swing in Java. In the form I have used
I created a button and I need it to restart the form I have
I have created a simple test form with FormBorderStyle = FixedToolWindow by default and
I have created a great stand-alone web form in asp.net utilizing many jQuery features

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.