Beispiel #1
0
 def post(self, request):
     form = CategoryForm(request.POST, request.FILES)
     if form.is_valid():
         form.save()
         return redirect('create_post')
     return render(request,
                   'blog/create_category.html',
                   context={'form': form})
Beispiel #2
0
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        name = form.name.data
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        return redirect(url_for('.manage_category'))
    return render_template('admin/new_category.html', form=form)
Beispiel #3
0
def new_category():
    form = CategoryForm()
    if form.validate_on_submit():
        name = form.name.data
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash('Category created.', 'success')
        return redirect(url_for('blog.index'))
    return render_template('admin/new_category.html', form=form)
Beispiel #4
0
def category():
    form=CategoryForm()
    if form.validate_on_submit():
        category=Category(name=form.name.data)
        db.session.add(category)
        db.session.commit()
        flash('Your Category Created Succefully','success')
        return redirect(url_for('category'))

    return render_template('category.html',title='New Post',form=form)
Beispiel #5
0
def addcategory():
    form=CategoryForm()
    if form.validate_on_submit():
        name=form.name.data
        category=Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash(f'Category Created Successfully','success')
        return redirect(url_for('index'))
    return render_template('addcategory.html',form=form)
Beispiel #6
0
def category_update(request, pk):
    category = get_object_or_404(Category, pk=pk)
    # If request is POST, create a bound form(form with data)
    if request.method == "POST":  # If request is POST, create a bound form
        f = CategoryForm(request.POST, instance=category)
        if f.is_valid():
            if request.POST.get('author') == "" and request.user.is_superuser:
                # if author is not supplied and user is superuser
                updated_category = f.save(commit=False)
                author = Author.objects.get(user__username='******')
                updated_category.author = author
                updated_category.save()
            elif request.POST.get('author') and request.user.is_superuser:
                # if author is supplied and user is superuser
                updated_category = f.save()
            else:
                # if author not a superuser
                updated_category = f.save(commit=False)
                updated_category.author = Author.objects.get(
                    user__username=request.user.username)
                updated_category.save()

            new_category = f.save()
            messages.add_message(request, messages.INFO, 'Category updated')
            return redirect(reverse('category_update', args=[category.id]))
    # if request is GET the show unbound form to the user
    else:
        f = CategoryForm(instance=category)
    return render(request, 'cadmin/category_update.html', {
        'form': f,
        'category': category
    })
Beispiel #7
0
def category_new(request):
    form = CategoryForm()
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('post_edit')
        else:
            return redirect('category_edit')
    return render_to_response('blog/category_edit.html', {'form': form}, RequestContext(request))
    
Beispiel #8
0
def edit_category(category_id):
    if category_id == 1:
        flash(u'禁止修改默认分类', 'warning')
    category = Category.query.get_or_404(category_id)
    form = CategoryForm()
    if form.validate_on_submit():
        category.name = form.name.data
        db.session.commit()
        flash('Category updated.', 'success')
        return redirect_back()
    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
Beispiel #9
0
def edit_category(category_id):
    category = Category.query.get_or_404(category_id)
    form = CategoryForm()
    if category.id == 1:
        flash('You can not edit the default category.', 'warning')
        return redirect(url_for('blog.index'))
    if form.validate_on_submit():
        category.name = form.name.data
        db.session.commit()
        flash('Category updated.', 'success')
        return redirect(url_for('.manage_category'))
    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
Beispiel #10
0
def add_category(request):
    '''
    Adds a new blog category
    '''
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            category = Category.objects.get(title=form.cleaned_data['title'])
            return HttpResponseRedirect(reverse('blog.views.get_category',args=(category.slug,)))
    else:
        form = CategoryForm()
    return render_to_response('form.html', {'form':form, 'action':'add_category'}, RequestContext(request))
Beispiel #11
0
def categories(page=1):
	''' Admin view for categories; create and
	delete functionality included.'''
	form = CategoryForm(request.form)
	categories = Category.objects.paginate(page=page, per_page=10)
	if request.method == 'POST' and form.validate_on_submit():
		if Category.objects(name=form.name.data):
			flash('Category already exists')
			return redirect(url_for('posts.categories', page=1))
		new_category = Category(form.name.data)
		new_category.save()
		return redirect(url_for('posts.categories', page=1))
	return render_template('/admin/categories.html', post=Post, form=form, categories=categories)
