Skip to content

Instantly share code, notes, and snippets.

@rhenter
Last active January 15, 2020 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhenter/0b0a464f59d06de81256d626eedce358 to your computer and use it in GitHub Desktop.
Save rhenter/0b0a464f59d06de81256d626eedce358 to your computer and use it in GitHub Desktop.
Cadastro do usuario com endereço separado
class User(models.Model):
email = models.EmailField()
endereco = models.ForeignKey(Endereco)
class State(models.Model):
name = models.CharField()
class City(models.Model):
name = models.CharField()
class District(models.Model):
name = models.CharField()
class UserAddress(models.Model):
user = models.ForeignKey(User, related_name='addresses', on_delete=models.CASCADE)
number = models.CharField()
zip_code = models.CharField()
street = models.CharField()
complement = models.CharField()
district = models.ForeignKey(District, on_delete=models.DO_NOTHING)
city = models.ForeignKey(City, on_delete=models.DO_NOTHING)
state = = models.ForeignKey(State, on_delete=models.DO_NOTHING)
...
urlpatterns = [
path('address/<int:user_id>/$', views.CustomerAddressCreate.as_view(), name='add_address'),
]
...
class CustomerAddressCreateView(LoginRequiredMixin, CreateView):
template_name = "caminho_do_template/template.html"
model = UserAddress
fields = [
'state', 'city', 'district', 'address', 'number',
'complement', 'zip_code'
]
def form_valid(self, form):
user = User.objects.get(pk=self.kwargs['user_id'])
instance = form.save(commit=False)
instance.user = user
instance.save()
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy('customer_address:list', kwargs=self.kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment