Django
-
There's a uniform with one field where you need to choose your login (logins are taken from the OBD - auth_user.username). Half the login is ForeignKey.
It was for the test. Now I want to remove this field and make sure that this field is filled with hidden and automaticity depending on the authorised logic on the website.
models.py:
class Watches_db(models.Model): ... account = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='Аккаунт')
forms.py:
class Add_watches_form(forms.ModelForm): class Meta: model = Watches_db fields = [..., 'account'] widgets = {}
views.py:
class AddMyWatches(CreateView): form_class = Add_watches_form template_name = 'marketplace/add_product/add_watches.html'
def get_context_data(self, *, object_list=None, **kwargs):
cont = super().get_context_data(**kwargs)
cont['title'] = 'Добавьте свой товар'
return cont
add_watches.html:
<form action = '' method='post' enctype="multipart/form-data">
{% csrf_token %}{% for wf in form %}
<p><label class='form-label' for='{{wf.id_for_label}}'>{{wf.label}}: </label>{{wf}}</p>
<div class = 'form-error'>{{wf.errors}}</div>
{% endfor %}<button type="submit">Добавить товар</button>
</form>
As one of my ideas is to say the request.user.username and return for this field. But I have no idea how to do it.
-
There are two options.
- Either we take the form to edit the field of account (excluding it from form, making editable=False), then we'll need to redesign the method save in shape, complementing this field with the value we need.
- We leave it in shape, but we'll redesign it in the clean method (possibly to save). In this case, it will not be possible to depict the shape in the template as {form}, because this field will also be painted.
Now that this field is accessible in shape, it needs to be transferred there (request.user) and the form must be processed. For example:
class AddWatchesForm(forms.ModelForm):
def __init__(self, user_info, *args, **kwargs): self.user_info = user_info super().__init__(*args, **kwargs) def clean(self): """Используем, если не убираем из формы, а просто даем возможность его не вводить blank=True""" cleaned_data = super().clean() cleaned_data['account'] = self.user_info return cleaned_data def save(self, *args, **kwargs): """Переопределим метод save, если используем вариант, когда исключаем account из формы""" self.instance.account = self.user_info return super().save(*args, **kwargs) class Meta: ...
In order to get the user in shape, redesign the method
get_form_kwargs
Ours.CreateView
def get_form_kwargs(self):
"""Необходимо учитывать, что текущий пользователь у нас может быть не залогинен."""
kwargs = super().get_form_kwargs()
kwargs.update({
'user_info': self.request.user if self.request.user.is_authenticated else None,
})
return kwargs
I also recommend that we stick. https://www.python.org/dev/peps/pep-0008/ for classes