TIL

Web Dev Bootcamp TIL Day-31 (Django CRUD)

frannyk 2022. 5. 30. 15:46

CREATE

  • when creating a tweet model, we must keep in mind the one-many relationship between user-tweet
  • in our sample model, we set author = usermodel FK ---> this will save the usermodel's object ID inside the author field of the tweet model
class TweetModel(models.Model):
    class Meta:
        db_table = "tweet"

    author = models.ForeignKey(UserModel, on_delete=models.CASCADE)
    content = models.CharField(max_length=256)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

tweets inside DB: user w/ objectID=18 has posted 3 tweets
<form> tag and view for posting / saving a tweet to DB


READ

  • we can pass all the tweets that we've so far stored in our local DB to the client side in reverse chronological order
if request.method == 'GET':
    user = request.user.is_authenticated
    if user:
        #최신순으로 트윗들 모두 가져오기
        all_tweets = TweetModel.objects.all().order_by('-created_at')

        return render(request, 'tweet/home.html', {'tweets': all_tweets})
  • using Jinja2 syntax, we can create a dynamic template where a delete button will be displayed only on tweets whose author ==  currently logged in user
{% if tw.author == user %}
    <div style="text-align: right">
        <a href="/tweet/delete/{{ tw.id }}">
            <span class="badge rounded-pill bg-danger">삭제</span>
        </a>
    </div>
{% endif %}
<div style="text-align: right">
    <a href="#">
        <span class="badge rounded-pill bg-success">보기</span>
    </a>
</div>

 

  • we can access the username of each tweet's author by utilizing the FK of the tweet model
  • tw.author ---> usermodel objectID
  • tw.author.username ----> username of that usermodel object
{{ tw.author.username }}

DELETE

  • for deleting a tweet, we want the tweet to be deletable only by its author
    • we can use a control flow statement in jinja to create a dynamic template for this feature
  • we will then send to views the objectID of the tweet model we want to delete by creating a dynamic URL
{% if tw.author == user %}
    <div style="text-align: right">
        <a href="/tweet/delete/{{ tw.id }}">
            <span class="badge rounded-pill bg-danger">삭제</span>
        </a>
    </div>
{% endif %}
path('tweet/delete/<int:id>', views.delete_tweet, name='delete-tweet'),

 

@login_required
def delete_tweet(request, id):
    my_tweet = TweetModel.objects.get(id=id)
    my_tweet.delete()
    return redirect('/tweet')