Linked Questions

Popular Questions

So I have a problem about how to save model instance with foreign key relation,

class Connect(models.Model):
    username = models.CharField(max_length=255)
    password = models.CharField(max_length=255,null=True, blank=True)
    conft = models.TextField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return unicode(self.username)

class Ip(models.Model):
    class Meta:
        db_table = 'autonet_ip'

    connect_id = models.ForeignKey(Connect, on_delete=models.CASCADE)
    ipaddr = models.CharField(max_length=255)

    def __str__ (self):
        return self.ipaddr

class NacmForm(ModelForm):
    password = forms.CharField(widget=forms.PasswordInput,required = False)
    class Meta:
        model = Connect
        fields = ['username', 'password','conft']

    labels = {'conft':_('Config'),}

class IpForm(ModelForm):

    class Meta:
        model = Ip
        fields = ['ipaddr']
    labels = {'ipaddr':_('IP address'),}

IpFormset = formset_factory(IpForm,  extra=1)

def konfig(request):
    ip_list = []
    status = ''
    value_bak = 1

    if request.method == 'POST':
        formm = NacmForm(request.POST or None)
        ipform = IpFormset(request.POST)
        upform = UploadForm(request.POST,request.FILES)
        userValue = formm['username'].value()
        passValue = formm['password'].value()
        confValue = formm['conft'].value()
        usernamef = get_object_or_404(Connect, pk=id)
        if ipform.is_valid():
            for form in ipform:
                ipaddr = form.cleaned_data.get('ipaddr')

                //.... some code ...//

                simpanIp =
                simpanIp.connect_id = usernamef


        return HttpResponseRedirect('/konfig')
        formm = NacmForm()
        ipform = IpFormset()
        return render(request, 'konfig.html', {'form': formm, 'logins': Connect.objects.all(), 'ipform': ipform, 'status': status })

Then, when I input all data and click submit to collect form data and on, I've got an error: id() takes exactly one argument (0 given).

I just want to know how to save the instance of Connect model to database with foreign key, thanks before

so i edit my like this

class Connect(models.Model):
        def get_usernameinf(self):
            return ', '.join(self.usernameinf.all().values_list('username', flat=True))

and like this

if request.method == 'POST':
.....some code.....

if ipform.is_valid() and formm.is_valid():
    simpanForm =

    for form in ipform:
    simpanIp =
    ...... some code ..
        simpanIp.connect_id = simpanForm

and its work, now the result is my "connect_id" got value from "Connect id"

Related Questions