Расширенный профайл юзера в Django: редактирование расширенных и встроенных полей через одну форму. Расширение профиля пользователя django Остервенение edit profile html view

в Django я по прежнему новичок, но что-то стараюсь понять и запомнить.

стояла задача расширить профиль пользователя дополнительными полями, статей на эту тему пресс и малелькая тележка, но не получалось, то у кого-то на сайте парсер html сильно злой и код надо было переписывать, у кого-то были ошибки в примерах и т.п.

но как-то оно получилось, попробую собрать все мысли в кучу в эту статью.

{% endblock content %}

сохраняем, теперь можно обратиться к /profiles/edit/ то должно открыться форма редактирования профиля.

бывают ситуации, что в профиле есть какие-то поля, что запрещено редактировать пользователю, реализуется это довольно просто

создаём класс формы, наследуемой от общей формы, в котором перечисляем, то что нам исключить от вывода пользователю
forms.py

from django.db import models
from django.forms import ModelForm

.........
class ProfileForm(forms.ModelForm ) :
class Meta:
model = UserProfile
exclude = ("user" , "last_name" , )

from PROJ.apps.APP.models import UserProfile
проект и приложение где расположена расширенная модель

теперь в urls.py надо указать, что страницу редактирования профиля надо открывать с нужной нам формой

from PROJ.APP .forms import ProfileForm
........
("^profiles/edit" , "profiles.views.edit_profile" , { "form_class" : ProfileForm, } ) ,
(r"^profiles/" , include("profiles.urls" ) ) ,
.......

Должно получиться примерно так.. проверяем на странице редактирования профиля (/profiles/edit/).

Теперь сделаем страницу отображения профиля profile/profile_detail.html

вывести можно что угодно из профиля вот так

< p>< strong> Address 2 :< /strong>< br> { { profile .address2 } } < /p>

где address2 это дополнительное поле
список пользователей с профилями можно вывести вот так

profiles/profile_list.html

{ % extends "base.html" %}
{ % block content %}
< h1> Список пользователей< /h1>
< br/>< br/>
{ % for p in object_list %}
< a href= "{% url profiles_profile_detail p.user %}" > { { p.user } } < /a>
{ % endfor %}
{ % endblock %}

Теперь задача такая, сейчас профиль и пользователь живут почти своей жизнью, при регистрации пользователя профиль сам не создаётся это мы сейчас и решим сигналами.

в models.py добавим

from django.db .models import signals
from bucket.signals import create_profile

# When model instance is saved, trigger creation of corresponding profile
signals.post_save .connect (create_profile, sender= User)

создадим файл, если он не создан signals.py:

def create_profile(sender, instance, signal , created, **kwargs) :
"""When user is created also create a matching profile."""

from PROJ.apps .APP .models import UserProfile

if created:
UserProfile(user = instance) .save ()
# Do additional stuff here if needed, e.g.
# create other required related records

вот и всё, при регистрации нового пользователя автоматически будет создаваться к нему профиль, если у вас уже сейчас много пользователей, то создать для каждого профиль можно вот так

$ python manage.py shell

from django.contrib .auth .models import User
from bucket.models import Profile

Users = User.objects .all ()
for u in users:
try :
p = u.get_profile ()
except p.DoesNotExist :
Profile(user = u) .save ()

ещё коснусь вопроса редактирования своего email в профиль, пока ещё не совсем разобрался с этим.

пока есть только пример, делается это анналогично через forms.py

class ProfileForm(ModelForm) :

def __init__ (self , *args, **kwargs) :
super (ProfileForm, self ) .__init__ (*args, **kwargs)
try :
self .fields [ "email" ] .initial = self .instance .user .email
# self.fields["first_name"].initial = self.instance.user.first_name
# self.fields["last_name"].initial = self.instance.user.last_name
except User.DoesNotExist :
pass

email = forms.EmailField (label= "Primary email" , help_text= "" )

class Meta:
model = Profile
exclude = ("user" , )

def save(self , *args, **kwargs) :
"""
Update the primary email address on the related User object as well.
"""

