Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get data from forms?
#1
How can I get data from a form (ProductCreateForm)?

If I write form = self.get_form(), then I just get a form template, where some data is selected, and some are not (select especially).

If I write form = ProductCreateForm(request.POST), then I get an error saying that the request was not found. Perhaps this is due to the fact that I set the request in get_context_data() and work with them in the __init__ method in the forms.py.

I process the data in the clean method in the forms.py.

class ProductsCreate(CreateView):
    model = Product
    form_class = ProductCreateForm
    http_method_names = ['get', 'post']
​
    def get_context_data(self, *args, **kwargs):
        ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs)
        ctx['special_form'] = SpeciallyPriceForm()
        
        return ctx
​
    def get(self, request, *args, **kwargs):
        self.object = None
        
        if kwargs.get('slug'):
            category = Category.objects.filter(slug=kwargs.get('slug')).first()
            self.initial.update({'category': category})
        
        return self.render_to_response(self.get_context_data())
        
    def post(self, request, *args, **kwargs):
        self.object = None
        form = self.get_form()                     #Тут что-то не то, видимо...
        special_form = SpeciallyPriceForm(self.request.POST)
​
        if form.is_valid() and special_form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

class ProductCreateForm(forms.ModelForm):
    #....
​
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        #...
        user = self.request.user
        provider = Provider.objects.filter(user=user.id).last()
        self.fields['category'] = ModelMultipleChoiceField(queryset=provider.category.all())
        #...
     
   def clean(self):
        cleaned_data = super(ProductCreateForm, self).clean()
        cd_category = cleaned_data.get('category')
        #...
​
​
class SpeciallyPriceForm(forms.ModelForm):
    class Meta:
        model = SpeciallyPrice
        fields = ['adittional_specially_price', 'adittional_specially_number']
Reply
#2
There are 2 forms on one page.

There are 2 models: 1. Product. 2. SpeciallyPrice. SpeciallyPrice is linked via FK to Product. At the same time, SpeciallyPrice is Inline model in Product.

The fields of the SpecialPriceForm are automatically created using JS. That is, them may be the n-th number. It is necessary to create a record for each created field. In principle, I guess how to do it - use the cycle to drive the values obtained. But the problem is that for some reason None comes from the form. And really come the last two empty (None's) created with JS fields.
How to solve this issue? Maybe Ajax should be connected and it somehow process the request? Or is there a more Django's option? Please help.

I added to views
    def get_initial(self):
        initial = super(ProductsCreate, self).get_initial()
        initial['request'] = self.request

        return initial
Changed post and form_valid functions
    def post(self, request, *args, **kwargs):
        self.object = None
        form = ProductCreateForm(request.POST, request.FILES, initial={'request': request})
        special_form = SpeciallyPriceForm(request.POST)
        print(special_form)           #Template of form, wit two last empty fields. Code at bottom.
        if form.is_valid() and special_form.is_valid():
            return self.form_valid(form, special_form)
        else:
            return self.form_invalid(form, special_form)

    def form_valid(self, form, special_form):
        product = form.save(commit=False)
        product.user = self.request.user
        product.save()

        special = special_form.save(commit=False)
        #Here I think, depending on the number of list items, to cycle through it and create the corresponding number of `special` records associated with this` product`. Is the logic correct?
        special.product = product
        special.save()

        for spec_price in special_form.cleaned_data.get('adittional_specially_price'):
            print(spec_price)
            special.adittional_specially_price = spec_price
        for spec_numb in special_form.cleaned_data.get('adittional_specially_number'):
            print(spec_numb)
            special.adittional_specially_number = spec_numb
class SpeciallyPriceForm(forms.ModelForm): 
    class Meta: 
        model = SpeciallyPrice 
        fields = ['adittional_specially_price', 'adittional_specially_number']

    def clean(self):
        cleaned_data = super(SpeciallyPriceForm, self).clean()
        cd_adittional_specially_price = cleaned_data.get('adittional_specially_price')
        print(cd_adittional_specially_price)   #None
        cd_adittional_specially_number = cleaned_data.get('adittional_specially_number')
        print(cd_adittional_specially_number)  #None
<html><body>
Special price from {{ special_form.adittional_specially_price }} kg {{ special_form.adittional_specially_number }} usd

    <script>
        (function(){
            var copy = document.querySelector('.field.inline.specially').cloneNode(true);
            document.querySelector('html').addEventListener('input', function(e){
                if(e.target.classList.contains('event') && e.target.tagName == 'INPUT'){
                    var error = 0;
                    for(var evt of document.querySelectorAll('.field.inline.specially input.event')){
                        evt.value = evt.value.replace(/[^\d]/,'');
                        if(!evt.value || +evt.value < 1) error++;
                    }
                    if(!error){
                        var last = document.querySelectorAll('.field.inline.specially');
                        last[last.length-1].insertAdjacentHTML('afterEnd', copy.outerHTML);
                    }
                }
            });
        })();
    </script>
</body></html>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I am trying to space the registration forms using css. But it is not working. tree 0 1,380 Apr-11-2021, 03:31 AM
Last Post: tree
  How to fill text fields web forms Martinelli 1 2,016 Sep-25-2019, 11:14 PM
Last Post: Martinelli
  Forms, python, passlib and other questions marienbad 1 2,405 Feb-05-2019, 04:23 AM
Last Post: snippsat
  Forms to render "Guide in steps" or not? stablepeak 1 2,227 Nov-29-2018, 10:05 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020