title: Create files in Django with user input
body: <p>I am building a Django messaging app where each chat room has its own template, model and view. What I'm struggling with is figuring out a way for a user to create private chat rooms with user input. I wanted the user to specify details in a template form and when they click submit, the files will be generated to create the chat room. Or is there a better way to do this? Any suggestions will be appreciated.</p>
  
  <p>oh and I am using Django 2.1.2 with Python 3.6.5. Thanks</p>
  
  <p>edit: I add some code below</p>
  
  <p>models.py:</p>
  
  <pre><code>class Chat(models.Model):
  created = models.DateTimeField(auto_now_add=True)
  #timeNow = models.DateTimeField()
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  message = models.TextField()
  file_upload = models.FileField()
  class Meta:
      verbose_name_plural = "general Chat"
  
  def __unicode__(self):
      return self.message
  </code></pre>
  
  <p>views.py:</p>
  
  <pre><code>def GeneralChat(request):
  c = Chat.objects.all()
  documents = Document.objects.all() #file upload
  return render(request, "channels/generalChat.html", {'generalChat': 'active', 'chat': c, 'documents': documents})
  
  def Post(request):
  if request.method == "POST":
      msg = request.POST.get('msgbox', None)
      time = datetime.now()
      c = Chat(user=request.user, message=msg, created=time)
  
      c = Chat(user=request.user, message=msg)
  
      if msg != '':            
          c.save()
      return JsonResponse({ 'msg': msg, 'user': c.user.username})
  else:
      return HttpResponse('Request must be POST.')
  
  def Uploads(request):
  if request.method == 'POST':
      form = DocumentForm(request.POST, request.FILES)
      if form.is_valid():
          form.save()
          return redirect('/generalChat')
  else:
      form = DocumentForm()
  return render(request, 'channels/uploads.html', {
      'form': form
  })
  </code></pre>
  
  <p>generalChat.html:</p>
  
  <pre><code>{% extends "base.html" %}
  {% load staticfiles %}
  {% block content %}
  &lt;div&gt;&lt;title&gt;General Chat&lt;/title&gt;&lt;/div&gt;
  
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"&gt;&lt;/script&gt;
  
  &lt;div id="chat-body" class="panel panel-default"&gt;
      &lt;div id="panel-heading" class="panel-heading"&gt;&lt;h4&gt;General Chat&lt;/h4&gt;&lt;/div&gt;
      &lt;div id="msg-list-div" class="panel-body"&gt;
          &lt;ul id="msg-list" class="list-group"&gt;
  
              {% for obj in chat %}
                  {%if obj.user == request.user %}
                      &lt;li class="text-right list-group-item"&gt;
                      &lt;font color="#3498DB"&gt;{{ obj.user }}&lt;/font&gt;&lt;br&gt;&lt;font color="#000000"&gt;&lt;/font&gt;{{ obj.message }}
                      &lt;br&gt;&lt;font size="1" &gt;{{ obj.created }}&lt;/font&gt;&lt;/li&gt;
                      &lt;br&gt;
                  {% else %}
                      &lt;li class="text-left list-group-item"&gt;
                      &lt;font color="#1ABC9C"&gt;{{ obj.user }}&lt;/font&gt;&lt;br&gt;&lt;font color="#000000"&gt;&lt;/font&gt;{{ obj.message }}
                      &lt;br&gt;&lt;font size="1" &gt;{{ obj.created }}&lt;/font&gt;&lt;/li&gt;&lt;/li&gt;
                      &lt;br&gt;
                  {%endif%}   
              {% empty %}
                  &lt;li class="text-right list-group-item"&gt;No messages yet.&lt;/li&gt;
              {% endfor %}
              &lt;h4&gt;Files&lt;/h4&gt;
              {% for obj in documents %}
                  {%if obj.userUpload == request.user %}
                      &lt;li class="text-right list-group-item"&gt;
                      &lt;font color="#3498DB"&gt;{{ obj.userUpload }}&lt;/font&gt;&lt;br&gt;
                      &lt;a href="{{ obj.document.url }}"&gt;&lt;font color="#000000"&gt;{{ obj.document.name }}&lt;/a&gt;&lt;/font&gt;
                      &lt;br&gt;&lt;small&gt;{{ obj.created }}&lt;/small&gt;&lt;/li&gt;&lt;br&gt;
                  {% else %}
                      &lt;li class="text-left list-group-item"&gt;
                      &lt;font color="#1ABC9C"&gt;{{ obj.userUpload }}&lt;/font&gt;&lt;br&gt;
                      &lt;a href="{{ obj.document.url }}"&gt;&lt;font color="#000000"&gt;{{ obj.document.name }}&lt;/a&gt;&lt;/font&gt;
                      &lt;br&gt;&lt;small&gt;{{ obj.created }}&lt;/small&gt;&lt;/li&gt;&lt;br&gt;
                  {% endif %}
              {% endfor %}
  
  
              &lt;script&gt;
                  var chatlist = document.getElementById('msg-list-div');
                  //chatlist.scrollTop = chatlist.scrollHeight;
              &lt;/script&gt;
          &lt;/ul&gt;
                  &lt;div&gt;&lt;a class="btn btn-warning" value="Upload File" href="{% url 'uploads' %}" &gt;Upload File&lt;/a&gt;&lt;/div&gt;
  
  
      &lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="form-input" style="height: 100px;"&gt;
  
      &lt;form id="chat-form" method="post" action="/post/"&gt;{% csrf_token %}
          &lt;div id="chat-bottom" class="input-group"&gt;
              &lt;input type="text" id="chat-msg" name="chat-msg" class="form-control"/&gt;
              &lt;span class="input-group-btn"&gt;
                  &lt;input class="btn btn-default" id="send" type="submit" value="Send"/&gt;
              &lt;/span&gt;
          &lt;/div&gt;
  
      &lt;/form&gt;
  
  &lt;/div&gt;
  
  &lt;script src="{% static 'chat.js' %}"&gt;&lt;/script&gt;
  &lt;script src="{% static 'jquery.cookie.js' %}"&gt;&lt;/script&gt;
  {% endblock %}
  </code></pre>
  
  <p>chat.js</p>
  
  <pre><code>$('#chat-form').on('submit', function(event){
  event.preventDefault();
  
  $.ajax({
      url : '/post/',
      type : 'POST',
      data : {msgbox: $('#chat-msg').val() },
  
      success : function(json){
          console.log(json);
          $('#chat-msg').val('');
          $('#msg-list').append('&lt;li class="text-right list-group-item"&gt;' + json.msg + '&lt;/li&gt;');
          var chatlist = document.getElementById('msg-list-div');
          //chatlist.scrollTop = chatlist.scrollHeight;
      }
  });
  });
  
  function getMessages(){
  if (!scrolling){
      $.get('/messages/', function(messages){
          console.log(messages);
          $('#msg-list').html(messages);
          var chatlist = document.getElementById('msg-list-div');
          //chatlist.scrollTop = chatlist.scrollHeight;
      });
  }
  scrolling = false;
  }
  
  var scrolling = false;
  $(function(){
  /*$('#msg-list-div').on('scroll', function(){
      scrolling = true;
  });*/
  refreshTimer = setInterval(getMessages, 5000); //0.5 seconds
  });
  
  $(document).ready(function(){
  $('#send').attr('disabled','disabled');
  $('#chat-msg').keyup(function(){
      if($(this).val() != ''){
          $('#send').removeAttr('disabled');
      }
      else{
          $('#send').attr('disabled', 'disabled');
      }
  });
  });
  
  //using JQuery
  function getCookie(name){
  var cookieValue = null;
  if (document.cookie &amp;&amp; document.cookie != ''){
      var cookies = document.cookie.split(';');
      for (var i=0; i &lt; cookies.length; i++){
          var cookie = jQuery.trim(cookies[i]);
  
          if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
          }
      }
  }
  return cookieValue;
  }
  
  var csrftoken = getCookie('csrftoken');
  
  function csrfSafeMethod(method){
  // these http methodes don't need CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
  beforeSend: function(xhr, settings){
      if(!csrfSafeMethod(settings.type) &amp;&amp; !this.crossDomain){
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
      }
  }
  });
  </code></pre>