u = self .instance .user
u.email = self .cleaned_data [ "email" ]
u.save ()
profile = super (ProfileForm, self ) .save (*args, **kwargs)
return profile

надеюсь вернусь к этому вопросу

For adding additional properties to the UserProfile table you will need to change a series of changes in

  • UserProfile table class
  • RegisterModel class
  • RegisterView (where you will be adding input for the new field)
  • AccountController/Register action (to read the new input value and use accordingly)

1. Modify your UserProfile class

Here in this example I am adding a new field called "MobileNumber ", have declared it as type string.

Public class UserProfiles { public int UserId { get; set;} public string Email { get; set;} public string FirstName { get; set; } public string LastName { get; set; } public string MobileNumber { get; set; } }

2. Add the additional property(ies) to your RegisterModel.cs

Add the new property in your Model. In this example where we want an extra field while user registration we need to update the RegisterModel class. Add validations if need be.

Public class RegisterModel { public string Email { get; set; } public string Password { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string MobileNumber { get; set; } }

3. Display additional fields on your View

Once you have update the Model you should be able to use the @Html.TextBoxFor(m => m.MobileNumber) in your view, which will bind the MobileNumber field to your "MobileNumber" property declared in your model.

@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary() @Html.LabelFor(m = m.Email) @Html.TextBoxFor(m => m.Email) @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password) @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName) @Html.LabelFor(m => m.LastName) @Html.TextBoxFor(m => m.LastName) @Html.LabelFor(m => m.MobileNumber) @Html.TextBoxFor(m => m.MobileNumber) }

4. Update your Controller - (AccountController in this case)

Last step, here you just need to read the value posted to your model and pass it along the repository for saving.

Public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { WebSecurity.CreateUserAndAccount(model.Email, model.Password, new { FirstName = model.FirstName, LastName = model.LastName, MobileNumber = model.MobileNumber }); WebSecurity.Login(model.Email, model.Password); return RedirectToAction("Index", "Home"); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return View(model); }

5. Get this value back from DB and into your view

Now since your RegisterModel already has this property and so does your UserProfile class, using RegisterModel class on your view, you should be able to access the new added property.

Избитая задача: сделать профайл пользователя, расширяющий встроенную модель . Допустим, нужно добавить в профайл юзера поле about , где он может написать кратко о своих интересах и т.п. Предполагается, что система авторизации юзеров на основе встроенных стредств Django у вас на сайте уже имеется.

Делаем, как прописано в мануалах Django. Определяем модель, расширяющую django.contrib.auth.models.User :

From django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): # необходимое поле для связки со встроенной моделью юзера Django user = models.ForeignKey(User, unique=True) # наше добавляемое поле about = models.TextField(blank=True)

ну и сохраняем этот класс в свой models.py

В settings.py проекта прописываем параметр AUTH_PROFILE_MODULE , который позволит обращаться к нашей расширенной модели через вызов метода get_profile у встроенной модели django.contrib.auth.models.User .

AUTH_PROFILE_MODULE = "models.UserProfile"

В принципе, модель готова. Теперь (например) в шаблонах можно использовать такую конструкцию для вывода нашего поля about:

{{ user.get_profile.about }}

Только не забудьте для такого шаблона использовать RequestContext вместо Context , и подключить соотв.процессор контекста в settings.py :

TEMPLATE_CONTEXT_PROCESSORS = (... "django.contrib.auth.context_processors.auth", ...)

Берем маленькое приложение Django под названием profiles вот , распаковываем архив, копируем каталог profiles в каталог, включенный в sys.path .
(для таких случаев у меня есть каталог django_apps).

Подключаем это приложение в urls.py своего проекта:

Urlpatterns = patterns("", ... (r"^profiles/", include("profiles.urls")), ...)

и в settings.py :

INSTALLED_APPS = (... "profiles",)

Добавляем таблицы этого приложения и свою таблицу профайлов в базу:

[~]$ python manage.py syncdb

Осталось сделать шаблоны. Приложение profiles использует четыре штуки. Их имена по умолчанию:

  • profiles/create_profile.html
  • profiles/edit_profile.html
  • profiles/profile_detail.html
  • profiles/profile_list.html

