Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - how to implement add another to django model form

I'm trying to implement + button for foreign key select field , if the foreign key doesn't exist instead of going to another page just pop up a form page to add new entry for the foreign key , I've implemented but its full size and dont go to the previous page and shows only a blank page when i submit the form : this is what i tried

my models.py

class MainGroup(models.Model):
    admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE)
    main_type = models.CharField(max_length=40,unique=True)

    def __str__(self):
        return self.main_type

    class Meta:
        db_table = 'maingroup'

class PartGroups(models.Model):
    admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE)
    main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes')
    part_group = models.CharField(max_length=30)

    def __str__(self):
        return self.part_group

and this is my forms.py

from django.contrib.admin import site as admin_site,widgets

class MainGroupForm(forms.ModelForm):
    class Meta:
        model = MainGroup
        fields = ['main_type']
        error_messages = {
            'main_type':{
                'required':_('some message'),
                'unique':_('some message'),

            }
        }
        widgets = {

            'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('placeholder')})
        }


class PartGroupForm(forms.ModelForm):
    main_type = forms.ModelChoiceField(queryset=MainGroup.objects.all(),empty_label=_('label'))

    def __init__(self, *args, **kwargs):
        super(PartGroupForm, self).__init__(*args, **kwargs)
        self.fields['main_type'].widget = (
            widgets.RelatedFieldWidgetWrapper(
                self.fields['main_type'].widget,
                self.instance._meta.get_field('main_type').remote_field,
                admin_site,
            )
        )

    class Meta:
        model = PartGroups
        fields = ['admin','main_type','part_group']

        error_messages = {
             'main_type':{
                 'required':_('some message'),
             },
             'part_group':{
                 'required':_('some message'),
             }

            }
         widgets = {
            'part_group':forms.TextInput(attrs={'placeholder':_('group')})
         }

and this is my views.py

@login_required
def create_productgroup(request):
    form = ProductGroupForm()
    if request.is_ajax() and request.method == 'POST':
        form = ProductGroupForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.admin = request.user
            obj.save()     
          
            return JsonResponse({'success':'success','admin':data})
        else:
            return 
 JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'})
    context = {
        'form':form
     }
     return render(request,'products/create_productgroup.html',context)

all other functionality works fine , but when i try to implement add another (plus button) it wont work , and only opens in the same window , and after submitting the form it shows only a blank page , even it doesnt open the pop up similar to django's admin !? i also tried this instead of ModelForm widget , i just add this in my template

<a href="/admin/products/maingroup/add/" class="add-another" id="add_id_{{form.main_type.html_name}}" onclick="return showAddAnotherPopup(this);"> <img src="/media/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/></a>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...