Exemplo n.º 1
0
def submit(request):
	PhotoFormSet = formset_factory(PhotoForm, extra=1)
	if request.method == 'POST':
		storyform = StoryForm(request.POST, request.FILES)
		photoformset = PhotoFormSet(request.POST, request.FILES)	
			
		if storyform.is_valid() and photoformset.is_valid():
			s = Story(
				title = storyform.cleaned_data['title'],
				moderator = request.user
			)
			s.save();

			for form in photoformset.cleaned_data:
				image = form['image']
				p = Photo(
					name=s.title,
					story=s,
					image=image
				)
				p.save()
	else:
		storyform = StoryForm()
		photoformset = PhotoFormSet()	


	
	return render(request, 'stories/submit.html', {'storyfrom': storyform, 'photoformset': photoformset})
Exemplo n.º 2
0
def story(request):
    if request.method == 'POST':
        form = StoryForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/")
    else:
        form = StoryForm()
    return render(request, "stories/story.html", {"form": form})
Exemplo n.º 3
0
    def test_storyform_valid(self):
        """test form is valid"""
        form = StoryForm(
            data={
                "title": "Test Story 1",
                "content": "This the body of Test story 1",
                "access": Story.PRIVATE,
            })

        self.assertTrue(form.is_valid())
Exemplo n.º 4
0
def _get_form(request, error, error_ref):
    try:
        if error['ref'] == 'add_error' and error_ref == 'add_error':
            form = _get_add_error_form(error)
        elif error['ref'] == 'edit_error' and error_ref == 'edit_error':
            form = _get_edit_error_form(error)
        else:
            form = StoryForm()
    except (TypeError, KeyError):
        form = StoryForm()
    return form
Exemplo n.º 5
0
def story(request):
	if request.method == 'POST':
		form = StoryForm(request.POST)
		if form.is_valid():
			story = form.save(commit = False)
			story.moderator = request.user
			story.save()
			return HttpResponseRedirect('/')
	else:
		form = StoryForm()
	return render(request, 'stories/story.html', {'form': form})
Exemplo n.º 6
0
def story(request):
	if request.method == "POST":
		form = StoryForm(request.POST)
		if form.is_valid():
			story = form.save(commit=False)
			story.moderator = request.user
			story.save()
			return HttpResponseRedirect('/post/%s/' % (story.id))
	else:
		form = StoryForm()

	return render(request, 'tidder/story.html', {'form': form})
Exemplo n.º 7
0
def story(request):
	if request.method == 'POST':				# ako forma nije prazna
	 	form = StoryForm(request.POST)
	 	if form.is_valid():						# ako forma nije cijela ispunjena
	 		story = form.save(commit=False)		# snimi u "clipboard", ali nemoj još snimiti
	 		story.moderator = request.user		# ovo radimo zato što moderator je NOT_NULL
	 		story.save()						# snimi
	 		return HttpResponseRedirect('/')	# vrati na početnu stranicu
	else:
		form = StoryForm()						# forma je prazna

	return render(request, 'stories/story.html', {'form': form})
Exemplo n.º 8
0
def story(request):
	# Check to see if the form has been posted or not
	if request.method == 'POST':
		# Create a bound form object by passing the posted data through. 
		form = StoryForm(request.POST)
		if form.is_valid():
			story = form.save(commit=False)
			story.moderator = request.user
			story.save()
			return HttpResponseRedirect('/')
	else :
		# Otherwise just create an unbound form - creates the HTML for the form and sends that back
		form = StoryForm()
	return render(request, 'stories/story.html', {'form': form})
Exemplo n.º 9
0
    def test_story_forms(self):

        category = Category.objects.create(title='Category title')
        valid_data = {
            'title': 'Story title',
            'description': 'Description',
            'category': category
        }
        form = StoryForm(data=valid_data)
        self.assertFalse(form.errors)

        invalid_data = {'title': 1, 'category': category}
        form = StoryForm(data=invalid_data)
        self.assertTrue(form.errors)