За что они отвечают, понятно из их имен. Написание шаблонов для отображения профайла юзера (profile_detail.html ) и списка профайлов (profile_list.html ) оставим в качестве упражнения для заинтересованных читателей этого поста.

А вот шаблоны создания и редактирования своего профайла юзером сделаем. Для простоты и краткости сделаем их одинаковыми.

В каталоге, указанном в параметре TEMPLATE_DIRS файла settings.py , создаем подкаталог profiles, а в нем шаблоны edit_profile.html и create_profile.html с таким вот (например) содержанием (код кривой отображается, видно из-за экранирования html, как правильно html сюда вводить - непонятно):

{% extends "base.html" %} {% block content %} {% csrf_token %} {{ form.as_p }} /> {% endblock %}

Предполагается, что шаблон base.html с основным html-кодом страниц сайта у вас есть.

Лирическое отступление. Я использую для регистрации юзеров еще одно приложение того же автора - registration . Профайл юзера создается автоматически по сигналу от этого приложения при активации нового юзера на сайте. Так что, лично мне шаблон создания нового профайла вообще не нужен.

Готово! Логинимся каким-нибудь юзером на свой сайт, переходим в браузере по адресу mysite.ru/profiles/edit/ упс…

На станице редактирования профайла только одно поле about из нашей расширенной модели. Имя и фамилию, которые хранятся во встроенной модели, нужно редактировать в админке. Хорошо бы сделать так, чтобы юзер на одной странице мог редактировать имя, фамилию и заметку о себе.

Использованное нами приложение profiles автоматически создает форму редактирования профайла на основе модели, указанной в параметре AUTH_PROFILE_MODULE файла settings.py . А в этой модели у нас единственное поле about (служебное связывающее поле user отбрасывается). Но это приложение позволяет передавать своим функциям-представлениям доп.параметы, среди которых есть параметр form_class , задающий класс формы, используемый для редактирования профайла. Этой фичей и воспользуемся.

Чтобы не изменять элементы внешнего приложения, добавми в urls.py своего проекта строчку перед инклудом урл приложения profiles. Эта строчка перехватит обращение при запросе на редактирование профайла и вместо вызова представления, предоставляемого profiles по умолчанию, вызовет представление с нужным доп.параметром.

Соответсвующий фрагмент urls.py проекта должен выглядеть как-то так:

Urlpatterns = patterns("", ... (r"^profiles/edit/$", "profiles.views.edit_profile", {"form_class": forms.ProfileForm}, "profiles_create_profile"), (r"^profiles/", include("profiles.urls")), ...)

Теперь нужно добавить определение класса формы ProfileForm в файл forms.py проекта. Идея заключается в том, что мы

  • сабклассим форму редактирования профайла на основе модели,
  • добавляем два поля для имени и фамилии юзера,
  • при создании экземпляра формы запоминаем экземпляр модели профайла, передаваемый в параметре instance ,
  • считываем из обьекта профайла связанный обьект user и инициализируем значениями first_name/last_name два поля нашей формы,
  • при сохранении модели (метод save ) присваиваем значения этих полей соотв.полям обьекта user и сохраняем его вместе с нашим профайлом.

Import django class ProfileForm(django.forms.ModelForm): first_name = django.forms.CharField(max_length=30, required=False) last_name = django.forms.CharField(max_length=30, required=False) def __init__(self, *args, **kwargs): # получаем обьект профайла self.prof = kwargs.get("instance", None) initial = {"first_name": self.prof.user.first_name, "last_name": self.prof.user.last_name} # в два поля нашей формы помещаем значения соотв.полей из модели user kwargs["initial"] = initial super(ProfileForm, self).__init__(*args, **kwargs) class Meta: # форма для нашей модели профайла model = models.UserProfile # для красоты, чтобы поля в форме шли в правильном порядке fields = ("first_name", "last_name", "about") def save(self, commit=True): super(ProfileForm, self).save(commit) if commit: self.prof.user.first_name = self.cleaned_data["first_name"] self.prof.user.last_name = self.cleaned_data["last_name"] self.prof.user.save()

