I made a web service with Django. It was completed, but I checked again where it was fluffy.
Example:
class Profile(models.Model):
~~ Field definition omitted ~~
@receiver(post_save, sender=User)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.get_or_create(user=kwargs['instance'])
def __str__(self):
return str(self.user)
@receiver @receiver is a signal, a function that calls the registered process when an event occurs. The post_save used in this example means that it will be executed immediately after adding or changing a record for the model (User in this case) specified by sender.
**kwargs You can specify any number of keyword arguments by defining arguments with **, such as ** kwargs. In the function, it is received as a dictionary whose argument name is key key and value is value. In this example, we take the sender as an argument and check if the instance was created with the if statement.
get_or_create If the object does not exist, it will be registered, and if it exists, it will not be registered.
def str(self) Process called when str or print is applied to the instance
Example:
class CommentCreateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
class Meta:
model = Comment
fields = ('text',)
*args It means whether to take a variable length argument as a tuple type or a dict type.
class Meta class Meta is a place to define something that is not a field definition.
Recommended Posts