Two models one form, or use generic CreateView

364 views
Skip to first unread message

The Sha

unread,
Jun 9, 2020, 8:36:37 AM6/9/20
to Django users
Hi 

I hava a problem in django, i have to models one is a CustomUser Model and the other is a Address model. 

The problem is that when i create a generic CreateView for the Address model and use a pk: url the address form wont get the instance of the users PK for adding a new address.

my models look like this, Even though i pass the PK in the URL the CreateView does not understand that i want to add a address to user with id: 42 in this example. How can i solve this problem?







The URL
 path('<int:CustomUser_id>/address', views.AddressCreateView.as_view(), name='Address-add'),


This is my view
class AddressCreateView(CreateView):
    model = Address
    template_name = 'members/address_form.html'
    success_url = reverse_lazy('MemberIndex')
    fields = ('CustomUser''address''zip_code''city''state','active')


The model
class CustomUser(AbstractBaseUserPermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    personal_Id = models.CharField(max_length=12blank=False)
    first_name = models.CharField(_('first name'), max_length=30blank=True)
    middle_name = models.CharField('middle name'max_length=30blank=True)
    last_name = models.CharField(_('last name'), max_length=30blank=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    avatar = models.ImageField(upload_to='images'blank=True)

    def __str__(self):
        return self.email

    def full_name(self):
        return '%s %s %s' % (self.first_name, self.middle_name, self.last_name)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []


    objects = CustomUserManager()

class Address(models.Model):
    CustomUser = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    address = models.CharField(max_length=60blank=False)
    zip_code = models.CharField(max_length=8blank=False)
    city = models.CharField(max_length=30blank=False)
    state = models.CharField(max_length=30blank=False)
    active = models.BooleanField(name='active'default=Trueeditable=True)
    address_reg_date = models.DateTimeField(default=timezone.now)
    class Meta:
        verbose_name_plural = "Address"
 
    def __str__(self):
         return self.address +', 'str(self.zip_code) + ', ' + self.city





Yamen Gamal Eldin

unread,
Jun 9, 2020, 10:01:16 AM6/9/20
to django...@googlegroups.com
There's many ways to solve it. My favorable approach will be to override the save method in the targeted form.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d0d3596f-6c0e-4928-8e57-7eb5476821d3o%40googlegroups.com.

The Sha

unread,
Jun 9, 2020, 10:24:28 AM6/9/20
to Django users
Ok intressant, i cant find any good exemplen. Thank you for the reply. Im new to django can you maybe be more specific with som examples or point me in the right direktion? thank you

Yamen Gamal Eldin

unread,
Jun 9, 2020, 4:19:09 PM6/9/20
to django...@googlegroups.com
It's pretty straight forward, just search about overload save function for update view, that will make u create a save function in your form, do the necessary actions on your instance, and voula

Le mar. 9 juin 2020 à 16:24, The Sha <mah...@gmail.com> a écrit :
Ok intressant, i cant find any good exemplen. Thank you for the reply. Im new to django can you maybe be more specific with som examples or point me in the right direktion? thank you

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

chaitanya orakala

unread,
Jun 9, 2020, 10:51:18 PM6/9/20
to django...@googlegroups.com
Hi Sha, 
I like your template CSS styling and formatting. 
Could you please post your index HTML and CSS style if you don't mind.
Thanks in Advance

Farai M

unread,
Jan 7, 2021, 8:41:33 AM1/7/21
to django...@googlegroups.com
Your code is fine but you will need to preload your form with the customer which you want this can be done in the get method of that create view.Read more about  use of DjangoModel form
Then override the get() method  and respond with the form populated with the customer details  .

Alternative use javascript to just take the  pk from your url 

Alternatively  pass it as a separate argument in your context  by again overriding the get() method.

Personally will do it right way using  model forms

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

_M_A_Y_A_N_K_

unread,
Jan 7, 2021, 8:58:11 AM1/7/21
to django...@googlegroups.com
You could use InlineFormSet, which is designed specially to handle such problems. Refer to the documentations here https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#inline-formsets 

Here you could provide the primary model (in your case it will be CUstomUser), and the secondary model (which will be Address).
Something similar to below.


from django.forms import inlineformset_factory
CustomerFormSet = inlineformset_factory(CustomUser, Address, fields=('email', 'firstname', ......  'address','zipcode',....))
  Hope this helps. 
 
Thanks & Regards,
---------------------
Mayank Tripathi
"Do what you can, with what you have, where you are -by Theodore Roosevelt"



Reply all
Reply to author
Forward
0 new messages