This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi everyone,
I would appreciate some guidance for an issue I am facing. Essentially, I am trying to create an API endpoint using ```generics.CreateAPIView```, where the current logged in user can create/add to their profile a new social media link. However, I am not sure how to go about this. Some readings from SO and Google tell me it has something to do with either the ```perform_create``` or ```create``` methods, but I do not know how to proceed. Ideally, I only want the user to only have to fill in the type of social media, and the social media URL, in order to add a new social media instance that is associated with the user profile for the current logged in user. Below is my first attempt at doing it, but it didn't work:
```
class CustomUser(AbstractUser):
id = models.UUIDField(default = uuid.uuid4, editable = False, primary_key = True)
country = CountryField(blank_label='(select country)')
updated_at = models.DateTimeField(auto_now = True, editable = False, null = True)
gender = models.CharField(max_length=50, choices=Gender.choices, default = Gender.OTHERS)
avatar = models.ImageField(upload_to = "avatar_pics", default = "avatar_pics/default.jpg", null = True)
class UserSocialMediaAccounts(models.Model):
id = models.UUIDField(default = uuid.uuid4, editable = False, primary_key = True)
user = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name = "social_media")
social_media = models.CharField(max_length=50, choices=SocialAccounts.choices)
social_media_url = models.URLField(null = False)
```
```
class CustomUserSocialMediaAddSerializer(serializers.ModelSerializer):
username = serializers.CharField(allow_blank = True)
class Meta:
model = UserSocialMediaAccounts
fields = ['username','social_media', 'social_media_url']
def create(self, validated_data):
username = validated_data.pop('username')
user_instance = CustomUser.objects.filter(username = username)
soc_instance = UserSocialMediaAccounts.objects.get_or_create(
user = user_instance, **validated_data)
```
```
class CustomUserDetailSocialMediaAddView(generics.CreateAPIView):
serializer_class = CustomUserSocialMediaAddSerializer
def perform_create(self,serializer):
serializer.save(username = self.request.user.username)
```
In this version, there are three writable fields for the views, being username, social_media and social_media_url. The username is optional and not supposed to be filled in, so that hopefully , when the social_media and social_media_url are filled in, the currently logged in user is associated with those fields. However, this set up throws an error upon a post request. Any help or guidance on the proper set up would be greatly appreciated.
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learndjango...