Beispiel #12
0
def add_category(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print (form.errors)
    else:
        form = CategoryForm()

    return render(request, 'blog/add_category.html', {'form':form})
Beispiel #13
0
def renameCategory(request,idCategory):
	categories=Category.objects.all();
	cat=Category.objects.get(id=idCategory)
	displayForm=True;	
	if request.method=='POST':
		form=CategoryForm(request.POST)
		if form.is_valid():
			title=form.cleaned_data['title'];
			cat.title=title
			cat.save();
			return page(request,idCategory)
	else:
		form=CategoryForm(initial={'title': cat.title,})
	return render(request, 'blog/blogForm.html',locals())
Beispiel #14
0
def category_add(request):
    # If request is POST, create a bound form(form with data)
    if request.method == "POST":
        f = CategoryForm(request.POST)
        if f.is_valid():
            if request.POST.get('author') == "" and request.user.is_superuser:
                # if author is not supplied and user is superuser
                new_category = f.save(commit=False)
                author = Author.objects.get(user__username='******')
                new_category.author = author
                new_category.save()
            elif request.POST.get('author') and request.user.is_superuser:
                # if author is supplied and user is superuser
                new_category = f.save()
            else:
                # if author not a superuser
                new_category = f.save(commit=False)
                new_category.author = Author.objects.get(
                    user__username=request.user.username)
                new_category.save()

            messages.add_message(request, messages.INFO, 'Category added')
            return redirect('category_add')
    # if request is GET the show unbound form to the user
    else:
        f = CategoryForm()
    return render(request, 'cadmin/category_add.html', {'form': f})
Beispiel #15
0
    def post(self, request):
        if not request.user.is_staff:
            raise Http404
        form = CategoryForm(request.POST)
        categories = Category.objects.all().order_by("-timestamp")

        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            # message success
            messages.success(request, "Successfully Created")
            return render(request, self.template_name, {"categories": categories})
        # message error
        messages.error(request, "Category with this Name already exists")
        return render(request, self.template_name, {"categories": categories})
Beispiel #16
0
def CategoryCreate(request):
    if request.method == 'GET':
        category = Category.objects.all()
        form = CategoryForm()
        return render(request, 'blog/category_create_form.html', {
            'category': category,
            'form': form
        })
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            parent_category = form.cleaned_data['parent_category']
            Category(name=name, parent_category=parent_category).save()
            return HttpResponseRedirect(reverse("blog:category_add"))
Beispiel #17
0
def edit_category(request, id):
    '''
    Edits category information
    '''
    category = get_object_or_404(Category, id=id)
    if request.method == 'POST':
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            category_edited = form.save(commit=False)
            category.title = category_edited.title
            category.description = category_edited.description
            category.save()
        return HttpResponseRedirect(reverse('blog.views.get_category',args=(category.slug,)))
    else:
        form = CategoryForm(instance=category)
    return render_to_response('form.html', {'form':form, 'action':'edit_category'}, RequestContext(request))
Beispiel #18
0
def categories(page=1):
    ''' Admin view for categories; create and
	delete functionality included.'''
    form = CategoryForm(request.form)
    categories = Category.objects.paginate(page=page, per_page=10)
    if request.method == 'POST' and form.validate_on_submit():
        if Category.objects(name=form.name.data):
            flash('Category already exists')
            return redirect(url_for('posts.categories', page=1))
        new_category = Category(form.name.data)
        new_category.save()
        return redirect(url_for('posts.categories', page=1))
    return render_template('/admin/categories.html',
                           post=Post,
                           form=form,
                           categories=categories)
Beispiel #19
0
def addCategory(request):
	categories=Category.objects.all();
	addCategory=True;
	displayForm=True;	
	if request.method=='POST':
		form=CategoryForm(request.POST)
		if form.is_valid():
			title=form.cleaned_data['title'];
			envoi=True
			#creation of the section object
			category=Category(title=title)
			category.save();
			return home(request)
	else:
		form=CategoryForm()
	return render(request, 'blog/blogForm.html',locals())		
Beispiel #20
0
def add_category(request):
	
	# Get the context from the request.
	# Access the context sorrounding the HTTP Request that allow us determine 
	# the type  being made whether it be HTTP GET or POST
	context =  RequestContext(request)

	# A HTTP POST?
	if request.method == 'POST':

		#showing a new, blank form for adding a category;
		form =  CategoryForm(request.POST)

		# Have we been provided with a valid form?
		if form.is_valid():
			
			# Save the new category to the database.
			form.save(commit=True)

			# Now call the index() view.
			# THe user will be shown the app homepage.
			return index(request)
		else:
			# The supplied form contained errors - just print them to the terminal.
			# if there are errors, redisplay the form with error messages.
			print form.errors
	else:
		
		#if the request was not a POST, display the form to enter details.
		form = CategoryForm()

	# Bad form (or form details), no form supplied...
	# Render the form with error messages (if any).
	return render_to_response('blog/add_category.html', {'form': form}, context)
Beispiel #21
0
def add_category(request):

    if request.method == 'GET':
        category_list = Category.objects.all()
        return render(request, 'admin/category-add.html',
                      {'category_list': category_list})

    validate_category = CategoryForm(request.POST)
    errors = {}
    if validate_category.is_valid():
        new_category = validate_category.save(commit=False)
        new_category.save()
        data = {"data": 'Category created successfully', "error": False}
        return JsonResponse(data)

    for k in validate_category.errors:
        errors[k] = validate_category.errors[k][0]
    return JsonResponse(errors)
Beispiel #22
0
def add_category(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('user_menu')
    else:
        form = CategoryForm()
    return TemplateResponse(request, 'blog/addCategory.html', {'form': form})
Beispiel #23
0
def new_category():
    form = CategoryForm()
    # print(form.validate_on_submit())
    if form.validate_on_submit():
        name = form.name.data
        if Category.query.filter_by(name=form.name.data).count() == 1:
            flash('分类已存在!', 'err')
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash('添加分类成功!', 'ok')
        oplog = Oplog(
            user='******',
            ip=request.remote_addr,
            reason="新增分类-%s" % form.name.data,
        )
        db.session.add(oplog)
        db.session.commit()
        return redirect(url_for('admin.new_category'))
    return render_template('admin/new_category.html', form=form)
Beispiel #24
0
def updatecategory(id):
    form=CategoryForm()
    updatecategory=Category.query.get_or_404(id)
    category=request.form.get('name')
    if request.method=='POST':
        updatecategory.name=category
        flash(f'Category Successfully Updated','success')
        db.session.commit()
        return redirect(url_for('cotegory'))
    elif request.method=='GET':
        form.name.data=updatecategory.name
    return render_template('updatecategory.html',form=form)
Beispiel #25
0
def edit_category(request, pk):
    if request.method == "GET":
        category = Category.objects.get(pk=pk)
        category_list = Category.objects.all()
        return render(request, 'admin/category-edit.html', {
            'category_list': category_list,
            'category': category
        })

    c = Category.objects.get(pk=pk)
    validate_category = CategoryForm(request.POST, instance=c)
    errors = {}

    if validate_category.is_valid():
        validate_category.save()
        data = {"data": 'Category edited successfully', "error": False}
        return JsonResponse(data)

    for k in validate_category.errors:
        errors[k] = validate_category.errors[k][0]
    return JsonResponse(errors)
Beispiel #26
0
def admin_add_category(request):

    if users.is_current_user_admin():
        if request.method == 'GET':
            form = CategoryForm()
            
        elif request.method == 'POST':
            form = CategoryForm(request.POST)
            if form.is_valid():
                category = form.save(commit=False)
                category.put()
            return HttpResponseRedirect('/admin')
        
        return render_to_response('admin/edit.html',
                                      dictionary={ 'form':form,
                                                    'type': 'Add Category',
                                                    },
                                      context_instance=RequestContext(request)
                                    )
    else:
        return HttpResponseRedirect('/')
Beispiel #27
0
def create_category(request):
    warn_already_made = False
    if request.POST:
        formf = CategoryForm(request.POST)

        form = formf.save(commit=False)
        if Category.objects.filter(title=form.title).count() == 0:
            form.slug = slugify(form.title)
            form.save()
            return HttpResponseRedirect('/')
        else:
            warn_already_made = True
            form = CategoryForm()
    else:
        form = CategoryForm()
    args = {}
    args.update(csrf(request))
    args['form'] = form
    args['throw_duplicity_error'] = warn_already_made

    return render_to_response('create_category.html', args)
Beispiel #28
0
def edit_category(request, category_id):
    category = get_object_or_404(Category, pk=category_id)
    blog_title_list = request.POST.getlist('blog_title_list')
    print(blog_title_list)
    user_id = request.user.id
    if request.method == 'POST':
        new_category_form = CategoryForm(request.POST, instance=category)
        if new_category_form.is_valid():
            new_category = new_category_form.save(commit=False)
            new_category.user_id = user_id
            new_category.name = new_category_form.cleaned_data['name']
            new_category.content = new_category_form.cleaned_data['content']
            new_category.save()
            for blog_title in blog_title_list:
                blog = Post.objects.get(user_id=user_id, title=blog_title)
                blog.category_id = new_category.id
                blog.save()
            return redirect(reverse('blog:categories', args=(user_id,)))
    else:
        new_category_form = CategoryForm(instance=category)
        Blogs = Post.objects.filter(user_id=user_id, category_id=None)
        context = {
            'new_category_form': new_category_form,
            'category_id': category_id,
            'Blogs': Blogs,
        }
        return render(request, 'blog/addCategory.html', context)
Beispiel #29
0
def add_category(request, user_id):
    if request.method == 'POST':
        blog_title_list = request.POST.getlist('blog_title_list')
        category_form = CategoryForm(request.POST)
        if category_form.is_valid():
            category = category_form.save(commit=False)
            category.user_id = user_id
            category.name = category_form.cleaned_data['name']
            category.content = category_form.cleaned_data['content']
            category_exist = Category.objects.filter(name=category.name)
            if len(category_exist) == 1:
                warning = 'The category you have already created!'
                context = {
                    'category_form': category_form,
                    'warning': warning,
                }
                return render(request, 'blog/addCategory.html', context)
            elif len(category_exist) == 0:
                category.save()
                for blog_title in blog_title_list:
                    blog = Post.objects.get(user_id=user_id, title=blog_title)
                    blog.category_id = category.id
                    blog.save()
                return redirect(reverse('blog:categories', args=(user_id,)))

    else:
        category_form = CategoryForm()
        Blogs = Post.objects.filter(user_id=user_id)
        context = {
            'category_form': category_form,
            'user_id': user_id,
            'Blogs': Blogs,
        }
        return render(request, 'blog/addCategory.html', context)
Beispiel #30
0
def categorycreate():
    if g.user.is_admin():
        form = CategoryForm(request.form)
        if request.method == 'POST' and form.validate():
            if not g.user.is_admin():
                flash(u'非管理员不能创建类别!')
                return redirect(url_for('category'))
            else:
                category = Category(name=form.name.data)
                category.createdate = datetime.now()
                if form.seq.data == None:
                    category.seq = Category.default_seq()
                else:
                    category.seq = form.seq.data
                db.session.add(category)
                db.session.commit()
                flash(u'类别已创建!')
                return redirect(url_for('category'))
        return render_template('admin/categoryedit.html', form=form)
    else:
        flash(u'无权限访问')
        return redirect(url_for('index1'))
Beispiel #31
0
def add_category(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = CategoryForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'add_category.html', {'form': form})
Beispiel #32
0
def categorycreate():
    if g.user.is_admin():
        form = CategoryForm(request.form)
        if request.method == 'POST' and form.validate():
            if not g.user.is_admin():
                flash(u'非管理员不能创建类别!')
                return redirect(url_for('category'))
            else:
                category = Category(name=form.name.data)
                category.createdate = datetime.now()
                if form.seq.data == None:
                    category.seq = Category.default_seq()
                else:
                    category.seq = form.seq.data
                db.session.add(category)
                db.session.commit()
                flash(u'类别已创建!')
                return redirect(url_for('category'))
        return render_template('admin/categoryedit.html',
                               form=form)
    else:
        flash(u'无权限访问')
        return redirect(url_for('index1'))
Beispiel #33
0
def category_update(request, pk):
    category = get_object_or_404(Category, pk=pk)

    # if request is POST, created bound form
    if request.method == "POST":
        f = CategoryForm(request.POST, instance=category)

        # check whether form is valid
        # if valid, save to database
        # redirect user back to category form

        # if invalid, show with errors
        if f.is_valid():

            if request.POST.get('author') == "" and request.user.is_supseruser:
                # if author is not supplied and user is supseruser
                updated_category = f.save(commit=False)
                author = Author.objects.get(user__username='******')
                updated_category.author = author
                updated_category.save()
            elif request.POST.get('author') and request.is_superuser:
                # if author is supplied and user is superuser:
                updated_category = f.save()
            else:
                # if author is not a superuser
                updated_category = f.save(commit=False)
                updated_category.author = Author.objects.get(
                    user__username=request.user.username)
                updated_category.save()

            new_category = f.save()
            messages.add_message(request, messages.INFO, 'Category Updated')
            return redirect(reverse('category_update', args=[category.id]))

    # if request is GET show unbound form to user
    else:
        f = CategoryForm(instance=category)

    return render(request, 'cadmin/category_update.html', {
        'forms': f,
        'category': category
    })
Beispiel #34
0
def edit_category(category_id=None):
    if page_data is None or page_data.pages == 1:
        page = 1
    else:
        page = page_data.page if page_data.page < page_data.pages or page_data.total % page_data.per_page != 1 else page_data.pages - 1
    form = CategoryForm()
    category = Category.query.get_or_404(category_id)
    if category.id == 1:
        flash('默认分类不可更改', 'err')
        return redirect(url_for('admin.category_list', page=page))
    if form.validate_on_submit():
        category.name = form.name.data
        db.session.commit()
        flash('编辑分类成功!', 'ok')
        oplog = Oplog(
            user='******',
            ip=request.remote_addr,
            reason="修改分类:'%s'为'%s'" % (category.name, form.name.data),
        )
        db.session.add(oplog)
        db.session.commit()
        return redirect(url_for('admin.category_list', page=page))
    form.name.data = category.name
    return render_template('admin/edit_category.html', form=form)
Beispiel #35
0
def category_add(request):

    # if request is POST, create a bound form
    if request.method == "POST":
        f = CategoryForm(request.POST)

        # check whether form is valid
        # if valid, save data to database
        # redirect user to add post form

        # if form is invalid, show errors
        if f.is_valid():
            # new_category = f.save()
            # new_category = f.save(commit=False)
            # new_category.author = get_user(request)
            # new_category.save()

            if request.POST.get('author') == "" and request.user.is_superuser:
                # if author is not supplied and user is supseruser
                new_category = f.save(commit=False)
                author = Author.objects.get(user__username="******")
                new_category.author = author
                new_category.save()
            elif request.POST.get('author') and request.user.is_superuser:
                # if author is supplied and user is superuser
                new_category = f.save()
            else:
                # if author is not a superuser
                new_category = f.save(commit=False)
                new_category.author = Author.objects.get(
                    user__username=request.user.username)
                new_category.save()

            message.add_message(request, messages.INFO, 'Category Added')
            return redirect('category_add')

    # if request is GET then show unbound form to user
    else:
        f = CategoryForm()

    return render(request, 'cadmin/category_add.html', {'form': f})
Beispiel #36
0
def category_add(request):

    # If request is POST, create a bound form(form with data)
    if request.method == "POST":
        f = CategoryForm(request.POST)

        # check whether form is valid or not
        # if the form is valid, save the data to the database
        # and redirect the user back to the add post form

        # If form is invalid show form with errors again
        if f.is_valid():
            # new_category = f.save()
            # new_category = f.save(commit=False)
            # new_category.author = get_user(request)
            # new_category.save()

            if request.POST.get('author') == "" and request.user.is_superuser:
                # if author is not supplied and user is superuser
                new_category = f.save(commit=False)
                author = Author.objects.get(user__username='******')
                new_category.author = author
                new_category.save()
            elif request.POST.get('author') and request.user.is_superuser:
                # if author is supplied and user is superuser
                new_category = f.save()
            else:
                # if author not a superuser
                new_category = f.save(commit=False)
                new_category.author = Author.objects.get(
                    user__username=request.user.username)
                new_category.save()

            messages.add_message(request, messages.INFO, _('Category added'))
            return redirect('category_add')

    # if request is GET the show unbound form to the user
    else:
        f = CategoryForm()

    return render(request, 'cadmin/category_add.html', {'form': f})
Beispiel #37
0
def category_create(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.site = request.site

            category.save()
            lgr.info("Created New Category: {}".format(category))

        return redirect(reverse('blog:categories:list'))
    else:
        form = CategoryForm()

    context = {'form': form}
    return render(request, 'blog/category/create.html', context)
Beispiel #38
0
def admin_add_category(request):

    if users.is_current_user_admin():
        if request.method == 'GET':
            form = CategoryForm()

        elif request.method == 'POST':
            form = CategoryForm(request.POST)
            if form.is_valid():
                category = form.save(commit=False)
                category.put()
            return HttpResponseRedirect('/admin')

        return render_to_response('admin/edit.html',
                                  dictionary={
                                      'form': form,
                                      'type': 'Add Category',
                                  },
                                  context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/')
Beispiel #39
0
def category_update(request, pk):
    category = get_object_or_404(Category, pk=pk)
    if request.method == 'POST':
        f = CategoryForm(request.POST, instance=category)
        if f.is_valid():
            if request.POST.get('author') == '' and request.user.is_superuser:
                updated_category = f.save(commit=False)
                updated_category.author = Author.objects.get(
                    user__username='******')
                updated_category.save()
                f.save_m2m()

            elif request.POST.get('author') and request.user.is_superuser:
                f.save()

            else:
                updated_category = f.save(commit=False)
                updated_category.author = Author.objects.get(
                    user__username=request.user.username)
                updated_category.save()
                f.save_m2m()

            messages.add_message(request, messages.INFO, 'Category updated')
            redirect('category_update', pk=pk)

        else:
            print(f.errors)

    else:
        f = CategoryForm(instance=category)

    return render(request, 'cadmin/category_update.html', {'form': f})
Beispiel #40
0
def category_add(request):
    if request.method == 'POST':
        f = CategoryForm(request.POST)
        if f.is_valid():
            if request.POST.get('author') == '' and request.user.is_superuser:
                new_category = f.save(commit=False)
                new_category.author = Author.objects.get(
                    user__username='******')
                new_category.save()
                f.save_m2m()

            elif request.POST.get('author') and request.user.is_superuser:
                f.save()

            else:
                new_category = f.save(commit=False)
                new_category.author = Author.objects.get(
                    user__username=request.user.username)
                new_category.save()
                f.save_m2m()

            messages.add_message(request, messages.INFO, 'Category added')
            return redirect('category_add')

        else:
            print(f.errors)

    else:
        f = CategoryForm()
    return render(request, 'cadmin/category_add.html', {'form': f})
Beispiel #41
0
def edit_category_view(request, blog):
    blog = get_object_or_404(Blog, name_field=blog)
    # CategoryFormSet = forms.formset_factory(CategoryForm, formset=BaseCategoryFormSet, max_num=20)
    if request.user != blog.user:
        next = request.META.get('HTTP_REFERER', '/')
        return HttpResponseRedirect(next)

    cat = blog.get_category()
    if request.method == 'POST':
        if 'edit' in request.POST:
            formset = CategoryFormSet(request.POST)
            if len(cat) < 20:
                form2 = CategoryForm()
            if formset.is_valid():
                for idx, form in enumerate(formset.forms):
                    n = form.cleaned_data['name']
                    if n != cat[idx]:
                        arti = blog.article_set.filter(category__exact=cat[idx]).update(category=n)
                        cat[idx] = form.cleaned_data['name']
                        cat = sorted(cat)
                        blog.set_category(cat)
                        blog.save()
                return HttpResponseRedirect(request.path)
        if 'delete' in request.POST:
            formset = CategoryFormSet(request.POST)
            form2 = CategoryForm(request.POST)
            if formset.is_valid():
                for idx, form in enumerate(formset.forms):
                    if form.cleaned_data['DELETE']:
                        arti = blog.article_set.filter(category__exact=cat[idx]).update(category='')
                        del cat[idx]
                        blog.set_category(cat)
                        blog.save()
                return HttpResponseRedirect(request.path)
        if 'add' in request.POST:
            formset = CategoryFormSet(initial=[{'name': i} for i in cat])
            form2 = CategoryForm(request.POST)
            if form2.is_valid():
                n = form2.cleaned_data['name']
                if n in cat:
                    form2.add_error('name', 'This category already exist.')
                else:
                    cat.append(n)
                    cat = sorted(cat)
                    blog.set_category(cat)
                    blog.save()
                    return HttpResponseRedirect(request.path)
    else:
        formset = CategoryFormSet(initial=[{'name': i} for i in cat])
        if len(cat) < 20:
            form2 = CategoryForm()
    context = {
        'blog': blog,
        'cat': cat,
        'formset': formset,
        'form2': form2,
    }

    return render(request, 'editcategory.html', context=context)