Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Build a Social Network with Flask Broadcasting Post Form and View

See the following error on 'Post Form and View' code: __init__() missing 1 required positional argument: 'model'

Any idea how I can fix this error?

Traceback (most recent call last): File "app.py", line 7, in <module> import forms

File "/flask-social/forms.py", line 6, in <module> from models import User

File "/flask-social/models.py", line 62, in <module> class Post(Model):

File "/flask-social/models.py", line 66, in Post related_name='posts'

TypeError: init() missing 1 required positional argument: 'model'

6 Answers

Peewee 3.x no longer supports rel_model or related_name - instead, use model and backref. See their change log here.

Try using the following:

class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        model=User,
        backref='posts')
    content = TextField()

    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)

Credit: https://stackoverflow.com/questions/51224092/typeerror-init-missing-1-required-positional-argument-model

Thanks Wes, I updated and then it threw some other peewee errors.

Traceback (most recent call last):
  File "app.py", line 174, in <module>
    models.initialize()
  File "/flask-social/models.py", line 92, in initialize
    DATABASE.create_tables([User, Post, Relationship], safe=True)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 3036, in create_tables
    model.create_table(**options)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 6060, in create_table
    cls._schema.create_all(safe, **options)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 5270, in create_all
    self.create_indexes(safe=safe)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 5183, in create_indexes
    for query in self._create_indexes(safe=safe):
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 5172, in _create_indexes
    for index in self.model._meta.fields_to_index()]
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 5544, in fields_to_index
    fields.append(self.combined[part])
KeyError: 'f'

Which I saw a fix for stating it was due to tuples in peewee, and would fix key error 'f;

https://stackoverflow.com/questions/49115997/peewee-throws-keyerror-f

I then applied the above suggested additional fix

    indexes = ((('from_user', 'to_user'), True),)

But then it throws this error below. So not sure if the above tuple fix was best fix, but if yes, then now how to fix the below?

Traceback (most recent call last):
  File "app.py", line 184, in <module>
    app.run(debug=DEBUG, host=HOST, port=PORT)
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 943, in run
    run_simple(host, port, self, **options)
  File "/flask-social/myenv/lib/python3.7/site-packages/werkzeug/serving.py", line 988, in run_simple
    run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
  File "/flask-social/myenv/lib/python3.7/site-packages/werkzeug/_reloader.py", line 332, in run_with_reloader
    sys.exit(reloader.restart_with_reloader())
  File "/flask-social/myenv/lib/python3.7/site-packages/werkzeug/_reloader.py", line 176, in restart_with_reloader
    exit_code = subprocess.call(args, env=new_environ, close_fds=False)
  File "/Users/asawa/anaconda3/lib/python3.7/subprocess.py", line 317, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/Users/asawa/anaconda3/lib/python3.7/subprocess.py", line 769, in __init__
    restore_signals, start_new_session)
  File "/Users/asawa/anaconda3/lib/python3.7/subprocess.py", line 1516, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
OSError: [Errno 8] Exec format error: '/flask-social/app.py'

Hmm, you do indeed need to fix the tuple but it sounds like you're missing your shebang line from your app.py. While your virtual environment is active, try which python3. Most likely, the path you see should be for the python you have in your environment. For example, mine is something like:

/Users/myname/my/project/path/.../social-app/env/bin/python3

Copy all of it and add it to the top of your app.py like this, replacing it with your path:

#!/Users/myname/my/project/path/.../social-app/env/bin/python3

That worked, thank you Wes.

The code is now throwing another set of errors, seems related to Peewee update again.

Can I assume the crux of the issue is the need to add join_date? Because it can't truly be that the user already exists since the info I am using is all different. Not sure how to deal with this one.

Traceback (most recent call last):
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2875, in execute_sql
    cursor.execute(sql, params or ())
sqlite3.IntegrityError: NOT NULL constraint failed: user.join_date

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/flask-social/models.py", line 57, in create_user
    is_admin=admin)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 5816, in create
    inst.save(force_insert=True)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 5967, in save
    pk_from_cursor = self.insert(**field_dict).execute()
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 1737, in inner
    return method(self, database, *args, **kwargs)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 1808, in execute
    return self._execute(database)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2512, in _execute
    return super(Insert, self)._execute(database)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2275, in _execute
    cursor = database.execute(self)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2888, in execute
    return self.execute_sql(sql, params, commit=commit)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2882, in execute_sql
    self.commit()
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2666, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 179, in reraise
    raise value.with_traceback(tb)
  File "/flask-social/myenv/lib/python3.7/site-packages/peewee.py", line 2875, in execute_sql
    cursor.execute(sql, params or ())
