def post(self, request): error_messages = [] form = SignupForm(request.POST) if form.is_valid(): first_name = form.cleaned_data.get("first_name") last_name = form.cleaned_data.get("last_name") username = form.cleaned_data.get("usr") email = form.cleaned_data.get("email") password = form.cleaned_data.get("pwd") blog_name = form.cleaned_data.get("blog_name") users = User.objects.filter(username=username) if len(users) == 0: new_user = User() new_user.username = username new_user.first_name = first_name new_user.last_name = last_name new_user.email = email new_user.set_password(password) new_user.save() blog = Blog() blog.name = blog_name blog.author = new_user blog.save() return redirect("posts_home") else: error_messages.append("El username {0} ya existe. Pruebe con otro".format(username)) context = {"errors": error_messages, "signup_form": form} return render(request, "users/signup.html", context)
def dashboard(request): try: blog = Blog.objects.get(user=request.user) if not resolve_subdomain(request.META['HTTP_HOST'], blog): return redirect(f"{blog.useful_domain()}/dashboard") if request.method == "POST": # TODO: Implement create Blog pass else: form = BlogForm(instance=blog) except Blog.DoesNotExist: blog = Blog(user=request.user, title=f"{request.user.username}'s blog", subdomain=slugify(f"{request.user.username}-new"), content="Hello World!", created_date=timezone.now()) blog.save() form = BlogForm(instance=blog) return render(request, 'dashboard/dashboard.html', { 'form': form, 'blog': blog, 'root': blog.useful_domain })
def dashboard(request): try: blog = Blog.objects.get(user=request.user) if not resolve_subdomain(request.META['HTTP_HOST'], blog): return redirect(f"http://{get_root(blog.subdomain)}/dashboard") if request.method == "POST": form = BlogForm(request.POST, instance=blog) if form.is_valid(): blog_info = form.save(commit=False) blog_info.save() else: form = BlogForm(instance=blog) except Blog.DoesNotExist: blog = Blog(user=request.user, title=f"{request.user.username}'s blog", subdomain=slugify(f"{request.user.username}-new"), content="Hello World!", created_date=timezone.now()) blog.save() form = BlogForm(instance=blog) return render(request, 'dashboard/dashboard.html', { 'form': form, 'blog': blog, 'root': get_root(blog.subdomain) })
def post(self,request): user = User() form = UserForm(data=request.POST) form.instance = user if form.is_valid(): user.first_name = form.cleaned_data.get('first_name') user.last_name = form.cleaned_data.get('last_name') user.email = form.cleaned_data.get('email') user.username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user.set_password(password) user.save() blog = Blog(user=user) blog.name = form.cleaned_data.get('blog_name') blog.description = form.cleaned_data.get('blog_description') blog.save() # logeamos al usaurio authenticate_user = authenticate(username=user.username, password=password) django_login(request, authenticate_user) # vaciamos el formulario form = UserForm() url = reverse("create_post") message = "User with blog created successfully!" message += '<a href="{0}">Create you first post</a>'.format(url) # enviamos mensaje de exito con un enlace al blog que acabamos de crear messages.success(request, message) return render(request, "singup_form.html", {'form': form})
def post(self, request): title = request.POST.get('title') gcontent = request.POST.get('gcontent') category = request.POST.get('category') user = request.user # user = User.objects.get(username=user) id = user.id print(title, id, gcontent) if not all((title, gcontent)): return render(request, 'user_center.html', {'errmsg': '数据不完整'}) blog = Blog() blog.title = title blog.content = gcontent user = User.objects.get(username=user) blog.author = user category = Category.objects.get(name=category) blog.category = category # blog=Blog.objects.create( # title=title, # # category=category, # author=id, # # ) blog.save() return redirect(reverse('blogs:personal_center'))
def register(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegisterForm(request.POST) print("there is a request") # check whether it's valid: if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() blog_id = Blog.objects.count() + 1 user = User.objects.get(username=request.POST.get('username')) blog = Blog(num=blog_id, writer=user, isDefault=True) blog.save() # form.save() response_data['status'] = 0 return HttpResponse(json.dumps(response_data), content_type="application/json") else: response_data['status'] = -1 response_data['message'] = list( form.errors.keys())[0] + ": " + form.errors[list( form.errors.keys())[0]][0] print( HttpResponse(json.dumps(response_data), content_type="application/json")) return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps(response_data), content_type="application/json")
def create_blog(request): user = request.user profile = Profile.objects.get(user=request.user) context = {'profile': profile} if request.method == 'GET': return render(request, 'blogs/create_blog.html', context=context) if request.method == 'POST': title = request.POST['title'] text = request.POST['text'] tags = request.POST['tags'] # blog create blog = Blog() blog.title = title blog.text = text blog.author = profile try: if any(request.FILES): blog.image = request.FILES['image'] except: blog.tags.add(tags) messages.error(request, 'Blog Image is not correct!') return render(request, 'blog/create_blog.html', context=context) blog.save() messages.success(request, 'Blog successfully created!') return redirect('/profiles/profile/{}'.format(user.username))
def postpage(request): if request.method == 'GET': return render(request, 'blogs/postnew.html') if request.method == 'POST': title = request.POST['subject'] content = request.POST['content'] if title and content: blog = Blog(title = title, content=content) blog.save() # memcache.set("update", True) # cache = memcache.get("top10") # print "cached : ",cache # cache.insert(0, blog) # cache = cache[:10] # memcache.set("top10", cache) # memcache.delete("time") blog_id = blog.id return redirect('/blogs/%s' %str(blog_id)) else: error = 'We need both a title and content' context = {'title': title, 'content': content, 'error': error } return render(request, 'blogs/postnew.html', context)
def post(self, req): error_messages = [] success_message = '' user = User() form = UserCreateForm(req.POST) if form.is_valid(): new_user = form.save() new_user.set_password(new_user.password) new_user.save() form = UserCreateForm() success_message = u'User creado con éxito! ' # blog for this user. blog = Blog(owner=new_user) if not req.POST.get('blog_name'): blog.name = 'Blog de ' + new_user.username else: blog.name = req.POST.get('blog_name') if not req.POST.get('blog_sdescription'): blog.short_description = 'Bienvenido al blog de ' + new_user.username else: blog.short_description = req.POST.get('blog_sdescription') blog.save() else: error_messages.append(u'Formulario incompleto.') context = { 'form': form, 'success_message': success_message, 'error_messages': error_messages } return render(req, 'users/signup.html', context)
def mutate(cls, root, info, project_id, blog): user = info.context.user if (user.is_authenticated): project = Project.objects.get(pk=project_id) author = User.objects.get(pk=user.id) if (author in project.members.all() or author in project.moderators.all() or author == project.admin): project_blog = Blog(author=author, title=blog.title, is_project_blog=True) if blog.data is not None: project_blog.data = blog.data if blog.tags is not None: project_blog.tags = blog.tags if blog.more_info is not None: project_blog.more_info = blog.more_info project_blog.save() project.blogs.add(project_blog) project.save() return AddProjectBlogMutation(blog=project_blog) raise Exception( "You don't have permissions to perform this action") raise Exception("You have to be logged in to access api")
def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() blog_id = Blog.objects.count() + 1 user = User.objects.get(username=request.POST.get('username')) blog = Blog(blog_id=blog_id, user=user) user.default_blog_id = blog_id user.save() blog.save() response = { "status": 0, } else: response = { 'status': -1, 'message': "some other error occurred" } return HttpResponse(json.dumps(response), content_type="application/json") else: response = { "status": -1, "message": "some error occurred" } return HttpResponse(json.dumps(response), content_type="application/json")
def create_blog(request): if request.method == "GET": context = {} return render(request, 'blogs/create_blog.html', context=context) if request.method == "POST": blog = Blog() blog.author = request.user.profile blog.title = request.POST['title'] blog.text = request.POST['text'] #тэги tags = request.POST.get('tags').split( ",") #делим строку из формы по запятым tags = [i.strip() for i in tags] #режем пробелы с обеих сторон #---------------------------------------------- try: if any(request.FILES): blog.image = request.FILES['image'] except: messages.error(reguest, 'Image is not correct!') return redirect(reverse('pages:index')) blog.likes = [] blog.save() blog.tags.set( *tags) #назначаем тэги в свежесохранённому блогу(или наоборот) messages.success(request, 'Blog successfuly created!') return redirect(reverse('pages:index'))
def create_blog_for_new_user(sender, instance, created, **kwargs): if created: b = Blog(user=instance) try: b.clean() except ValidationError: pass else: b.save()
def post(self, request, *args, **kwargs): blog = Blog( author=get_user_model().objects.get(pk=request.data.get("author")), title=request.data.get("title"), content=request.data.get("content"), summary=get_summary(request.data.get("content")), is_published=request.data.get("is_published"), ) blog.save() return Response(status=status.HTTP_200_OK)
def create(request): if request.user.is_authenticated() == False: return HttpResponseRedirect(reverse('login')) b = Blog(title=request.POST['blog[title]'], content=request.POST['blog[content]'], writer=request.POST['blog[writer]'], published_at=timezone.now(), email=request.POST['blog[email]']) b.save() return HttpResponseRedirect(reverse('blogs:show', args=(b.id,)))
def post(self, request): form = SignupForm(request.POST) if form.is_valid(): user = form.save() django_login(request, user) first_blog = Blog(owner=user, title=user.first_name + ' first Blog') first_blog.save() return redirect('home') context = {'form': form} return render(request, 'users/login.html', context)
def do_regist_blog(request): blog_regist_form = BlogRegistForm(request.POST) if blog_regist_form.is_valid(): _name = blog_regist_form.cleaned_data["name"] _title = blog_regist_form.cleaned_data["title"] _blog_id = blog_regist_form.cleaned_data["blog_id"] _user = User.objects.filter(username=request.session["user_id"]) new_blog = Blog(name=_name, title=_title, blog_id=_blog_id, user=_user[0]) new_blog.save() return redirect(ref_blog_top)
def post(self, request): serializer = UserSerializer(data=request.data) # se inicializa el serializer con los datos que me llegan por http mediante POST if serializer.is_valid(): new_user = serializer.save() # Guarda el objeto en BB.DD. y me lo devuelve new_blog = Blog() new_blog.name = 'El blog de {0} {1}'.format(request.data.get('first_name'), request.data.get('last_name')) new_blog.author = new_user new_blog.save() # serializer almacena los datos en 'serializer.data' return Response(serializer.data, status=status.HTTP_201_CREATED) else: # serializer almacena los errores en 'serializer.errors' return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create_blog(title): """ Helper function to create blog if it doesn't already exist """ blog = Blog( title = title, slug = slugify(title), summary = '', site = site, ) blog.save() return blog
def create(self, request): serializer = UserSerializer(data=request.data) #TODOS LOS MÉTODOS REST VIENEN POR EL PARAMETRO 'DATA' DE LA REQUEST if serializer.is_valid(): new_user = serializer.save() # TODO - crear el usuario y su blog en una sóla llamada blog_for_newUser = Blog() blog_for_newUser.owner = new_user blog_for_newUser.name = new_user.first_name + ' ' + new_user.last_name + '\'s Personal Blog' blog_for_newUser.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() default_blog_name = "Weblog " + user.username url = "/blogs/" + user.username blog_default = Blog(description="", name=default_blog_name, user=user, url=url) blog_default.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, validated_data): instance = User() blog = Blog() instance.first_name = validated_data.get("first_name") instance.last_name = validated_data.get("last_name") instance.username = validated_data.get("username") instance.email = validated_data.get("email") instance.set_password(validated_data.get("password")) instance.save() blog.blog_title = self.initial_data.get('blog_title') blog.user = instance blog.save() return instance
def post(self, request): user_post = User() form = SignUpForm(request.POST, instance= user_post) if form.is_valid(): user_post.set_password(form.cleaned_data.get("password")) user_post = form.save() default_blog_name= "Weblog " + str(user_post.username) url = "/blogs/" + str(user_post.username) blog_default = Blog(description="",name="Weblog " + user_post.username,user=user_post, url=url) blog_default.save() form = SignUpForm() message = "User "+user_post.username+" registered successfully! " message+= "Your default blog name is "+ default_blog_name messages.success(request, message) context = {'form': form} return render(request, "signup_form.html", context)
def index(request): if request.POST == {}: latest_blog_list = Blog.objects.order_by('-pub_date')[:5] context = {'latest_blog_list': latest_blog_list} return render(request, 'blogs/index.html', context) else: try: if (request.POST['url'] == u' ' or request.POST['description'] == u'' or request.POST['value'] == u' ' or request.POST['url'] == u' ' or request.POST['blog_title'] == u' ' or request.POST['date'] == u' '): raise Exception("Enter value") else: action_obj = Blog(Blog_Title=request.POST['blog_title'], Blog_Field=request.POST[ 'value'], URL=request.POST['url'], Blog_Description=request.POST['description'], pub_date=request.POST['date']) except Exception: return render(request, 'blogs/addblock.html', {'error_message': "Please Enter Full Information."}) else: action_obj.save() return HttpResponseRedirect(reverse('blogs:index'))
def post(self, request): form = RegistrationForm(request.POST) if form.is_valid(): new_user = form.save() # TODO - crear el usuario y su blog en una sóla llamada blog_for_newUser = Blog() blog_for_newUser.owner = new_user blog_for_newUser.name = new_user.first_name + ' ' +new_user.last_name + '\'s Personal Blog' blog_for_newUser.save() return redirect(reverse('users_login')) else: context = { 'signup_form': form } return render(request, 'users/sign-up.html', context)
def post(self, request): """ Método para cuando el signup viene del método HTTP get :param request: HttpRquest :return: render que contruye un HttpResponse con el template indicado """ # Mensaje de éxito al crear nuevo usuario success_message = '' # Crearemos un Django Form para presentarlo en la plantilla # Todos los valores del formulario se inicializan con los valores que vienen en el POST form = SignupForm(request.POST) # Si el formulario es válido, guardamos usuario if form.is_valid(): new_user = User.objects.create_user(form.cleaned_data.get('username'), form.cleaned_data.get('email'), form.cleaned_data.get('password')) new_user.first_name = form.cleaned_data.get('first_name') new_user.last_name = form.cleaned_data.get('last_name') new_user.is_staff = False # Guardamos usuario new_user.save() # Creamos blog con el nuevo usuario blog = Blog() blog.owner = new_user blog.save() # Reseteamos formulario form = SignupForm() success_message = 'OK' # Creamos contexto con mensaje éxito context = { 'signup_form': form, 'success_message': success_message } # Mandamos respuesta con error a través de la plantilla return render(request, 'users/registro.html', context)
def post(self, request): """ Método para cuando el signup viene del método HTTP get :param request: HttpRquest :return: render que contruye un HttpResponse con el template indicado """ # Mensaje de éxito al crear nuevo usuario success_message = '' # Crearemos un Django Form para presentarlo en la plantilla # Todos los valores del formulario se inicializan con los valores que vienen en el POST form = SignupForm(request.POST) # Si el formulario es válido, guardamos usuario if form.is_valid(): new_user = User.objects.create_user( form.cleaned_data.get('username'), form.cleaned_data.get('email'), form.cleaned_data.get('password')) new_user.first_name = form.cleaned_data.get('first_name') new_user.last_name = form.cleaned_data.get('last_name') new_user.is_staff = False # Guardamos usuario new_user.save() # Creamos blog con el nuevo usuario blog = Blog() blog.owner = new_user blog.save() # Reseteamos formulario form = SignupForm() success_message = 'OK' # Creamos contexto con mensaje éxito context = {'signup_form': form, 'success_message': success_message} # Mandamos respuesta con error a través de la plantilla return render(request, 'users/registro.html', context)
def create(self, request): """ Endpoint de creación de usuario. Guardamos automáticamente también el blog con su nombre de usuario :param request: :return: """ # Creamos serializador a partir de los datos de la petición. En rest framwork, para evitar request.POST, # request.GET, etc., se utiliza simplemente data serializer = UserSerializer(data=request.data) if serializer.is_valid(): new_user = serializer.save() # Guardamos blog para el nuevo usuario user_blog = Blog() user_blog.owner = new_user user_blog.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def blog_form(request): if request.method == 'POST': form = forms.BlogForm(request.POST) if form.is_valid(): data = form.cleaned_data if 'id' not in data: blog = Blog(title=data['title'], author=data['author'], content=data['content']) blog.save() else: blog = Blog.object.get(id=data.id) blog.title = data['title'] blog.author = data['author'] blog.content = data['content'] blog.save() return HttpResponseRedirect('/blog/list') else: form = forms.BlogForm() return render_to_response('blog_form.html', {'form': form}, context_instance=RequestContext(request))
def post(self, request): form = SignupForm(request.POST) self.translate(form) context = dict() if form.is_valid(): if User.objects.filter( username=form.cleaned_data.get("username")).exists(): form.add_error("username", _("El usuario ya existe")) else: user = User() user.username = form.cleaned_data.get("username") user.set_password(form.cleaned_data.get("password")) user.first_name = form.cleaned_data.get("first_name") user.last_name = form.cleaned_data.get("last_name") user.email = form.cleaned_data.get("email") try: user.save() blog = Blog() if user.first_name or user.last_name: blog.name = "Blog de " + user.first_name + " " + user.last_name else: blog.name = "Blog de " + user.username blog.owner = user blog.save() url = request.GET.get('next', '/new-post') return redirect(url) except Error as err: form.add_error("__all__", _("Error en acceso a base de datos")) print("Error en acceso a base de datos: ", err) context["form"] = form return render(request, 'signup.html', context)
def post(self, request): """ Endpoint de creación de usuario. Por convención, se utiliza la url de listado con una petición POST para la creación de un objeto de ese listado. En el serializer.save() comprueba automáticamente si tiene instasncia del User; si no la tiene, llama al método create del serializer. """ # Creamos serializador a partir de los datos de la petición. En rest framwork, para evitar request.POST, # request.GET, etc., se utiliza simplemente data serializer = UserSerializer(data=request.data) if serializer.is_valid(): # Guardamos el usuario a través del serializer y devolvemos los datos del objeto creado new_user = serializer.save() # Guardamos blog para el nuevo usuario user_blog = Blog() user_blog.owner = new_user user_blog.save() # Respondemos código 201 (creado) y los datos del objeto creado return Response(serializer.data, status=status.HTTP_201_CREATED) else: # Devolvemos diccionario con errores y el código 400 (petición errónea) si algo fue mal return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def blog_form(request): state = None if request.method == 'POST': if Blog.objects.all().exists(): blog_last = Blog.objects.all().order_by('-id')[0] Blog.id = int(blog_last.id) + 1 else: Blog.id = 0 new_blog = Blog( id=Blog.id, title=request.POST.get('title', ''), author=request.POST.get('author', ''), content=request.POST.get('content', ''), ) new_blog.save() state = 'success' con = { 'state': state, } return render(request, 'yemian/blog_form.html', con)
def post(self, request): error_messages = [] form = SignupForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('usr') password = form.cleaned_data.get('pwd') email = form.cleaned_data.get('email') user = User.objects.filter(email=email) if user.exists(): error_messages.append('Ya existe un usuario con este email') else: # creamos el usuario new_user = form.save() new_user.set_password(new_user.password) new_user.save() form = SignupForm() if new_user.is_active: # nos autenticamos user = authenticate(username=new_user.username, password=new_user.password) # creamos el blog del usuario blog = Blog(owner=new_user) blog.title = 'Blog de ' + new_user.username blog.save() # redireccionamos a la página de inicio django_login(request, user) url = request.GET.get('next', 'wordplease_home') return redirect(url) else: error_messages.append('El usuario no está activo, contacte con el administrador del sitio.') context = { 'errors': error_messages, 'signup_form': form } return render(request, 'users/signup.html', context)
def post(self, request): form = BlogForm(request.POST) if form.is_valid(): blog = Blog() cleaned_data = form.cleaned_data blog.name = cleaned_data.get('name') blog.user = request.user blog.slug = cleaned_data.get('name').replace(" ", "_") blog.save() message = "Post creado con éxito!" form = BlogForm() else: message = "Se ha producido un error" context = {"form": form, "message": message} return render(request, 'blogs/new_post.html', context)