I tried to create a simple Django Chat App. There is no login system.
Whenever a user(e.g. John) tries to create a message, it stores under 'messageroom'
I tried to pass the username 'John' value in the URL but somehow it is not creating a message as expected.
Here is my code Urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('checkview',views.checkview,name='checkview'),
path('messageroom/<str:room_name>/<str:username>',views.messageroom,name='messageroom'),
]
Models.py
class Room(models.Model):
roomname = models.CharField(max_length=1000)
class Message(models.Model):
messagetext = models.CharField(max_length=10000)
username = models.CharField(max_length=1000)
datetime = models.DateTimeField(default=datetime.now,blank=True)
messageroom = models.CharField(max_length=1000)
Views.py
def home(request):
return render(request,'home.html',{})
def checkview(request):
room_name=request.POST.get('room_name')
username = request.POST.get('username')
Roomexists = Room.objects.filter(roomname=room_name)
if Roomexists.exists():
return redirect('messageroom/' room_name '/' username)
else:
newroom = Room(roomname=room_name)
newroom.save()
return redirect('messageroom/' room_name '/' username)
def messageroom(request,room_name,username):
if request.method == "POST":
messagetext = request.POST.get('message')
newmessage = Message(messagetext=messagetext,messageroom=room_name,username=username)
newmessage.save()
listmessages = Message.objects.filter(messageroom=room_name)
return render(request, 'room.html', {'listmessages':listmessages,'room_name':room_name,'username':username})
Room.html
<form id="post-form2" method="POST" action="messageroom">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
I want to create messages under the user which should be there on the URL.
CodePudding user response:
you should pass values in urls in html form like this....
<form id="post-form2" method="POST" action="{% url 'messageroom' room_name username %}">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>
-------------------------- OR ------------------
<form id="post-form2" method="POST" action="/messageroom/room_name/username/">
{% csrf_token %}
<input type="text" name="message" id="message" width="100px" />
<input type="submit" value="Send">
</form>