Reputation:
i have created a list in which it shows the name of all groups present when you click it redirect to another page with group id, when i create a post i need to specify which group it is, i am getting the id in url of page but i have no idea how to define group object with that url,
views
def create(request):
if request.method == "POST":
name = request.user
author = request.user
message = request.POST['message']
message = comments(user=author,message=message,name=name,group_id=2)
message.save()
return HttpResponse('')
instead of group_id=2 or hardcode it , can i automatically take the id from url of the page like we do in request.user
models
class group(models.Model):
group_name = models.CharField(max_length=100)
group_user = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return f'{self.id} group'
class comments(models.Model):
userId = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
group = models.ForeignKey(group,on_delete=models.CASCADE,null=True)
user = models.ForeignKey(User,on_delete=models.CASCADE)
message = models.TextField()
date = models.TimeField(auto_now_add=True)
def __str__(self):
return f'{self.user} comments'
i have been trying day and night and couldnt solve, all the genius programmers out there pls give me a solution
Upvotes: 0
Views: 1842
Reputation: 8411
urls.py
urlpatterns = [
path('create/<int:group_id>', views.create)
]
views.py
def create(request, group_id):
if request.method == "POST":
name = request.user
author = request.user
message = request.POST['message']
message = comments(user=author,message=message,name=name,group_id=group_id)
message.save()
return HttpResponse('')
As an example if you are running your app on localhost going to localhost:8000/create/1
will make group_id
= 1, going to localhost:8000/create/2
will make group_id
= 2 etc..
Upvotes: 1