Exemplo n.º 10
0
def story(request):
	if request.method == "POST":
		form = StoryForm(request.POST)
		if form.is_valid():
			#Get object back
			story = form.save(commit=False)
			story.moderator = request.user
			#Now save to DB
			story.save()
			return HttpResponseRedirect("/")
	else:
		form = StoryForm()

	return render(request, "stories/story.html", {"form": form})
Exemplo n.º 11
0
def helper(category, request):
    form = None
    result = False
    if category == 'Photos':
        form = PhotoForm(data=request.POST, files=request.FILES)
    elif category == 'Story':
        form = StoryForm(data=request.POST, files=request.FILES)
    current_category = Categories.objects.filter(category=category)
    if form.is_valid():
        if category == 'Photos':
            new_photo = form.save(commit=False)
            new_photo.owner = request.user
            new_photo.categoryid = current_category[0]
            new_photo.save()
            result = True
            return result, new_photo
        elif category == 'Story':
            pending_form = form.save(commit=False)
            pending_form.author = request.user
            pending_form.categoryid = current_category[0]
            pending_form.save()
            result = True
            return result, pending_form
        else:
            raise ValueError('category should be among predefined values')
    else:
        return result,
Exemplo n.º 12
0
    def test_field_setup_from_model(self):
        inspiration = mommy.make(Story, text='Inspiring')
        story = mommy.make(Story, text='Something', inspired_by=inspiration)
        form = StoryForm(user=story.author.user, instance=story)

        self.assertFieldsConfigured(form)
        self.assertIn('inspired_by', form.fields)
Exemplo n.º 13
0
def stories_detailview(request, story_id):
    if request.method == 'POST':


        form = StoryForm(request.POST)
        if form.is_valid():
            form.instance.sahip = request.user
            form.instance.evebeyn_id = story_id
            form.save()
    elif request.method == 'GET':
        form = StoryForm()
    return render(request, 'stories_detail.html',
                  {
                      'object': hikaye.objects.get(pk=story_id),
                      'form': form
                  })
Exemplo n.º 14
0
def add_story(request):
    """
    Create a new Story for the user
    """
    if request.method == 'POST':
        form = StoryForm(request.POST)
        if form.is_valid():
            story = form.save()
            return HttpResponseRedirect(reverse('stories_edit_story',args=[story.id]))
        else:
            print form.errors
    else:
        form = StoryForm()

    return render_to_response(
                'stories/add_story.html',
                locals(),
                context_instance=RequestContext(request))
Exemplo n.º 15
0
    def test_field_setup_inspired_by(self):
        inspiration = mommy.make(Story, text='Inspiring')
        form = StoryForm(user=inspiration.author.user,
                         initial={'inspired_by': inspiration})

        self.assertFieldsConfigured(form)
        self.assertListEqual(
            ['author', 'title', 'tagline', 'text', 'inspired_by', 'private'],
            list(form.fields.keys()))
Exemplo n.º 16
0
    def test_field_setup_no_inspired_by(self):
        story = mommy.make(Story, text='Something')
        form = StoryForm(user=story.author.user)

        self.assertFieldsConfigured(form)
        # Make sure the inspired_by field is NOT present
        self.assertListEqual(['author', 'title', 'tagline', 'text', 'private'],
                             list(form.fields.keys()))

        self.assertNotIn('inspired_by', form.fields)
Exemplo n.º 17
0
def add_story(request):
    if request.method == 'POST':
        project_id = request.POST.get('project', None)
        story = Story(accepted=True)
        story.order = Story.objects.filter(project=project_id).count()+1
        form = StoryForm(request.POST, instance=story)
        if form.is_valid():
            form.save()
            return redirect('project_page', project_id=project_id )
        else:
            request.session['error'] = {
                'ref':'add_error',
                'name':request.POST.get('name', ''),
                'time':request.POST.get('time', ''),
                'user':request.POST.get('user', ''),
            }
            return redirect('project_page', project_id=project_id)
    else:
        raise Http404
Exemplo n.º 18
0
def _get_add_error_form(error):
    user_id = error['user']
    if user_id == '':
        user_id = None
    form = StoryForm(
            {
                'name':error['name'],
                'time':error['time'],
                'user':int(user_id),
                }
            )
    return form
