Code Monkey home page Code Monkey logo

django-realworld-example-app's Introduction

Django DRF Example App

Example Django DRF codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.

This repo is functionality complete โ€” PR's and issues welcome!

Installation

  1. Clone this repository: git clone [email protected]:gothinkster/productionready-django-api.git.
  2. cd into conduit-django: cd productionready-django-api.
  3. Install pyenv.
  4. Install pyenv-virtualenv.
  5. Install Python 3.5.2: pyenv install 3.5.2.
  6. Create a new virtualenv called productionready: pyenv virtualenv 3.5.2 productionready.
  7. Set the local virtualenv to productionready: pyenv local productionready.
  8. Reload the pyenv environment: pyenv rehash.

If all went well then your command line prompt should now start with (productionready).

If your command line prompt does not start with (productionready) at this point, try running pyenv activate productionready or cd ../productionready-django-api.

If pyenv is still not working, visit us in the Thinkster Slack channel so we can help you out.

django-realworld-example-app's People

Contributors

brwr avatar ericsimons avatar jamesbrewerdev avatar priyadhoundiyal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-realworld-example-app's Issues

Reimplement profiles views with Generic Views from DRF

The profile views are good candidates to reuse some common patterns with Generic Views from Django REST framework and make the code more DRY.

ProfileRetrieveAPIView looks like this:

class ProfileRetrieveAPIView(RetrieveAPIView):
    permission_classes = (AllowAny,)
    queryset = Profile.objects.select_related('user')
    renderer_classes = (ProfileJSONRenderer,)
    serializer_class = ProfileSerializer

    def retrieve(self, request, username, *args, **kwargs):
        # Try to retrieve the requested profile and throw an exception if the
        # profile could not be found.
        try:
            profile = self.queryset.get(user__username=username)
        except Profile.DoesNotExist:
            raise NotFound('A profile with this username does not exist.')

        serializer = self.serializer_class(profile, context={
            'request': request
        })

        return Response(serializer.data, status=status.HTTP_200_OK)

Using generic views features, will look like this:

class ProfileRetrieveAPIView(RetrieveAPIView):
    permission_classes = (AllowAny,)
    queryset = Profile.objects.select_related('user')
    renderer_classes = (ProfileJSONRenderer,)
    serializer_class = ProfileSerializer
    lookup_field = 'user__username'
    lookup_url_kwarg = 'username'

Error on runserver: Specifying a namespace in include() without providing an app_name is not supported

Enviroment

  • Docker Community Stable
  • Image: python:3

OBS

After add a property app_name in each django app the run server runs correctly

Ex: app_name = 'authentication'

Log

`root@02edf224ea78:/app# python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check
all_issues = self._run_checks(
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 399, in check
for pattern in self.url_patterns:
File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 80, in get
res = instance.dict[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 584, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 80, in get
res = instance.dict[self.name] = self.func(instance)
File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 577, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/local/lib/python3.8/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in find_and`

Django Cors

Looks like a great project.

I tried installing in both python2.7 and python3.5 and got the same error.
When running

python manage.py runserver

I got

mw_instance = middleware(handler)
TypeError: object() takes no parameters

So by upgrading to django=1.10.5 and adding django-cors-headers==1.3.1.

I was able to get the project to build.

Hopefully this helps someone

How do you run this?

How do you run this? There are no instructions in the README. I got as far as completing the build steps (I had to do pyenv install 3.5.3 instead of 3.5.2 because of openssl dependency issues) but there is nothing actually running.

in authentication.Models

the function token creates a new token every time because it returns self._generate_jwt_token()
so when i use postman and a post request to login, i get a new token every time I correctly login.

When i use postman to a get request, how would it find the correct user if the token keeps changing?
Thats why I think this may be an error, I may most likely be wrong, I've asked on slack no response, I've asked on stackoverflow no response, this is my only shot

does not work with Angular front end

The Angular front end does not work with this Django backend, yet it works with other backends, such as the Flask backend.

That could be an issue on the Angular front end side... but could be from the Django side in adhering to the specs?? Specifically might it be connected to Django's ending slash preference on urls??

dt.strftime('%S')

I could runserver following hunterway55 comments: upgrading to django=1.10.5 and adding django-cors-headers==1.3.1, but the Postman register & login commands didn't work.

In apps/authentication/models.py

I replaced dt.strftime('%s') by dt.strftime('%S') and the Login & Register commands worked.

Token generation function is now:

def _generate_jwt_token(self):
    """
    Generates a JSON Web Token that stores this user's ID and has an expiry
    date set to 60 days into the future.
    """
    dt = datetime.now() + timedelta(days=60)

    token = jwt.encode({
        'id': self.pk,
        'exp': int(dt.strftime('%S'))
    }, settings.SECRET_KEY, algorithm='HS256')

    return token.decode('utf-8')

Hope it helps someone.

Segmentation Fault

