Django Form has no attribute get - python

I have an form
class EntryForm(forms.ModelForm):
status = forms.ChoiceField(
choices=Maca.Status.choices,
widget=forms.RadioSelect(attrs={"class": "radio-ul"}),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Entry
fields = ["status", "commission"]
I try to update the object with class based view
def post(self, request, *args, **kwargs):
entries = UsersProductConfig.objects.get(pk=request.POST["object_id"])
maca = EntryForm(request.POST or None, instance=entries)
if maca.is_valid():
maca.save()
return maca
But I got the following error
'EntryForm' object has no attribute 'get'

Class based views are not my strength, and I don't have your full view, but one possibility is that you do not have a get() method to check for get requests. I'm thinking something like,
def get(self, request):
maca = EntryForm()
return maca
Source: Django - 'ContactForm' object has no attribute 'get'

Related

how to dynamically set the choices of a choice field in django DRF serializer through __init__ or __new__ method?

I am trying to dynamically set the choices of a choice field in django serializer class
I want to pass the choices (dynamically) to it and it set it for me
The simplified version of the project is this
# urls
urlpatterns = [
path("cat", CatView.as_view(), name="cat")
]
I have tried different things and they don't work. I am sharing one of them here
I even had to use the private methods (which I would prefer not to) of the field but still not successful
# serializers
class CatSerializer(serializers.Serializer):
name = serializers.ChoiceField(choices=[])
def __new__(cls, *args, **kwargs):
name_choices = kwargs["names"]
f = CatSerializer._declared_fields["name"]
f._set_choices(name_choices)
f.__dict__["_kwargs"]["choices"] = name_choices
obj = super().__new__(cls)
return obj
def __init__(self, *args, **kwargs):
kwargs.pop("names")
super().__init__(self, *args, **kwargs)
# views
class CatView(APIView):
def __init__(self, *arg, **kwargs):
super().__init__(*arg, **kwargs)
self.names = ['a', 'b', 'c']
def get_serializer(self, *args, **kwargs):
serializer_class = CatSerializer
return serializer_class(
*args, **kwargs,
names=self.names
)
def post(self, request):
request_body = request.body
serializer = self.get_serializer(
data=json.loads(request_body),
)
is_data_valid = serializer.is_valid()
if is_data_valid:
serialized_data = serializer.data
return Response({"message": "success", "serialized-data": serialized_data})
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I now see this error:
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `CatSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `CatSerializer` instance.
Original exception text was: 'CatSerializer' object has no attribute 'name'.
it fails in views when it tries to get the data here serialized_data = serializer.data
this is another question with some variations that I have not yet figured out to solve and not received a response on.
problem initializing django serializer with extra vars to be used in choice field

Django create form field with a model of the current user

I have a simple app, where a user has multiple businesses, and each business has multiple products, what I´m trying to do is a make product creatView, where i can select a business from the ones owned by the current user. I tryed editing the init() method of the ModelForm like this:
class Producto_Form(forms.ModelForm):
class Meta:
model = Producto_Model
fields = ("Nombre_Producto","Negocio","Descripcion_Producto",'Precio_Producto','Tags',"Foto")
def __init__(self, *args, **kwargs):
super(Producto_Form, self).__init__(*args, **kwargs)
self.fields['Negocio'].queryset = Negocio_Model.objects.all().filter(Administrador_id=kwargs['user'].id)
and then i changed the get_form_kwargs from the create product view like this:
class crear_producto(LoginRequiredMixin, CreateView):
template_name = "tienda/crear_producto.html"
form_class= Producto_Form
success_url = reverse_lazy('tienda_app:crear_producto')
login_url = reverse_lazy('register_app:logIn')
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs(*args, **kwargs)
kwargs['user'] = self.request.user
return kwargs
I was following this question but I keep getting the error __init__() got an unexpected keyword argument 'user'
So everything is almost fine but you must pass the user variable to the form init as the kwargs, also, on the queryset dont call it like kwargs['user'] and just call user, something like this:
def __init__(self, user, *args, **kwargs):
super(Producto_Form, self).__init__(*args, **kwargs)
self.fields['Negocio'].queryset = Negocio_Model.objects.all().filter(Administrador_id=user.id)
also I changed the super() constructor on the get_form_kwargslike this:
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(crear_producto, self).get_form_kwargs(*args, **kwargs)
kwargs['user'] = self.request.user
return kwargs

Django-Filter FilterSet Show Only User Generated Objects

I'm using a django-filter form and it's filtering all objects for 'associated_portfolios' how can I make it so it only shows the user the objects they created?
Error message:
'StatsFilter' object has no attribute 'fields'
Filters.py
class StatsFilter(django_filters.FilterSet):
associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios)
class Meta:
model = Trade
fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']
def __init__(self, request, *args, **kwargs):
super(StatsFilter, self).__init__(*args, **kwargs)
self.fields['associated_portfolios'].queryset = Trade.objects.filter(user=request.user)]
views.py
class StatsView(LoginRequiredMixin, FilterView):
model = Trade
template_name = 'dashboard/stats.html'
filterset_class = StatsFilter
def get_context_data(self, **kwargs):
filter = StatsFilter(self.request.GET, queryset=self.get_queryset())
context = super().get_context_data(**kwargs)
context['filter'] = filter
context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin')
context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value']
return context
Ah, now I remember: set the queryset argument of ModelMultipleChoiceFilter to a callable that accepts request as it's only argument:
def portfolio_filtered_queryset(request):
return Trade.objects.filter(user=request.user)
class StatsFilter(django_filters.FilterSet):
associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=porfolio_filtered_queryset)
The view:
class StatsView(LoginRequiredMixin, FilterView):
model = Trade
template_name = 'dashboard/stats.html'
filterset_class = StatsFilter
def get_context_data(self, **kwargs):
# Must pass in request!
filter = StatsFilter(self.request.GET, queryset=self.get_queryset(), request=self.request)
context = super().get_context_data(**kwargs)
context['filter'] = filter
context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin')
context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value']
return context
In django_filters.filters.QuerySetRequestMixin.get_request() the request instance is obtained from the parent. But I see no logic in django_filters.filterset.BaseFilterSet or concretes that tries to obtain the request through other means. So you must pass the request to the StatsFilter if you wish to make use of QuerySetRequestMixin.

Django objects error in view, why I got this error? It looks like my model does not exist

This is my view code:
class Planificare_concedii(AllView):
template_name = "pep/planificare_concedii.html"
def get_context_data(self, *args, **kwargs):
magazinu = self.request.GET.get('magazinul')
queryset = Planificare_concedii.objects.filter(magazin=magazinu)
context = context = super(Planificare_concedii, self).get_context_data(
*args, **kwargs)
return context
This is the error that I got in view page:
AttributeError at /planificare_concedii/
type object 'Planificare_concedii' has no attribute 'objects'

Success message not displayed

Don't see any SuccessMessage. Anyone can tell me why I don't get any success message once I successfully created the database entry?
class TicketCreate(AdminPermissionRequiredMixin, SuccessMessageMixin, FormValidationMixin, BaseTicketView, TemplateView):
template_name = 'tickets/admin/create.html'
success_message = _("Ticket has been successfully created.")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['ticket_form'] = self.ticket_form
context['tax_form'] = self.tax_form
return context
#cached_property
def ticket_form(self):
return TicketForm(data=self.request.POST or None, event=self.request.event)
#cached_property
def tax_form(self):
return TicketTaxForm(prefix='tax', data=self.request.POST or None)
#transaction.atomic
def post(self, request, *args, **kwargs):
if self.ticket_form.is_valid() and self.tax_form.is_valid():
tax_instance = self.tax_form.save(commit=False)
tax_choice = self.tax_form.cleaned_data.get('tax_choice')
new_tax = (tax_choice == TicketTaxChoice.NEW_TAX and
tax_instance.name and tax_instance.percentage)
# save the tax instance
if new_tax:
tax_instance.event = self.request.event
tax_instance.save()
# save the ticket instance
ticket_instance = self.ticket_form.save(commit=False)
ticket_instance.event = self.request.event
if new_tax:
ticket_instance.tax = tax_instance
self.ticket_form.save()
return redirect(
'tickets:admin:detail',
self.request.organizer.slug,
self.request.event.slug,
ticket_instance.pk
)
return super().get(request, *args, **kwargs)
From the official docs:
Adds a success message attribute to FormView based classes
I can't see your other classes, but from what I see your class is based on TemplateView, which is not derived from FormView.
Looking the source you can see that message is shown when form_valid is called, so your class should at least specify form_class or model field. But you are calling is_valid() manually, so form_valid is not called and message is not shown.

Categories