Exemplo n.º 19
0
def stories_create(request):
    if request.method == 'POST':
        story_form = StoryForm(request.POST)
        # storytag_form = StoryTagForm(request.POST)
        if story_form.is_valid():
            story_post = story_form.save(commit=False)
            story_post.author = request.user
            story_post.save()
            tag_ids = request.POST.get('tags').split(',')
            print(tag_ids)
            for tag_id in tag_ids:
                story_tag = StoryTag(tag_id=tag_id, story_id=story_post.id)
                story_tag.save()
            messages.success(request,
                             f'Your story has been added!',
                             extra_tags='success')
            return redirect('stories-home')
        else:
            messages.error(request,
                           f'Something went wrong!',
                           extra_tags='danger')
    else:
        story_form = StoryForm()
        context = {
            'story_form': story_form,
        }
    return render(request, 'stories/story_create.html', context)
Exemplo n.º 20
0
 def test_base_form_characteristics(self):
     """test base form child is inheriting characteristics"""
     form = StoryForm(
         data={
             "title": "Test Story 1",
             "content": "This the body of Test story 1",
             "access": Story.PRIVATE,
         })
     for _, field in form.fields.items():
         # if "Boolean" in str(field):
         #     self.assertTrue("form-check-input" in field.widget.attrs["class"])
         # else:
         self.assertTrue("form-control" in field.widget.attrs["class"])
Exemplo n.º 21
0
def create_story(request):
    if request.method == 'POST' and request.FILES['thumbnail']:
        user_id = request.user
        title = request.POST['title']
        thumbnail = request.FILES['thumbnail']
        category = request.POST['category']
        content = request.POST['content']
        cat = StoryCategory.objects.get(id=category)
        story = Story(uid=user_id, title=title, category=cat, thumb=thumbnail, content=content)
        story.save()

        sc_list = StoryCategory.objects.all()
        story_form=StoryForm()
        context = {'story_form':story_form, 'sc_list' : sc_list}

        return render(request, 'create-story.html', context)
    else:
        story_form=StoryForm()
        sc_list = StoryCategory.objects.all()
        context = {'story_form':story_form, 'sc_list' : sc_list}

        return render(request,'create-story.html',context)
Exemplo n.º 22
0
def edit_story(request):
    if request.method == 'POST':
        edit_id = request.POST.get('id', 0)
        try:
            story = Story.objects.get(id=edit_id)
        except Story.DoesNotExist:
            raise Http404
        form = StoryForm(request.POST, instance=story)
        if form.is_valid():
            form.save()
            return redirect('project_page', project_id=story.project_id)
        else:
            request.session['error'] = {
                'ref':'edit_error',
                'id':request.POST.get('id', ''),
                'name':request.POST.get('name', ''),
                'time':request.POST.get('time', ''),
                'user':request.POST.get('user', ''),
            }
            return redirect('project_page', project_id=request.POST['project'])
    else:
        raise Http404
Exemplo n.º 23
0
def submit(request):
    genres = Genres.objects.all()
    if request.method == "POST":  # If the form has been submitted...
        form = StoryForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            story = form.save(commit=False)
            story.user = request.user
            # genre = Genres.objects.get(pk=form['genre'])
            # genre.story_count += 1
            # genre.save()
            global STORYID
            STORYID += 1
            story.id = STORYID
            story.save()
            response = {"result": "true"}

            return HttpResponse(simplejson.dumps(response), mimetype="application/json")
    else:
        form = StoryForm()
        return render_to_response(
            "stories/submit.html", {"form": form, "genres": genres}, context_instance=RequestContext(request)
        )
Exemplo n.º 24
0
def submit(request):
	"""Submit new post view"""
	topic_list = Topic.objects.get_tree()
	selected_topic = ''
	if request.method == 'POST':
		form = StoryForm(request.POST)
		if form.is_valid():
			s = Story(title = form.cleaned_data['title'], text = form.cleaned_data['text'], user = request.user, topic = form.cleaned_data['topic'], url = form.cleaned_data['url'])
			s.slug = slugify(form.cleaned_data['title'])
			s.save()
			ds = DuggedStory(user = request.user, story = s)
			ds.save()
			urlredirect = reverse('stories_slug', args=[s.topic.urlname, s.slug])
			return redirect_to(request, urlredirect)
		else:
			if form.data['topic']:
				try:
					selected_topic = int(form.data['topic'])
				except:
					pass
	else:
		form = StoryForm()
	return render_to_response('stories/submit.html', {'form': form, 'user': request.user, 'topic_list': topic_list, 'selected_topic': selected_topic})