peewee.IntegrityError: NOT NULL constraint failed: user.join_date

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/flask-social/myenv/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/flask-social/app.py", line 55, in register
    password=form.password.data
  File "/flask-social/models.py", line 59, in create_user
    raise ValueError("User already exists")
ValueError: User already exists
Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

Howdy all, just wanted to give a no-update update and let you know that Ashley Boucher and I are digging into this. This course is on our roadmap for a full refresh, but we'll see if we can fix this specific issue in the mean time.

i have this problem now what is solution please ?

Pierson Brannan
Pierson Brannan
1,141 Points

Could you post your code where that class is? Hard to say what it is when we can't look at the code.

From my understanding, these types of errors happen when a variable in the class calls on an argument that doesn't actually exist. In your case, 'model' may not be defined.

Make sure you 'model' is being called in the arguments of the __init__

class NateMan:
   def __init__(self, model):
      self.model = model
   def showModel(self):
      print(self.model)

Hi Pierson, yes, I actually compared and ran into this error with the supplied class files.

So it seems to be an issue not just in my code but also in the provided files. So I don't think its just what I coded.

Showing code snippets below for

1) the lines inclusive of 62 and 66 the traceback error references from models.py

2) the main initialization lines from app.py (though traceback does not show an error explicitly here)

3) then the full models.py code just as reference

Thank you for responding and looking at this issue!

class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='posts'
    )
    content = TextField()

    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)
if __name__ == '__main__':
    models.initialize()
    try:
        models.User.create_user(
            username='kennethlove',
            email='kenneth@teamtreehouse.com',
            password='password',
            admin=True
        )
    except ValueError:
        pass
    app.run(debug=DEBUG, host=HOST, port=PORT)
import datetime

from flask_bcrypt import generate_password_hash
from flask_login import UserMixin
from peewee import *

DATABASE = SqliteDatabase('social.db')

class User(UserMixin, Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField(max_length=100)
    joined_at = DateTimeField(default=datetime.datetime.now)
    is_admin = BooleanField(default=False)

    class Meta:
        database = DATABASE
        order_by = ('-joined_at',)

    def get_posts(self):
        return Post.select().where(Post.user == self)

    def get_stream(self):
        return Post.select().where(
            (Post.user << self.following()) |
            (Post.user == self)
        )

    def following(self):
        """The users that we are following."""
        return (
            User.select().join(
                Relationship, on=Relationship.to_user
            ).where(
                Relationship.from_user == self
            )
        )

    def followers(self):
        """Get users following the current user"""
        return (
            User.select().join(
                Relationship, on=Relationship.from_user
            ).where(
                Relationship.to_user == self
            )
        )

    @classmethod
    def create_user(cls, username, email, password, admin=False):
        try:
            with DATABASE.transaction():
                cls.create(
                    username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
        except IntegrityError:
            raise ValueError("User already exists")


class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='posts'
    )
    content = TextField()

    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)


class Relationship(Model):
    from_user = ForeignKeyField(User, related_name='relationships')
    to_user = ForeignKeyField(User, related_name='related_to')

    class Meta:
        database = DATABASE
        indexes = (
            (('from_user', 'to_user'), True)
        )


def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Post, Relationship], safe=True)
    DATABASE.close()

Hi Ben, thanks for posting and letting me know. As it’s been 1 month, is there any further update on a possible specific fix for this issue and timing on course refresh? I care specifically about this class for being able to apply it in my own projects. It is a high priority for me, so hoping for a solution. Thank you!

Ben Jakuben
Ben Jakuben
Treehouse Teacher

I'm sorry about the delayed response here. We're revamping Python plans for the rest of the year, and it looks like we're going to focus on Django refreshes over Flask because of its higher demand in the job market. We are also confident that students who learn Django with us will be able to pick up Flask pretty easily after that. This is a little bit of a moving target, but it means we'll retire Flask content as issues like this pop up, and with updated Django content, we'll be able to offer a better learning path in the Techdegree and Django track.