|
30 | 30 | from django.db import connection, transaction
|
31 | 31 | from django.db.models import Count, Q, Sum
|
32 | 32 | from django.db.utils import IntegrityError
|
33 |
| -from django.forms import ModelForm |
| 33 | +from django.forms import ModelForm, ValidationError |
34 | 34 | from django.http import (
|
35 | 35 | HttpResponse,
|
36 | 36 | HttpResponseBadRequest,
|
@@ -399,10 +399,38 @@ def label_show(request, label_id: int, filter: ArticleFilter):
|
399 | 399 |
|
400 | 400 |
|
401 | 401 | class LabelForm(ModelForm):
|
| 402 | + """ |
| 403 | + Always instantiate with an instance. |
| 404 | + """ |
| 405 | + |
402 | 406 | class Meta:
|
403 | 407 | model = Label
|
404 | 408 | fields = ["text", "feeds"]
|
405 | 409 |
|
| 410 | + def clean_text(self): |
| 411 | + """ |
| 412 | + Validate that the label text is unique |
| 413 | + """ |
| 414 | + data = self.cleaned_data["text"] |
| 415 | + if data == self.instance.text: # No change |
| 416 | + return data |
| 417 | + |
| 418 | + if self.instance.user.label_set.filter(text=data).count() > 0: |
| 419 | + raise ValidationError( |
| 420 | + "Label text must be unique", |
| 421 | + code="duplicate" |
| 422 | + ) |
| 423 | + |
| 424 | + return data |
| 425 | + |
| 426 | + def clean_feeds(self): |
| 427 | + """ |
| 428 | + Ensure that only the user's own feeds are selectable. Other PKs are |
| 429 | + ignored. |
| 430 | + """ |
| 431 | + data = self.cleaned_data["feeds"] |
| 432 | + return self.instance.user.feed_set.intersection(data) |
| 433 | + |
406 | 434 |
|
407 | 435 | @login_required
|
408 | 436 | def label_edit(request, label_id: int):
|
@@ -437,25 +465,22 @@ def label_add(request):
|
437 | 465 | """
|
438 | 466 | Add a new label.
|
439 | 467 | """
|
| 468 | + label = Label(user=request.user) |
440 | 469 | if request.method == "POST":
|
441 |
| - form = LabelForm(request.POST) |
| 470 | + form = LabelForm(request.POST, instance=label) |
442 | 471 | if form.is_valid():
|
443 |
| - label = form.save(commit=False) |
444 |
| - label.user = request.user |
| 472 | + label = form.save(commit=True) |
445 | 473 | label.save()
|
446 |
| - label.feeds.set( |
447 |
| - request.user.feed_set.filter(id__in=form.cleaned_data["feeds"]), |
448 |
| - ) |
449 | 474 | return HttpResponseRedirect(
|
450 | 475 | reverse(
|
451 | 476 | "label-show",
|
452 | 477 | kwargs={"label_id": label.pk, "filter": ArticleFilter.unread},
|
453 | 478 | ),
|
454 | 479 | )
|
455 |
| - elif request.method == "GET": |
456 |
| - form = LabelForm() |
457 |
| - else: |
| 480 | + elif request.method != "GET": |
458 | 481 | return HttpResponseNotAllowed(["GET", "POST"])
|
| 482 | + else: |
| 483 | + form = LabelForm(instance=label) |
459 | 484 | return render(request, "label_add.html", {
|
460 | 485 | "form": form,
|
461 | 486 | "tabs_selected": {"global-label-list"},
|
|
0 commit comments