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 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 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 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): user = request.user profile = Profile.objects.get(user=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'].replace(' ', '').lower().split(',') blog = Blog() blog.title = title blog.text = text blog.author = profile try: if any(request.FILES): blog.image = request.FILES['image'] except: messages.error(request, 'Blog Image is not correct!') return render(request, 'blogs/create_blog.html', context=context) blog.save() if tags: for tag in tags: blog.tags.add(tag) 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 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 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 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, *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_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 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): blog = Blog() blog.owner = request.user form = BlogForm(request.POST, instance=blog) if form.is_valid(): new_blog = form.save() messages.success( request, 'Post creado correctamente con ID {0}'.format(new_blog.pk)) form = BlogForm() context = {'form': form} return render(request, 'new-post.html', context)
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 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 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 post(self, request): """ Recibe los datos del nuevo post los valida y los guarda :param request: HttpRequest :return: HttpResponse """ # crear el formulario con los datos del POST blog_with_user = Blog(owner=request.user) form = BlogForm(request.POST, instance=blog_with_user) if form.is_valid(): #crea el post blog = form.save() #generar mensaje de exito msg = "Blog creado con éxito" # limpiamos el formulario creando uno vacío para pasar a la plantilla form = BlogForm() else: msg = "Ha ocurrido un error al guardar el blog" \ # renderiza la plantilla con el formulario context = {"form": form, "msg": msg} # renderiza y devuelve la plantilla return render(request, 'blogs/new-blog.html', context)
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 post(self, request): """ Shows a form to create a new blog :param request: HttpRequest :return: HttpRequest """ blog_with_owner = Blog() blog_with_owner.owner = request.user form = BlogForm(request.POST, instance=blog_with_owner) if form.is_valid(): new_blog = form.save() # Guarda el objeto y lo devuelve FTW return redirect('blog_detail', ownerName=new_blog.owner, pk=new_blog.pk) context = {'form': form} return render(request, 'blogs/new_blog.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): """ Shows a form to create a new blog :param request: HttpRequest :return: HttpRequest """ blog_with_owner = Blog() blog_with_owner.owner = request.user form = BlogForm(request.POST, instance=blog_with_owner) if form.is_valid(): new_blog = form.save() # Guarda el objeto y lo devuelve FTW return redirect('blog_detail', ownerName=new_blog.owner, pk=new_blog.pk) context = { 'form': form } return render(request, 'blogs/new_blog.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 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 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 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 post(self, request): new_blog = Blog(author=request.user) form = BlogForm(request.POST, instance=new_blog) if form.is_valid(): new_blog = form.save() messages.success( request, 'Blog {0} created successfully!'.format(new_blog.name)) form = BlogForm() return render(request, 'blogs/blog_new.html', {'form': form})
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): """ Procesa el formulario para crear un blog :param request: objeto HttpRequest :return: HttpResponse con la respuesta """ blog = Blog() blog.author = request.user form = BlogForm(request.POST, instance=blog) if form.is_valid(): # creamos el blog blog = form.save() # limpiar el formulario form = BlogForm() # Devolvemos un mensaje de OK messages.success(request, 'Blog created correctly') return redirect('blogs') context = {'form': form} context['title'] = "Create a new Blog" context['claim'] = 'Create an incredible new blog' messages.error(request,'Blog could not be created. Please check fields') return render(request, 'blogs/new-blog.html', context)
def post(self, request): """ Procesa el formulario de creación de un blog :param request: objeto HttpRequest :return: HttpResponse con respuesta """ blog = Blog() try: blog.owner = User.objects.get(username=request.user) except Blog.DoesNotExist: return HttpResponse('Este usuario no existe', status=404) form = BlogForm(request.POST, request.FILES, instance=blog) if form.is_valid(): new_blog = form.save() form = BlogForm() messages.success(request, 'Blog creado correctamente') context = {'form': form} return render(request, 'blogs/form.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): new_blog = Blog() blog_form = BlogForm(request.user, request.POST, request.FILES, instance=new_blog) if blog_form.is_valid(): new_blog = blog_form.save() messages.success( request, 'El blog {0} se ha creado corretamente!'.format( new_blog.title)) blog_form = BlogForm(request.user) return render(request, 'new_blog.html', {'form': blog_form})
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): blog_with_user = Blog(owner=request.user) form = BlogForm(request.POST, instance=blog_with_user) self.translate(form) message = "" if form.is_valid(): form.save() form = BlogForm() message = _("Se ha creado correctamente el blog") context = {"form": form, "message": message} return render(request, 'blogs/new_blog.html', context)
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): # Nos definimos previamente un formulario con el valor del usuario que hemos excluido de la página. new_blog_in = Blog(owner=request.user) # Coge los datos del formulario y de los ficheros form = BlogForm(request.POST, instance=new_blog_in) if form.is_valid(): new_blog_in = form.save() messages.success( request, 'Blog {0} creado con éxito!'.format(new_blog_in.title)) # Se limpia el formulario para una nueva inserción form = BlogForm() else: storage = generate_new_html_errors(form.errors) for msg in storage: messages.error(request, storage.get(msg)) return render(request, 'blogs/new_blog.html', {'form': form})
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): 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): 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)