Exemplo n.º 1
0
def save_entry(request):
	if not request.is_ajax() or not request.method == 'POST':
		raise Http404
	
	form= EntryForm(request.POST)
	
	if not form.is_valid():
		return HttpResponse('{}', mimetype='application/javascript')
	
	if 'pk' in request.POST:
		entry= get_object_or_404(Entry, pk= request.POST['pk'])
		form= EntryForm(request.POST, instance= entry)
		entry= form.save(commit= False)
		
		entry.body = strip_tags(entry.body)
		entry.title = strip_tags(entry.title)
		entry.save()
	else:
		entry= form.save(commit= False)
		entry.body = strip_tags(entry.body)
		entry.title = strip_tags(entry.title)
		entry.save()
	
	entry_content_type= ContentType.objects.get_for_model(entry.__class__)
	
	response_data= json.dumps({
		'pk': entry.pk,
		'model': '%s.%s' % (entry_content_type.app_label, entry_content_type.model),
	})
	
	return HttpResponse(response_data, mimetype='application/javascript')
Exemplo n.º 2
0
def entry(request):
    if request.session.has_key('logged_in'):
        now = datetime.datetime.now()
        if request.method == 'POST':
            form = EntryForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                now = datetime.datetime.now()
                strnow = now.strftime('%d/%m/%Y')
                author = cd['author']
                content = cd['content']
                e = Entry(date=now,
                          strdate=strnow,
                          author=author,
                          content=content)
                e.save()
                return HttpResponseRedirect('/diary/submitted/')
        else:
            form = EntryForm()
            return render(request, 'new_entry.html', {
                'form': form,
                'now': now
            })
    else:
        return render(request, 'login.html',
                      {'user_login': '******'})
Exemplo n.º 3
0
def create(request):
	if request.user.is_authenticated() is False:
		args = {}
		args['entry_list'] = Entry.objects.all()
		args['error'] = 'You must be signed in before creating a new post.'	
		return render_to_response('coltrane/entry_index.html', args)
	if request.POST:
		#post_values = request.POST.copy()
		#post_values['author'] = 4
		post_values = request.POST.copy()
		form = EntryForm(request.POST, request.FILES)
		if form.is_valid():
			#form.save()
			obj = form.save(commit=False)
			obj.author = request.user
			#get entry and category id:
			e1 = obj.id
			c1 = post_values['categories']
			c2 = Category.objects.get(id=c1)
			#save entry to category	
			obj.save()	
			#add the hashtags from the post into the database:
			getHashtags = obj.body + " " + obj.title
			s = {tag.strip("#") for tag in getHashtags.split() if tag.startswith("#")}
			for item in s:
				h = Hashtag.objects.filter(title=item)
				if not h:
					item = item.lower()
					newhash = Hashtag(title=item, num_used=1)
					newhash.save()
					obj.tags.add(newhash)
					#obj.save()
				else:
					#oldh = Hashtag.objects.get(title=item)	
					for item2 in h:
						item2.num_used += 1
						item2.save()
						obj.tags.add(item2)			
					#obj.save()	
			#this code increments each time a specific user creates a post
			inc_post = request.user.id
			count_post = User_Profile.objects.get(uid_id=inc_post)
			count_post.num_posts += 1
			count_post.save()
			
			obj.categories.add(c1)
			return HttpResponseRedirect('/weblog')
	else:
		form = EntryForm()
		form.author = request.user
	args = {}
	args.update(csrf(request))
	args['form'] = form 
	args['username'] = request.user.username
	args['uid'] = request.user.id
	return render_to_response('coltrane/newpost.html', args)
def subscribe(request):
    form = EntryForm()
    if request.method == "POST":
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            success = True
            form = EntryForm()
            return render_to_response(
                "subscribe.html", {"success": success, "form": form}, context_instance=RequestContext(request)
            )

    return render_to_response("subscribe.html", {"form": form}, context_instance=RequestContext(request))
Exemplo n.º 5
0
def edit_entry(request, entry_id):
    """Редактирует существующую запись."""
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if request.method != 'POST':
        # Исходный запрос; форма заполняется данными текущей записи.
        form = EntryForm(instance=entry)
    else:
        # Отправка данных POST; обработать данные.
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(
                reverse('learning_logs:topic', args=[topic.id]))
    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'learning_logs/edit_entry.html', context)
Exemplo n.º 6
0
def new_entry(request, topic_id):
    """Добавляет новую запись по конкретной теме."""
    topic = Topic.objects.get(id=topic_id)
    if request.method != 'POST':

        form = EntryForm()
    else:
        # Отправлены данные POST; обработать данные.
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return HttpResponseRedirect(
                reverse('learning_logs:topic', args=[topic_id]))
    context = {'topic': topic, 'form': form}
    return render(request, 'learning_logs/new_entry.html', context)
def subscribe(request):
    form = EntryForm()
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            success = True
            form = EntryForm()
            return render_to_response('subscribe.html', {
                'success': success,
                'form': form
            },
                                      context_instance=RequestContext(request))

    return render_to_response(
        'subscribe.html',
        {'form': form},
        context_instance=RequestContext(request),
    )
Exemplo n.º 8
0
def new_entry(request):

    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')

    if request.POST:
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/newentry/')
    else:
        form = EntryForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('newentry.html', args)
Exemplo n.º 9
0
def create_entry(request):
    """
    Create entry:
      Model form which automatically fills in the author and uses slugify to
      create a slug for the entry based on the tittle.
    """
    if request.method == 'POST':
        try:
            user = User.objects.get(username=request.user)
            new_entry = Entry(author=user)
            form = EntryForm(request.POST, instance=new_entry)
        except User.DoesNotExist:
            return HttpResponse("Invalid username")
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.slug = slugify(new_entry.title)
            new_entry.save()
            return HttpResponseRedirect("/")
    else:
        form = EntryForm()

    return render_to_response("mingus/create_entry.html",
                              {"form": form, },
                              context_instance=RequestContext(request))
Exemplo n.º 10
0
def form(request, date=None):
    if request.user.is_authenticated():
        # get the date
        if date == None:
            date = datetime_date.today()
        else:
            date = parse_date(date)

        # get the entry
        try:
            entry = Entry.objects.filter(user=request.user).get(date=date)
        except Entry.DoesNotExist:
            entry = Entry(user=request.user,date=date)
            entry.save()

        if request.method == 'POST':
            # construct the form
            form = EntryForm(request.POST,groups=Group.objects.filter(user=request.user))

            if form.is_valid():
                values = form.cleaned_data

                for key in values:
                    field_id = key.split('_')[1]
                    value = values[key]

                    field = Field.objects.get(id=field_id)

                    record = Record.objects.filter(entry=entry).get(field=field)
                    record.value = value
                    record.save()
            else:
                print form.errors

            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
        else:

            fieldsets = []
            for group in Group.objects.filter(user=request.user):
                fieldset = {
                    'name': group.name,
                    'elements': []
                }

                for field in group.fields.all():
                    try:
                        record = field.records.get(entry=entry)
                    except Record.DoesNotExist:
                        record = Record(entry=entry,field=field)
                        record.save()

                    fieldset['elements'].append({
                        'field': field,
                        'record': record
                    })

                fieldsets.append(fieldset)

            return render(request,'form.html', {
                'fieldsets': fieldsets,
                'yesterday': date - datetime_timedelta(1),
                'today': date,
                'tomorrow': date + datetime_timedelta(1),
                'auth': True,
                'user': request.user
            })
    else:
        return HttpResponseRedirect('/login/')