A
A
Alexander2016-04-02 21:14:02
Django
Alexander, 2016-04-02 21:14:02

How to fill the slug field automatically through the form?

Good evening, how to fill in the slug field automatically through the form? I am making a bulletin board, it is necessary that when a person fills out all the fields of the ad, the slug field is filled in automatically from the title, there is a model

class Advert(models.Model):
    region = models.CharField(max_length=32)
    city = models.CharField(max_length=30)
    category = models.TextField()
    title = models.CharField(max_length=32)
    description = models.CharField(max_length=900)
    photo = models.ImageField(upload_to='')
    phone_number = models.CharField(max_length=11)
    date = models.DateTimeField(auto_now_add=True, null=True)
    slug = models.SlugField(unique=True, null=True, blank=True)

    def __str__(self):
        return self.title

there is a form
class AddAdvertForm(ModelForm):
    region = forms.ModelChoiceField(queryset=Russian_Federation_Regions.objects.order_by('region'))
    city = forms.Field(widget=forms.Select)
    category = forms.ModelChoiceField(queryset=CategoryAdvert.objects.order_by('name'))
    title = forms.CharField()
    description = forms.CharField(widget=forms.Textarea)
    phone_number = forms.CharField(widget=forms.NumberInput)

    class Meta:
        model = Advert
        fields = '__all__'

and vyushka
class CreateAdvertView(View):
    template_name = 'bulletinboard/add_advert.html'
    form_class = AddAdvertForm

    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            print(form.title)
            form.save()
            return HttpResponseRedirect('/advert/')
        return render(request, self.template_name, {'form': form})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2016-04-02
@AlexMine

django-autoslug

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question