def discussion_add(request):
    error = ""

    try:
        community = CommunityCommunities.objects.get(id=request.POST.get("community_id"))
        discussion = CommunityDiscussions()
        discussion.community = community
        discussion.user = request.user
        discussion.post = request.POST.get("post")
        discussion.subject = request.POST.get("subject")
        discussion.save()
        if request.FILES.get("attachment") is not None and request.FILES.get("attachment").size:
            try:
                attachment = FileUploads()
                attachment.type = "discussion_attachment"
                attachment.sub_type = discussion.id
                attachment.upload = request.FILES.get("attachment")
                attachment.save()
            except:
                attachment = None
        else:
            attachment = None
        if attachment:
            discussion.attachment = attachment
            discussion.save()
        success = True
        discussion_id = discussion.id
    except Exception as e:
        error = e
        success = False
        discussion_id = None
    return HttpResponse(
        json.dumps({"Success": success, "DiscussionID": discussion_id, "Error": "Error: {0}".format(error)}),
        content_type="application/json",
    )
def discussion_reply(request, discussion_id):
    discussion = CommunityDiscussions.objects.get(id=discussion_id)
    reply = CommunityDiscussionReplies()
    reply.discussion = discussion
    reply.user = request.user
    reply.post = request.POST.get("post")
    reply.subject = request.POST.get("subject")
    if request.FILES.get("attachment") is not None and request.FILES.get("attachment").size:
        try:
            attachment = FileUploads()
            attachment.type = "discussion_attachment"
            attachment.sub_type = discussion_id
            attachment.upload = request.FILES.get("attachment")
            attachment.save()
        except:
            attachment = None
    else:
        attachment = None
    if attachment:
        reply.attachment = attachment
    reply.save()
    discussion.date_reply = reply.date_create
    discussion.save()
    return redirect(reverse("community_discussion_view", kwargs={"discussion_id": discussion_id}))
def community_edit_process(request):
    """
    Processes the form data from the community add/edit form.
    :param request: Request object.
    :return: JSON response.
    """
    try:
        # Get all of the form data.
        community_id = request.POST.get("community_id", "")
        name = request.POST.get("name", "")
        motto = request.POST.get("motto", "")
        hangout = request.POST.get("hangout", "")
        try:
            district_id = request.POST.get("district-dropdown", False)
            if district_id:
                district = District.objects.get(id=int(district_id))
            else:
                district = None
        except:
            district = None
        try:
            state_id = request.POST.get("state-dropdown", False)
            if state_id:
                state = State.objects.get(id=int(state_id))
            else:
                state = None
        except:
            state = None
        # The logo needs special handling. If the path isn't passed in the post, we'll look to see if it's a new file.
        if request.POST.get("logo", "nothing") == "nothing":
            # Try to grab the new file, and if it isn't there, just make it blank.
            try:
                logo = FileUploads()
                logo.type = "community_logos"
                logo.sub_type = community_id
                logo.upload = request.FILES.get("logo")
                logo.save()
            except Exception as e:
                logo = None
                log.warning("Error uploading logo: {0}".format(e))
        else:
            # If the path was passed in, just use that.
            logo = None
        facilitator = request.POST.get("facilitator", "")
        private = request.POST.get("private", 0)
        # These all have multiple values, so we'll use the get_post_array function to grab all the values.
        courses = get_post_array(request.POST, "course")
        resource_names = get_post_array(request.POST, "resource_name")
        resource_links = get_post_array(request.POST, "resource_link")

        # If this is a new community, create a new entry, otherwise, load from the DB.
        if community_id == "new":
            community_object = CommunityCommunities()
        else:
            community_object = CommunityCommunities.objects.get(id=community_id)

        # Set all the community values and save to the DB.
        community_object.name = name
        community_object.motto = motto
        if logo:
            community_object.logo = logo
        community_object.hangout = hangout
        community_object.private = int(private)
        community_object.district = district
        community_object.state = state
        community_object.save()

        # Load the main user object for the facilitator user.
        user_object = False
        try:
            user_object = User.objects.get(email=facilitator)
        except Exception as e:
            log.warning("Invalid email for facilitator: {0}".format(e))

        # As long as the object loaded correctly, make sure this user is set as the facilitator.
        if user_object:
            # First we need to make sure if there is already a facilitator set, we unset them.
            try:
                old_facilitator = CommunityUsers.objects.filter(facilitator=True, community=community_object)
                for f in old_facilitator:
                    f.facilitator = False
                    f.save()
            except:
                pass
            # Now we try to load the new user in case they are already a member.
            try:
                community_user = CommunityUsers.objects.get(user=user_object, community=community_object)
            # If they aren't a member already, create a new entry.
            except:
                community_user = CommunityUsers()
                community_user.community = community_object
                community_user.user = user_object
            # Set the facilitator flag to true.
            community_user.facilitator = True
            community_user.save()
        else:
            raise Exception("A valid facilitator is required to create a community.")

        # Drop all of the courses before adding those in the form. Otherwise there is a lot of expensive checking.
        CommunityCourses.objects.filter(community=community_object).delete()
        # Go through the courses and add them to the DB.
        for key, course in courses.iteritems():
            # We only want to save an entry if there's something in it.
            if course:
                course_object = CommunityCourses()
                course_object.community = community_object
                course_object.course = course
                course_object.save()

        # Drop all of the resources before adding those  in the form. Otherwise there is a lot of expensive checking.
        CommunityResources.objects.filter(community=community_object).delete()
        # Go through the resource links, with the index so we can directly access the names and logos.
        for key, resource_link in resource_links.iteritems():
            # We only want to save an entry if there's something in it.
            if resource_link:
                resource_object = CommunityResources()
                resource_object.community = community_object
                resource_object.link = resource_link
                resource_object.name = resource_names[key]
                # The logo needs special handling since we might need to upload the file. First we try the entry in the
                # FILES and try to upload it.
                if request.POST.get("resource_logo[{0}]".format(key)):
                    file_id = int(request.POST.get("resource_logo[{0}]".format(key)))
                    logo = FileUploads.objects.get(id=file_id)
                else:
                    try:
                        logo = FileUploads()
                        logo.type = "community_resource_logos"
                        logo.sub_type = community_id
                        logo.upload = request.FILES.get("resource_logo[{0}]".format(key))
                        logo.save()
                    except Exception as e:
                        logo = None
                        log.warning("Error uploading logo: {0}".format(e))

                if logo:
                    resource_object.logo = logo
                resource_object.save()

        return redirect(reverse("community_view", kwargs={"community_id": community_object.id}))
    except Exception as e:
        data = {
            "error_title": "Problem Saving Community",
            "error_message": "Error: {0}".format(e),
            "window_title": "Problem Saving Community",
        }
        return render_to_response("error.html", data)