We'll also add a couple of views to views.py. Snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=())īecause 'snippets' is a reverse relationship on the User model, it will not be included by default when using the ModelSerializer class, so we needed to add an explicit field for it. In serializers.py add: from import UserĬlass UserSerializer(serializers.ModelSerializer): Now that we've got some users to work with, we'd better add representations of those users to our API. The quickest way to do this will be with the createsuperuser command. You might also want to create a few different users, to use for testing the API. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again. When that's all done we'll need to update our database tables. Self.highlighted = highlight(de, lexer, formatter) Options = įormatter = HtmlFormatter(style=self.style, linenos=linenos, Linenos = 'table' if self.linenos else False Use the `pygments` library to create a highlighted HTML save() method to our model class: def save(self, *args, **kwargs): We'll need some extra imports: from pygments.lexers import get_lexer_by_nameįrom import HtmlFormatterĪnd now we can add a. We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library. owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) The other field will be used to store the highlighted HTML representation of the code.Īdd the following two fields to the Snippet model in models.py. One of those fields will be used to represent the user who created the code snippet. We're going to make a couple of changes to our Snippet model class.įirst, let's add a couple of fields. Unauthenticated requests should have full read-only access.Only the creator of a snippet may update or delete it.Only authenticated users may create snippets.Code snippets are always associated with a creator. We'd like to have some more advanced behavior in order to make sure that: Currently our API doesn't have any restrictions on who can edit or delete code snippets.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |