Python Django - Customizing add user save method - python

I am pretty new to django framework . I am working on add user form in admin login .I need to send user details to third party API , On success from API call ,have to save in application database . Could you please guide me how to customize user save method to achieve this.

I suggest you override clean() method in UserCreationForm. This way, you can send user details to third party API and validate it.
class CustomUserCreationForm(UserCreationForm):
class Meta:
model=User
def clean(self):
# Send API
class UserAdmin(UserAdmin):
add_form = CustomUserCreationForm
admin.site.register(User, UserAdmin)
clean() method
custom user creation form

Related

How to add check on admin side actions in django?

Here i'm using django latest verion which is 3.1.4 and I just want to add condition in django admin side. I just wanted to return some text in terminal if i update my model from admin panel.
In my case
user submit kyc form
admin person approved that form
user will get notification on approval. (Right now I just want to print some message when admin update his kyc by updating his kyc form by updated approved boolean field.
In short Just wanted to show message when admin updates any model in django admin side.
admin.py
class KycAdmin(admin.ModelAdmin):
list_display = ['__str__','owner']
class Meta:
model = KycModel
def post(self,request):
response = "i'm updated"
print(vu)
return vu
admin.site.register(KycModel,KycAdmin)
If more detail is require then you can just tell me in a comments.
Have you tried overriding the save method in models.
Whenever you save an object, it will hit the save method. You can print whatever you want to over there
class SomeModel(models.Model):
... some fields for eg. name
def save(self, *args, **kwargs):
print(self.name)
super().save(*args, **kwargs)
This is the simplest way to achieve it. You can also override save in admin.

Django CustomUser created in Admin, User notification by email

Hobby developer, new with Python and Django.
Working on project which will include creating new users with a CustomUser(AbstractUser) Model via the Admin backend. On [Save] I want to auto-send email to the new user email [To:] and share the Username and Password provided when the new user was created by admin.
I'm using Python3.7 Django 2.2 on MacOS. Development being done in virtual env [Conda]. Email server setup in the development env as Backend File type. I have done 'extensive' search on forums [incl this one] ... tried the example code I could find. I have been able to send [then receive in Backend File] email on Form save but do not know how one would include the form variables in the email.
VIEWS.py
from django.shortcuts import render
from django.core.mail import send_mail
def notification_mail_send(request):
form = CustomUserCreationForm(request.POST)
if form.is_valid():
# SET UP MAIL CONTENT AND SEND MAIL
pass
FORMS.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'owner_fullname', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm):
model = CustomUser
fields = ('username', 'owner_fullname', 'email')
You should be able to access to form data with form.cleaned_data[field_name], where field_name would e.g. be "username".
If you are using a Django template to build your email content, pass the form object as context and use e.g. {{ form.cleaned_data.username }}
When using the django admin you don’t need to write your custom views and forms.
If you want to change the behavior of the admin you often need to overide the ModelAdmin class.
In your case I'd suggest to override save_model()
Thank to my fellow developers for assistance. I did deep dive into Rupin's suggestion and applied successfully using 'signals' : http://docs.djangoproject.com/en/2.2/topics/signals. Solved by merely adding 'if created': in the post_save_receiver(sender, instance, created, **kwargs): function in models.py.

How to update a user profile field using rest API

I am new to django and very confused. I am using django as the backend API for my angular application.
I want to add few more details to the User model so I added the following to my models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
company_name = models.CharField(max_length=100)
I am using an application to add rest authentication support: https://github.com/Tivix/django-rest-auth
Using this application I can edit a users profile with this URL doing a POST request: http://localhost:8080/rest-auth/user/
Question
How can I update the custom field company_name? while editing a users profile?
What I've tried
I tried to override the UserDetailsSerializer that the application provides but it isn't having any effect.
This is what I tried adding to my applications serializers.py
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserProfile
fields = ('company_name',)
class UserDetailsSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer(required=True)
class Meta:
model = models.User
fields = ('id', 'username', 'first_name', 'last_name', 'profile')
If you are using django rest framework, then you basically want to have an update method on your view class for UserProfile that takes in the user id as a request param. Then in that method you want to use the ORM to get a model object for the given userprofile id, set the property that was also passed as a param, and save the changed model object. Then generate a success response and return it.
You can read more about how to do this here: http://www.django-rest-framework.org/api-guide/views/

not saving custom fields to django-allauth - no luck from previous posts

I am trying to create custom fields for users to enter on signup with django-allauth. I have referred to several posts about this, but I am not able to get my custom form to save to my database. I do get a combined form on my signup.html page with username, password1 and 2, email and my extra fields of city and school, but I am not able to save the extra fields to the database. I have run syncdb and can see my User Profile table in the admin area.
This advice is the closest I have come to the answer but I do not understand how to implement it: "You can't use UserProfileForm to the allauth.SIGNUP_FORM_CLASS. You need to extend it from SignUpForm and write a save method which will accept the newly created user as the only parameter," from this post:
Custom registration form for use with django-allauth
I have also attempted to integrate advice on this form these posts:
Django Allauth not saving custom form
How to customize user profile when using django-allauth
This is my code:
Models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
# A required line - links a UserProfile to User.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
school = models.CharField(max_length=128)
city = models.CharField(max_length=128)
def __unicode__(self):
return self.user.username
Forms.py
from django import forms
from django.contrib.auth.models import User
from myapp.models import UserProfile
from django.forms.widgets import HiddenInput
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('city', 'school')
def signup(self, request, user):
user=User.objects.get(email=request.email)
city=request.POST.get('city','')
school=request.POST.get('school','')
userprofile_obj = UserProfile(user=user,city=city,school=school)
userprofile_obj.save()
Settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.UserProfileForm'
My template is the basic Signup.html from the django-allauth templates and I do not have a view made for this, although I attempted to make one from the tangowithdjango user authentication section register view, and this gave similar behavior (not saving to the database).
Thanks,
Kelly
Not sure if this is still an active question/issue for the original poster: if so, and for anyone else who comes across this, a few things to correct to at least move in the right direction:
I don't see an __init__() method that calls the superclass? E.g.:
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
use the user parameter to the signup method. It should be populated; don't reload it.
Ensure the two objects are linking correctly (I didn't use Django to build my profile table so YMMV but I set user.profile = Profile(...); then execute user.profile.save() at the end of my signup() method.
get the values to place into the profile from the form cleaned_data (e.g. self.cleaned_data['city'] not the POST.
Then start debugging: is your signup() method firing? What does it get? What happens when you execute the profile.save() method?

Writing user.get_profile() custom function which should create auth profile if there is not any

I am trying to write custom get_profile() function which should create user profile for users who are registered thru admin or any other way where post_save was not called.
How can I start this?
I guess that you have a model to handle user profile like this:
class UserProfile(models.Model):
"""Contains user profile fields not provided by User model"""
user = models.OneToOneField(User)
# Defined User profile fields like picture, phone, etc
So adding following line (maybe in your models.py after UserProfile model):
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
Allows access to the profile of a user (i.e. in templates: {% user.profile.phone %}) by creating it if not exists.
This is the way I solved in my site a problem like you describe.
Hope this helps
I am a bit confused. Are you trying to let users create account and sign in? Then use django-registration which is easy and works out of the box.

Categories