I created a virtualenv, cloned the git project, and ran the initial migration.

image

Type of views

Do I need to override the create method on the article-view if I am using generic class based views.
I am not trying to replicate everything you have done but just using this as reference. I have two views One which returns a list of my article objects, and one which returns just one article.

#  1.I only want to save the author of an article
#  2.Create a slug based on the title and id
#  3.make the slug the lookup field****
                                                          ##   #Please Help!!!!!!

#MY FILES:

my article views
my_models

failing to runserver - ImportError: No module named 'pysqlite2'

Hi,
I tried to run the django server. However I get the following error :
ImportError: No module named 'pysqlite2'
full log below.

What can be the cause of this error?

Traceback (most recent call last):
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 34, in
from pysqlite2 import dbapi2 as Database
ImportError: No module named 'pysqlite2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 36, in
from sqlite3 import dbapi2 as Database
File "/home/idan/.pyenv/versions/3.5.2/lib/python3.5/sqlite3/init.py", line 23, in
from sqlite3.dbapi2 import *
File "/home/idan/.pyenv/versions/3.5.2/lib/python3.5/sqlite3/dbapi2.py", line 27, in
from _sqlite3 import *
ImportError: No module named '_sqlite3'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "manage.py", line 22, in
execute_from_command_line(sys.argv)
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/core/management/init.py", line 367, in execute_from_command_line
utility.execute()
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/core/management/init.py", line 341, in execute
django.setup()
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/init.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "/home/idan/.pyenv/versions/3.5.2/lib/python3.5/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 958, in _find_and_load_unlocked
File "", line 673, in _load_unlocked
File "", line 665, in exec_module
File "", line 222, in _call_with_frames_removed
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in
class AbstractBaseUser(models.Model):
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/models/base.py", line 119, in new
new_class.add_to_class('_meta', Options(meta, app_label))
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/models/base.py", line 316, in add_to_class
value.contribute_to_class(cls, name)
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/models/options.py", line 214, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/init.py", line 33, in getattr
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/utils.py", line 211, in getitem
backend = load_backend(db['ENGINE'])
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/utils.py", line 115, in load_backend
return import_module('%s.base' % backend_name)
File "/home/idan/.pyenv/versions/3.5.2/lib/python3.5/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/home/idan/.pyenv/versions/productionready/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 39, in
raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3'

Update to latest?

Will this get updated at any point to more recent Django version?

CORS issues

Anyone else having trouble with CORS issues?

I get this when trying to access the django api on localhost:5000 from angular4 localhost:4200...

XMLHttpRequest cannot load http://localhost:8000/api/articles?limit=10&offset=0. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Profiles/Articles Serializers

In the Profiles and Articles serializers the parenthesis should be removed on the code below:

if not request.user.is_authenticated():

You are using as a function, according to the docs is_authenticated is an attribute not a method.

if not request.user.is_authenticated:

Image field always return empty

It is empty every time when I retrieve in the authentication route
u'profile': OrderedDict([(u'bio', u'Java developer')])
Image field is not here.

Image in profile can't be updated

On the endpoint {{apiUrl}}/user - the PUT request does not save the image in the user's profile since image field is a SerializerMethodField(which is readonly) in ProfileSerializer.

I was thinking that one way to allow image to be updated could be to remove image as a SerializerMethodField but keep it included in serializer fields like so:

class ProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    bio = serializers.CharField(allow_blank=True, required=False)
    following = serializers.SerializerMethodField()

    class Meta:
        model = Profile
        fields = ('username', 'bio', 'image', 'following',)
        read_only_fields = ('username',)

    def get_following(self, instance):
        request = self.context.get('request', None)

        if request is None:
            return False

        if not request.user.is_authenticated():
            return False

        follower = request.user.profile
        followee = instance

        return follower.is_following(followee)

But in this way we end up losing the default image for the profile in the {{apiUrl}}/profiles/ view.

To get the default image in the {{apiUrl}}/user view - we could include image as a SerializerMethodField there
image = serializers.SerializerMethodField()
and define get_image as:

def get_image(self, obj):
    if obj.profile.image:
        return obj.profile.image
    return 'https://static.productionready.io/images/smiley-cyrus.jpg'

but I don't think it's very consistent if the user endpoint shows a default value for the image but the profile endpoint does not.
Could anyone share another - hopefully consistent - way to do this?
TIA

Faulty unique constraint on slug field of Tag model

The Tag model has "unique=True" set for the slug field. This must be an error since it implies that we can only have one tag per slug... Below is the code pasted from conduit/articles/models.py.

class Tag(TimestampedModel):
tag = models.CharField(max_length=255)
slug = models.SlugField(db_index=True, unique=True)

Failing to decode token and get current user with postman

After adding the custom authentication backend in backends.py and settings.py. It seems like it caused a total breakdown of all the endpoints. I cannot get current user and the url endpoints that work before don't work anymore.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.