Теперь при редактировании своего профайла по адресу mysite.ru/profiles/edit/ залогиненный юзер на одной страничке может редактировать свои имя, фамилию, и заметку ‘о себе’. При этом имя/фамилия сохраняются во встроенной модели django.contrib.auth.models.User в полях first_name/last_name , а заметка ‘о себе’, в поле about нашей модели UserProfile .

So you’ve just purchased an HTML template and now you have to customize it before you can put it online, but you’re not experienced with code so you’re not sure how to go about it. Well, rest easy, because in this tutorial we’re going to step you through the entire process.

We’re going to be working off the assumption you’ve never seen a line of HTML before, let alone edited one, so no matter how new you are to working with code you’ll be shown exactly what to do every step of the way.

Let’s start at the very beginning.

What is HTML?

Technically speaking the answer to this question is “Hyper Text Markup Language ”. However, for the purposes of customizing a template, you can consider HTML as a series of opening and closing tags like this:

Tags are indicated with < and > signs, and the closing tag always includes a / . Pairs of tags have content in between them like this:

John Smith, Front End Developer

Sometimes, however, there are also stand alone tags, with no closing partner, like this:

Different HTML tags make different types of content appear on a web page. The above example of

tags would create a large heading reading “John Smith, Front End Developer”, and the example tag would make the image file “mypic.jpg” appear on the page.

To edit an HTML template all you need to know is which tags represent the parts of the page you want to change, how to find them in the code, and how to edit them so they show what you want.

Get Yourself a Code Editor

Yes, it’s completely possible to edit HTML in Notepad or a similar program, but things will go much more smoothly for you if you use a proper code editing app. One of the main reasons is you’ll get colored highlighting of your code, as you’ll see shortly, which will make it much easier to read and edit.

Download and View Your HTML Template

Download the template you’ve purchased–in the case of this tutorial we’ll be using this “Clean CV ” template to demonstrate.

Most HTML templates will come in a ZIP file - if so, go ahead and extract yours now. Then look around inside the template’s folders until you find the “index.html” or “index.htm” file.

In our example CV template the “index.html” file is found in the “01.html-website” directory.

Now, open that file up in Chrome. Even if Chrome isn’t your default or preferred browser please use it anyway, because we’re going to be working with some tools it has in-built to help you with the editing process.

Identify the Parts You Want to Change

If this is your first time editing a template, try not to get drawn into the idea of tweaking the colors and layout just yet. To do that you have to dig into CSS, the language responsible for page styling. It’s a good idea to focus on one thing at a time when you’re new to template customization, and HTML is the best place to start.

To get the ball rolling, take a look at your template in Chrome and figure out which written elements and images on the page you need to change. If you’d like, you can prepare a list so you can go through and check each item off as you make your edits.

In the case of our CV template we want to change:

  • Profession
  • Personal picture
  • Social media links
  • Contact information
  • CV sections: “Professional Profile”, “Work Experience”, “Technical Skills” and “Education”
  • Copyright message

Now we have a list of items to change, we can set about locating their corresponding HTML tags in the code. Let’s start with the name.

Find the Tag in the Inspector

Right-click on the name, which reads “John Smith” by default, and select Inspect :

A panel like this should open in your browser:

The “Inspection” panel

This panel gives you an interactive way of looking at the code. Hover your mouse over the line that shows

...

(heading level 1 tags) and you should see the name section of the template highlighted as you see in the screenshot above.

By hovering your mouse over different lines of code and seeing which areas of the page light up, this panel helps you to figure out which code corresponds with what element. You just keep hovering over different lines of code until the part you’re looking for lights up.

Now expand the h1 tags by clicking the little triangle to their left and you should see the content in between them, i.e. John Smith Front End Developer .

This wording matches up with what you see on screen, so you know you have found the right part of the code.

Edit the Tag in HTML

It’s now time to open up your HTML file for editing. Open the “index.html” file in Sublime Text and you should see something like this:

You want to find the code in here that matches what you saw in the Chrome inspector. Scroll through until you find it on lines 61 - 64.

Now you can edit the content in between the tags to change the name and profession to your own. First, edit “John Smith” to your own name:

Then, in between the tags, change “Front End Developer” to your own profession.

Save your file then refresh the template in Chrome. You should see your changes appear like so:

Repeat to Edit Other Content

Now you have the basic process down:

  1. Inspect the content you want to change
  2. Identify the corresponding tags
  3. Locate those tags in your HTML file
  4. Edit the code to suit

Let’s repeat the process to edit the rest of the content we want to customize.

Add Your Own Image

Next we’ll add our own image to the left of the name and profession area. Right-click the image and inspect it, and note the corresponding tag:

You can see in the inspector window this line is directly above the lines we just changed:

Go to your HTML file and locate the tag on line 59:

For this tag, you’ll need to change the value of the src attribute you see inside the img tag. You do this by editing what’s in between its quotation marks. You’ll be changing it to the file name and location of your own image.

Grab an image of yourself that’s 150px by 150px in size, (ignore that the filename there says 140x140.png, the size is actually 150x150).

Drop your image into the “_content” subfolder; it’s in the same folder as your “index.html” file.

Now, in your HTML file, change the value of the src attribute, replacing “140x140.png” with the file you just added to the “_content” subfolder. Be sure to check the file extension you type out is the same as the one on your file e.g. “png” / “jpg”:

Save your file, refresh Chrome, and you should see your new picture show up:

Edit Social Media Links

Now let’s edit the links on the social media icons in the top right corner of the template. Just like before, right-click one of the icons and inspect it. In the window, look at the line above the one that’s highlighted and you’ll see it includes the text “facebook-icon”. We’re going to use this to find the code in our HTML file.

Back in Sublime Text, press CTRL + F and run a find for “facebook-icon”. You should find it on line 75.

