Три вопроса о django-autocomplete-light
Я использую django-autocomplete-light в своем Django проекте. Я создаю новую статью для списка статей. И в этом третьем приложении я хочу использовать автозаполнение и создать новую форму для названия журнала, года журнала, тома и номера. Например, в моих моделях основной моделью является Article с полем: journal, journal year, volume and issue. Это поле имеет внешний ключ в своей модели. Также в шаблоне я использую зависимость от выпадающего списка. название журнала -> год журнала -> том и номер
Как это работает? Если пользователь хочет добавить свою статью на сайт. Он выбирает название журнала, год выпуска, том и номер. Если у него нет информации во внешнем ключе, он может создать новую информацию о нем.
Я мог бы построить его, но у меня есть некоторые проблемы.
Depends on dropdown work good, but If I use create new one, I want to assign it to a foreign key. For example, the User created journal, year, volume and issue, and then when other user want to add in the same journal, year, volume and issue they can do it. Now new Foreign key to create in database, but It does not assign to depend on dropdown. In this case, the year is not given in the journal or volume, and the issue is not given in the year.
Depending on the drop-down list show all information contains in year, volume and issue. I want me to select a journal and then show information in year If I don't select a journal, I don't see information for the year, volume, and issue
I can't build create new field for field contains in other app Django. In my case, I have two app: articles and journal. I use django-autocomplete-light in articles app, but models for journals contain in journals.
articles/models.py
class Article(models.Model, HitCountMixin):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
title = models.CharField(max_length=255)
author = models.ForeignKey("users.CustomUser", on_delete=models.SET_NULL, null=True)
keywords = models.CharField(max_length=50)
abstract = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
language = models.ForeignKey("Language", on_delete=models.SET_NULL, null=True)
journal = models.ForeignKey(
"journals.Journal", on_delete=models.SET_NULL, null=True, blank=True
)
journalyear = models.ForeignKey(
"JournalYear", on_delete=models.SET_NULL, null=True, blank=True
)
journalvolume = models.ForeignKey(
"JournalVolume", on_delete=models.SET_NULL, null=True, blank=True
)
class JournalYear(models.Model):
journal = models.ForeignKey(
"journals.Journal", on_delete=models.SET_NULL, null=True, blank=True
)
name = models.CharField(max_length=10, blank=True, null=True)
def __str__(self):
return self.name
class JournalVolume(models.Model):
journalyear = models.ForeignKey(
"JournalYear", on_delete=models.CASCADE, blank=True, null=True
)
name = models.CharField(max_length=10, blank=True, null=True)
def __str__(self):
return self.name
articles/views.py
class ArticleCreateView(CreateView, SuccessMessageMixin):
model = Article
form_class = ArticleForm
template_name = "articles/article_create.html"
success_message = "%(title)s was updated successfully"
def form_valid(self, form):
form.instance.author = self.request.user
return super(ArticleCreateView, self).form_valid(form)
class JournalAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated:
return Journal.objects.none()
qs = Journal.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
class JournalYearAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated:
return JournalYear.objects.none()
qs = JournalYear.objects.all()
journal = self.forwarded.get("journal", None)
if journal:
qs = qs.filter(journal=journal)
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
class JournalVolumeAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated:
return JournalVolume.objects.none()
qs = JournalVolume.objects.all()
journalyear = self.forwarded.get("journalyear", None)
if journalyear:
qs = qs.filter(journalyear=journalyear)
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
articles/urls.py
urlpatterns = [
path("articles/create", ArticleCreateView.as_view(), name="article_create"),
path(
"journalvolumeautocomplete/",
JournalVolumeAutocomplete.as_view(create_field="name"),
name="journalvolumeautocomplete",
),
path(
"journalyearautocomplete/",
JournalYearAutocomplete.as_view(create_field="name"),
name="journalyearautocomplete",
),
path(
"journalautocomplete/",
JournalAutocomplete.as_view(create_field="name"),
name="journalautocomplete",
),
]
articles/forms.py
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
exclude = ["author", "id"]
widgets = {
"journalvolume": autocomplete.ModelSelect2(
url="journalvolumeautocomplete", forward=["journalyear"]
),
"journalyear": autocomplete.ModelSelect2(
url="journalyearautocomplete", forward=["journal"]
),
"journal": autocomplete.ModelSelect2(url="journalautocomplete"),
}
template/articles/create.html
<form method="post">{% csrf_token %}
{{ form.media }}
{{form.as_p}}
<button type="submit"> Create a new article Article</button>
</form>
journals/models.py
class Journal(models.Model):
slug = models.SlugField(unique=True)
name = models.CharField(max_length=100, blank=True, null=True)