Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask Broadcasting Stream Views

Getting builtins.TypeError TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

I am doing this work on my PC, everything is working fine but when i try to post, i get this builtins.TypeError. TypeError: init() takes from 1 to 2 positional arguments but 3 were given

I don't understand what's wrong with my code. I have checked the code again and again, but din't found the mistake.

Please help me.

This is what i am getting in browser when i click on Post to post something.

Traceback (most recent call last):
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "c:\tools\python3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "c:\tools\python3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "c:\tools\python3\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "c:\tools\python3\lib\site-packages\flask_login.py", line 792, in decorated_view
    return func(*args, **kwargs)
  File "c:\Users\Nitesh Sharma\OneDrive\Documents\My Stuff\My Web Development Stuff\Learning Flask\Flask Social\app.py", line 91, in post
    if form.validate_on_submit():
  File "c:\tools\python3\lib\site-packages\flask_wtf\form.py", line 166, in validate_on_submit
    return self.is_submitted() and self.validate()
  File "c:\tools\python3\lib\site-packages\wtforms\form.py", line 310, in validate
    return super(Form, self).validate(extra)
  File "c:\tools\python3\lib\site-packages\wtforms\form.py", line 152, in validate
    if not field.validate(self, extra):
  File "c:\tools\python3\lib\site-packages\wtforms\fields\core.py", line 204, in validate
    stop_validation = self._run_validation_chain(form, chain)
  File "c:\tools\python3\lib\site-packages\wtforms\fields\core.py", line 224, in _run_validation_chain
    validator(form, self)
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

[MOD: added ```python formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Can you post you app.py? An object is being created with the wrong number of parameters.

2 Answers

Thanks Chris. Actually i found the problem. In forms.py i forget to put parenthesis after validator 'DataRequired'.

Yaa Sure,

from flask import (Flask, g, render_template, flash, redirect, url_for)
from flask.ext.bcrypt import check_password_hash
from flask.ext.login import (LoginManager, login_user, logout_user, 
                            login_required, current_user)

import forms
import models

DEBUG = True
PORT = 8000
HOST = '0.0.0.0'

app = Flask(__name__)
app.secret_key = 'asdnafnj#46sjsnvd(*$43sfjkndkjvnskb6441531@#$$6sddf'
"""here secret_key is a random string of alphanumerics"""

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(userid):
    try:
        return models.User.get(models.User.id == userid)
    except models.DoesNotExist:
        return None


@app.before_request
def before_request():
    """Connect to database before each request
        g is a global object, passed around all time in flask, used to setup things which 
        we wanna have available everywhere.
    """
    g.db = models.DATABASE
    g.db.connect()
    g.user = current_user


@app.after_request
def after_request(response):
    """close all database connection after each request"""
    g.db.close()
    return response


@app.route('/register', methods = ('GET','POST'))
def register():
    form = forms.RegisterForm()
    if form.validate_on_submit():
        flash("Congrats, Registered Successfully!", "success")
        models.User.create_user(
            username = form.username.data,
            email = form.email.data,
            password = form.password.data
        )
        return redirect(url_for('index'))
    return render_template('register.html', form = form)


@app.route('/login', methods = ('GET', 'POST'))
def login():
    form = forms.LoginForm()
    if form.validate_on_submit():
        try:
            user = models.User.get(models.User.email == form.email.data)
        except models.DoesNotExist:
            flash("Your email or password does not match", "error")
        else:
            if check_password_hash(user.password, form.password.data):
                login_user(user) 
                """Creating a session on user's browser"""
                flash("You have been logged in", "success")
                return redirect(url_for('index'))
            else:
                flash("Your email or password does not match", "error")
    return render_template('login.html', form = form)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash("You have been logged out.")
    return redirect(url_for('login'))


@app.route('/new_post', methods = ('GET', 'POST'))
@login_required
def post():
    form = forms.PostForm()
    if form.validate_on_submit():
        models.Post.create(user = g.user.id, 
                            content = form.content.data.strip())
        flash("Message Posted: Thanks!", "success")
        return redirect(url_for('index'))
    return render_template('post.html', form = form)



@app.route('/')
def index():
    stream = models.Post.select().limit(100)
    return render_template('stream.html', stream = stream)

@app.route('/stream')
@app.route('/stream/<username>')
def stream(username = None):
    template = 'stream.html'
    if username and username != current_user.username:
        user = models.User.select().where(models.User.username**username).get()
        stream = user.posts.limit(100)
    else:
        stream = current_user.get_stream().limit(100)
        user = current_user
    if username:
        template = 'user_stream.html'
    return render_template(template, stream = stream, user = user)



if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username = 'niteshsharma',
            email = 'nbsharma@outlook.com',
            password = 'password',
            admin = True
        )
    except ValueError:
        pass
    app.run(debug=DEBUG,host = HOST, port = PORT)