The a tag on line 75 is what creates the link on the icon, and the href attribute you see inside it determines where that link will go. You’ll need to change the value of that href attribute to your Facebook URL (for example: https://www.facebook.com/mylink).

Replace the # that’s there by default with your URL. Then do the same thing for Twitter on line 79, Google+ on line 83 and LinkedIn on line 87.

If there is an icon you’d like to remove entirely, highlight its link starting at the opening tag and finishing at the closing tag, then delete that code.

Now save and refresh your site, then when you click the links they should go off to the correct location.

Edit Contact Information

Next up let’s change the contact information right below the social icons.

Start by inspecting the word “Email” so we can find where this contact information section starts in the code. Take note of the line of code you’ve highlighted, and the line below that so you can match it in your HTML file.

In Sublime Text, press CTRL + F again and this time search for “Email”. You need to locate the instance of the word “Email” which is surrounded by code matching what you saw in the inspector window.

You’ll find it on line 94. Highlight the default email address “[email protected]” in the two locations on that line:

Then replace it with your own email address. On the next line you can also replace the phone number with your own, and on the line below that you can replace the web address with your own:

Edit CV Sections

Now let’s go ahead and start editing the main CV sections of the template. There are a few parts to these sections, so we’re going to start by inspecting each of them so you’ll know what to look for in your code. This will also be a chance for you to learn a little more about moving through the inspector window to find different parts of your site.

Scroll down to the “Professional Profile” section, right-click in the paragraph of text and inspect it.

In the inspector you’ll see it has highlighted a p tag–this tag is responsible for creating paragraphs in your text.

Next up, we want to know what a whole section of text in a CV section looks like in code, not just individual paragraphs. In the inspector window, click on the line of code above the paragraph you just inspected and you should see all the text light up:

This tells you that each section of code is wrapped in the tags

...
. A div is short for a division , and these tags are used to control layout and styling.

Now inspect the CV section’s title, “Professional Profile”:

At first, all you’ll see is another set of div tags. This is because the actual heading is nested in between these tags.

Hit that little triangle on the end of the line to expand it and see its contents, then do the same again on the next line until you see the “Professional Profile” text you’re looking for. You’ll find it wrapped in

...

tags, which create a level 2 heading:

Now we know what the code looks like for every part of this CV section, we can go back to Sublime Text and start editing it.

Position your cursor right at the top of your HTML document so you can start searching from the top. Press CTRL + F and search for “cv-item”. Keep looking until you find the instance of of the code

that’s right after the

Professional Profile

code you just identified.

Now you can replace the text for the Professional Profile section with your own. Wrap each paragraph of your text with tags.

When you’re done, make sure the opening paragraph tag of your final paragraph of the section includes the attribute class with the value last , like this: . This applies a layout styling class from the template’s CSS that will make sure that the spacing under the section of text is handled correctly.

If you save your HTML document and refresh your site you should see everything in the top two sections has been customized.

Now we can move on to editing the remaining CV item sections in the same way we just did with the “Professional Profile”.

Inspect each part of each section to familiarize yourself with the code that you should look for in order to edit them.

Inspect a job title:

Inspect a job period:

Inspect a bullet list:

Use the same approach as you did to edit the “Professional Profile” section to edit the content of the remaining CV sections. To edit job titles, job periods or bullet lists find the code that matches what you saw in the inspector window, just like you’ve done with each edit so far.

Use p tags to create paragraphs, and as with the "Professional Profile" section, if you’re ending a section with a paragraph make sure its

Tag includes class="last" , i.e. .

Note : if you want to add new CV sections, or remove existing ones, you’ll need to use the inspector to find the code tags that wrap the entire section.

In this example you see the whole section is wrapped with the tags

...
.

In your code you can now find that entire block of code and either copy and paste it to create a new item, or delete the whole lot if you want to get rid if it.

Edit Copyright Message

With your CV sections edited we’re down to the last item on our list of changes; the copyright message in the footer. Once again we’ll be using the same process. Right-click the copyright message and inspect it:

Then find the matching code in your HTML and edit it with the current year and your own name:

And You’re Done!

Well done! You’ve just fully customized this HTML template to show your own content. I hope you’re now feeling confident to take on more code customization in the future.

The template we worked on might be a relatively simple one, but remember the process for editing is always the same, no matter how complicated a template might seem. Just inspect the template and identify the code for the part you want to change, then find that code in your HTML file and edit it.

When you’re editing, if you see an HTML tag you don’t understand, don’t let that hold you back. There’s endless amounts of information online to help you learn what each and every one does.

For some extra help along the way, check out these great learning guides.

I have put a section on my website to fill a form of userprofile called profile.html . I have on this moment this models.py to display this information on my admin panel:

I want to enable the possibility of edit this information per user on their respective profile, thereby i can audit the user profile information per user in my admin panel (localhost:8000/admin) what is the good form to create the respective view and it url?

This is my urls.py actually (This isn"t the main urls.py, is an especial urls.py for my app and lack the url for profile)

From django.conf.urls import patterns, include, url urlpatterns = patterns("", url(r"^$","dracoin.apps.home.views.index" ,name="vista_principal"), url(r"^landing/$","dracoin.apps.home.views.landing" ,name="vista_aterrizaje"), url(r"^shop/page/(?P.*)/$","dracoin.apps.home.views.shop" ,name="vista_tienda"), url(r"^card/(?P.*)/$","dracoin.apps.home.views.singleCard",name="vista_single_card"), url(r"^contacto/$","dracoin.apps.home.views.contacto" ,name="vista_contacto"), url(r"^login/$","dracoin.apps.home.views.login_view",name="vista_login"), url(r"^logout/$","dracoin.apps.home.views.logout_view",name="vista_logout"), url(r"^registro/$","dracoin.apps.home.views.register_view",name="vista_registro"),

This is my models.py for profile:

From django.db import models from django.contrib.auth.models import User def url(self,filename): ruta = "MultimediaData/Users/%s/%s"%(self.user.username,filename) return ruta class userProfile(models.Model): name = models.CharField(max_length=30, default="") user = models.OneToOneField(User) photo = models.ImageField(upload_to=url) email = models.EmailField(max_length=75) def __unicode__(self): return self.user.username

My views.py (lack the userProfile view)

From django.shortcuts import render_to_response from django.template import RequestContext from dracoin.apps.synopticup.models import card from dracoin.apps.home.forms import ContactForm,LoginForm,RegisterForm from django.core.mail import EmailMultiAlternatives from django.contrib.auth.models import User from dracoin.settings import URL_LOGIN from django.contrib.auth import login,logout,authenticate from django.http import HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.contrib.auth.decorators import login_required def index(request): return render_to_response("home/index.html",context_instance=RequestContext(request)) @login_required(login_url=URL_LOGIN) def landing(request): return render_to_response("home/landing.html",context_instance=RequestContext(request)) @login_required(login_url=URL_LOGIN) def shop(request,pagina): lista_tarj = card.objects.filter(status=True) paginator = Paginator(lista_tarj,5) try: page = int(pagina) except: page = 1 try: tarjetas = paginator.page(page) except (EmptyPage,InvalidPage): tarjetas = paginator.page(paginator.num_pages) ctx = {"tarjetas":tarjetas} return render_to_response("home/shop.html",ctx,context_instance=RequestContext(request)) @login_required(login_url=URL_LOGIN) def singleCard(request,id_tarj): tarj = card.objects.get(id=id_tarj) ctx = {"card":tarj} return render_to_response("home/singleCard.html",ctx,context_instance=RequestContext(request)) @login_required(login_url=URL_LOGIN) def contacto(request): info_enviado = False # Define si se envio la informacion o no email = "" titulo = "" texto = "" if request.method == "POST": formulario = ContactForm(request.POST) if formulario.is_valid(): info_enviado = True email = formulario.cleaned_data["Email"] titulo = formulario.cleaned_data["Titulo"] texto = formulario.cleaned_data["Texto"] # Configuracion de enviado de correos vis hotmail to_supp = "[email protected]" html_content = "Informacion recibida


***Mensaje***

%s



%s

%s"%(titulo,email,texto) msg = EmailMultiAlternatives("Correo de Contacto",html_content,"[email protected]",) msg.attach_alternative(html_content,"text/html") # Contenido definido como html msg.send() else: formulario = ContactForm() ctx = {"form":formulario,"email":email, "titulo":titulo, "texto":texto, "info_enviado":info_enviado} return render_to_response("home/contacto.html",ctx,context_instance=RequestContext(request)) def login_view(request): mensaje = "" if request.user.is_authenticated(): return HttpResponseRedirect("/") else: if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): next = request.POST["next"] username = form.cleaned_data["username"] password = form.cleaned_data["password"] usuario = authenticate(username=username,password=password) if usuario is not None and usuario.is_active: login(request,usuario) return HttpResponseRedirect(next) else: mensaje = "user or password aren"t correct" next = request.REQUEST.get("next") form = LoginForm() ctx = {"form":form,"mensaje":mensaje,"next":next} return render_to_response("home/login.html",ctx,context_instance=RequestContext(request)) def logout_view(request): logout(request) return HttpResponseRedirect("/") def register_view(request): form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): first_name = form.cleaned_data["first_name"] usuario = form.cleaned_data["username"] email = form.cleaned_data["email"] password_one = form.cleaned_data["password_one"] password_two = form.cleaned_data["password_two"] u = User.objects.create_user(first_name=first_name,username=usuario,email=email,password=password_one) u.save() return render_to_response("home/thanks_register.html",context_instance=RequestContext(request)) else: ctx = {"form":form} return render_to_response("home/register.html",ctx,context_instance=RequestContext(request)) ctx = {"form":form} return render_to_response("home/register.html",ctx,context_instance=RequestContext(request))

Def edit_profile(request): user = request.user user_profile = user.userprofile if request.method == "POST": user_profile_form = userProfile(request-POST) if user_profile_form.is_valid(): update user profile else: user_profile_form = userProfileForm(instance=user_profile) variables = RequestContext(request,{"user_profile_form" : user_profile_form}) return render_to_response("home/edit_profile.html", variables)