forms.py:
class Postform(forms.ModelForm):
class Meta:
model=Post
fields=['title','sometext','tags']
widgets={
'title':forms.TextInput(attrs={'class':'form-control'}),
'tags': forms.SelectMultiple(attrs={'class': 'form-control'}),
'sometext':forms.Textarea(attrs={'class':'form-control'})
}<code lang="django">
</code>
def clean_title(self):
new_text = self.cleaned_data['title'].lower
if new_text =='':
raise ValidationError('title may not be')
if Post.objects.filter(title__iexact=new_text).count():
raise ValidationError('title must be unique We have it"{}" it yet'.format(new_text))
return new_text
def save(self):
new_post=Post.objects.create(title=self.cleaned_data['title'],
sometext=self.cleaned_data['sometext'],
tags=self.cleaned_data['tags'],
)
return new_post
html формы:
{% extends 'foundation/base.html' %}
{% block title %}
Create Post - {{block.super}}
{% endblock %}
{% block content %}
<form action="{% url 'postcreate_url' %}" method="post" >
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field.label}}
{{ field}}
</div>
{% if field.errors %}
<div class="alert alert-danger">
{{ field.errors}}
</div>
{% endif %}
{% endfor %}
<button type="submit" class="btn btn-primary" >Create Post</button>
</form>
{% endblock %}
views.py:
class Postcreate(View):
def get(self,request):
form =Postform()
return render(request,'foundation/Post_create.html',context={'form':form})
def post(self,request):
bound_form=Postform(request.POST)
print(bound_form)
print(bound_form['title'])
if bound_form.is_valid():
new_post=bound_form.save()
return redirect(new_post)
return render(request, 'foundation/Post_create.html', context={'form': bound_form})
models.py:
from django.db import models
from django.shortcuts import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=50, db_index=True)
sometext=models.CharField(max_length=50,db_index=True)
tags=models.ManyToManyField('Tag',blank=True, related_name='posts')
date_pub=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('postdetail_url',kwargs={'sometext':self.sometext})
class Tag(models.Model):
title=models.CharField(max_length=50)
sometext=models.CharField(max_length=50)
def get_absolute_url(self):
return reverse('tag_url',kwargs={'title':self.title})
def _str_(self):
return self.title