models.py:
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
thumb = models.ImageField(default='default-3.jpg', blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
tags = models.ManyToManyField('Tag', blank=True) #поле с тегом, привязано к классу Tag
def __str__(self):
return self.title
def snippet(self):
return self.body[:50] + '...'
class Tag(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
def __str__(self):
return self.title
forms.py:
from django import forms
from . import models
class CreateArticle(forms.ModelForm):
class Meta:
model = models.Article
fields = ['title', 'body', 'slug', 'tags', 'thumb']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'slug': forms.TextInput(attrs={'class': 'form-control'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
'tags': forms.SelectMultiple(attrs={'class':'forms-control'})
}
view.py:
@login_required(login_url='/accounts/login/')
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('article:list')
else:
form = forms.CreateArticle
return render(request, 'app/article_create.html', {'form': form})
html:
{% block content %}
<div class='login-container'>
<div class='login-border'>
<div>
<h2>Create New Article</h2>
<form class='site-create' action="{% url 'article:create' %}" method='post' enctype='multipart/form-data'>
{% csrf_token %}
{{ form }}
<input class='login-button' type="submit" value='Create'>
</form>
</div>
<script src='/static/slugify.js'></script>
</div>
</div>
{% endblock %}