You can give the user the coins in the view action that adds the journal that you posted here, like this:
...
obj.profile_pix = request.user.profile.image
obj.save()
# Gives the user 10 coins for creating a journal
profile = obj.user.profile
profile.coins += 10
profile.save()
return redirect('/journal/')
...
This will work, although I would rather use signals for this behaviour.
Using signals, you’d give the user 10 coins for creating the journal every time django saves a new instance, not only by the view action. If by any chance you write another piece of code that creates a journal, I’m guessing you’d still want to give the user 10 coins.
To do this, simply add to your journal model:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver([post_save], sender=JournalModel)
def gives_user_coins_after_create(sender, instance, created, **kwargs):
if created:
profile = instance.user.profile
profile.coins += 10
profile.save()
I have tried alot of codes yet none of them have worked so I decided to leave the views unrelated to my models.py
My question is:
I want to give users ten coins each time they create a post on my blog in django but it’s not giving them automatically
Here’s my views.py below
def journal_create_view(request):
form = JournalModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.Country = request.user.profile.your_country
obj.slug = obj.Your_Post_Title
obj.profile_pix = request.user.profile.image
obj.save()
return redirect('/journal/')
form = JournalModelForm()
template_name = 'add_post.html'
context = {'form': form}
return render(request, template_name, context)
Here is my models.py
user = models.OneToOneField(User,on_delete=models.CASCADE)
name = models.CharField(max_length=50, blank=False,null=False)
age = models.PositiveIntegerField(blank=False,null=False)
phone = models.IntegerField(blank=False,null=False)
your_country = models.CharField(max_length=50, blank=False)
image = models.ImageField(blank=False,null=False, upload_to="profile_image")
coins = models.IntegerField(default=100)
def __str__(self):
return self.user.username
And lastly, here’s my forms.py
class Meta():
model = Profile
fields = [
'coins'
]
I will be of gratitude if anyone help me out
Where in the code that you have given do you think you are adding coins to the person account ?