Exemplo n.º 25
0
def story(request):
    if request.method == 'POST':
        form = StoryForm(request.POST)
        if form.is_valid():
            story = form.save(commit=False)
            story.moderator = request.user
            story.save()
            return HttpResponseRedirect('/')
    else:
        form = StoryForm()
    return render(request, 'stories/story.html', {'form': form})
Exemplo n.º 26
0
def story(request):
    if request.method == 'POST':
        #call the class constructor and pass a dict. In this case StoryForm is the constructor. The dict is the form name and form dict.
        form = StoryForm(request.POST)
        if form.is_valid():
            story = form.save(commit=False)
            story.moderator = request.user
            story.save()
            return HttpResponseRedirect('/')
    else:
        form = StoryForm()
    return render(request, 'stories/story.html', {'form': form})
Exemplo n.º 27
0
def add_story(request):
    if request.method == 'POST':
        form = StoryForm(data=request.POST, files=request.FILES)
        current_category = Categories.objects.filter(category='Story')
        if form.is_valid():
            pending_form = form.save(commit=False)
            pending_form.author = request.user
            pending_form.categoryid = current_category[0]
            pending_form.save()
            # return redirect('stories:list_stories')
            return redirect(pending_form.get_absolute_url())
    else:
        form = StoryForm()
        return render(request,
                      'stories/add_story.html',
                      {'form': form})
Exemplo n.º 28
0
def stories_edit(request, pk):
    story = get_object_or_404(Story, pk=pk)
    if request.method == "POST":
        story_form = StoryForm(request.POST, instance=story)
        if story_form.is_valid():
            story_post = story_form.save()
            # story_post.author = request.user
            # story_post.save()
            messages.success(request,
                             f'Your story has been updated!',
                             extra_tags='success')
            return redirect('stories-detail', pk=story_post.pk)
        else:
            messages.error(request,
                           f'Something went wrong!',
                           extra_tags='danger')
    else:
        story_form = StoryForm(instance=story)
    return render(request, 'stories/story_edit.html',
                  {'story_form': story_form})
Exemplo n.º 29
0
    def test_save(self):
        # If we edit an existing form, can we re-save it without change?
        story = mommy.make(Story, text='Nothing')

        form = StoryForm(user=story.author.user, instance=story)
        # This is a hack to get the data=request.POST dict for save checking
        form = StoryForm(data=form.initial,
                         user=story.author.user,
                         instance=story)

        saved = form.save()
        for field in Story._meta.fields:
            name = field.name
            self.assertEqual(getattr(saved, name), getattr(story, name))

        # If we create a new story with the form, does it save as expected
        form = StoryForm(data={
            'title': 'This is the title',
            'author': story.author.id,
            'text': 'This is the text',
            'inspired_by': story.id,
            'private': True
        },
                         user=story.author.user)
        saved = form.save()
        self.assertEqual(saved.inspired_by.id,
                         story.id)  # Should be inspired by story
        self.assertIsNone(saved.published_at)
        self.assertIsNotNone(saved.id)

        # Save a new story without an inspired_by field
        form = StoryForm(data={
            'title': 'This is the title',
            'author': story.author.id,
            'text': 'This is the text',
            'private': False
        },
                         user=story.author.user)
        saved = form.save()
        self.assertIsNone(saved.inspired_by)  # Not inspired by anything
        self.assertIsNotNone(saved.published_at)  # And published
        self.assertIsNotNone(saved.id)
Exemplo n.º 30
0
    def test_storyform_invalid(self):
        """test its invalid with no content"""
        form = StoryForm(data={"title": "Test Story 1", "content": ""})

        self.assertFalse(form.is_valid())