Инфернальный edit profile html view. Расширение профиля пользователя django

User-agent styles are displayed against a different background, and the link to the filename and line number contains the prefix (user agent) :

element {} rule

The element {} rule at the top of the rules list isn"t actually a CSS rule. It represents the CSS properties assigned to the element via its style attribute.

Starting in Firefox 52, this also gets the target icon: , giving you a convenient way to highlight the currently selected element in the page.

Filtering rules

There"s a box at the top of the Rules view labeled "Filter Styles":

As you type:

  • any rules which don"t contain the typed string at all are hidden
  • any declarations which contain the typed string are highlighted

Click the "X" at the end of the search box to remove the filter.

While in the Rules view, you can press Ctrl / Cmd + F to focus the search field. Once you"ve typed in a filter, you can press Esc to remove it again.

Strict search

By default, the search box highlights all declarations which contain any part of the string. For example, searching for "color" will highlight declarations containing border-bottom-color and background-color as well as just color .:

If you enclose the search query in ticks, like this: `color`, the search is restricted to exact matches:

Expanding shorthand properties

If you set one of these pseudo-classes for a node, an orange dot appears in the markup view next to all nodes to which the pseudo-class has been applied:

Link to CSS file

At the top right of each rule, the source filename and line number is displayed as a link: clicking it opens the file in the Style Editor .

You can copy the location of the source file: right-click the link and select "Copy Location".

Overridden declarations

If a CSS declaration is overridden by some other CSS rule with a greater weight, then the declaration is shown with a line through it.

Overridden declarations have a funnel next to them. Click the funnel to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the complete cascade for the given property.

This makes it easy to see which rule is overriding the declaration:

View @media rules for Print

Beginning with Firefox 68, you can toggle the display into a mode that emulates @media rules for print.

When on, any rules defined for printing the page will be displayed similar to the "Print Preview" mode that many word processing applications provide.

Examine computed CSS

To see the complete computed CSS for the selected element, select the Computed panel in the righthand pane. This panel shows the calculated value that each CSS property has for the selected element:

You can Tab through them to select them, and from Firefox 49 onwards, you can find more information about these properties - pressing F1 on a selected property will open up its MDN reference page.

Clicking the arrow next to the property name (or pressing Enter or Space while it is selected) shows the rule that set this value, along with a link to the source filename and line number:

By default, this view only shows values that have been explicitly set by the page: to see all values, click the "Browser styles" box. You can Tab through the filenames/line numbers; pressing Enter / Return will open up the relevant file at that point in the Style Editor .

Typing in the search box performs a live filtering of the list, so, for example, if you just want to see font-related settings, you can type "font" in the search box, and only properties with "font" in the name will be listed. You can also search for the values of properties: to find the rule responsible for setting the font to "Lucida Grande", type that in the search box.

While in the Computed view, you can press Ctrl / Cmd + F to focus the search field. Once you"ve typed in a filter, you can press Esc to remove it again.

Edit rules

If you click on a declaration or a selector in the Rules view you can edit it and see the results immediately. You can also Tab through the different existing properties and values, and start editing them by pressing Enter or Space . To add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace).

As you start typing a property name, you"ll see a list of autocomplete suggestions. Press Tab to accept the current suggestion or Up and Down to move through the list. The default choice is the most common property that starts with the letters you"ve typed. For example, here the user has typed "c" and the default choice is "color":

If you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the declaration.

Edits that you make in the Rules view are reflected in the Style Editor , and vice versa. Any changes you make are temporary: reloading the page will restore the original styling.

While you"re editing CSS, the context menu you"ll see is the normal one for working with editable text:

CSS variable autocompletion

In addition, hovering over a CSS variable name brings up a tooltip showing what color value is stored in that variable (bug 1431949).

Editing keyboard shortcuts

You can use the arrow and page up/down keys (along with others) to increase/decrease numeric rules while editing:

  • The Up arrow will increment values by 1 - "1px" will change to "2px", for example.
  • Shift + Up / Down will increment values by 10.
  • Alt + Up / Down will increment values by 0.1. Please note that in Firefox 60 this combination changed to Ctrl + Up / Down on Linux and Windows to avoid clashes with default OS-level shortcuts (see bug 1413314). It stayed the same on Mac - Ctrl + Up on macOS is the default shortcut for showing Mission Control.
  • Shift + Page up / Page down will increment values by 100.

Track changes

When you are editing the rules in the rules view, you can see the changes you have made in the Changes pane. (Firefox 65 and later)

Note: You can view changes made to the rules view only. If you edit the CSS using the Style Editor, the changes will not be shown in the changes pane.

Also remember, as noted above, that changes you make to the CSS rules are temporary and will be reset if you reload the page.

Beginning in Firefox 67, if you are satisfied with the changes you have made, you can copy the new settings to page the edited rule into your stylesheet. Right-click on the changes panel and select Copy Rule from the context menu.

The Copy Rule command copies the entire element, class, or id definition, including any unchanged rules and the rules that describe your changes. For example, copying the changes in the preceding image, you get the following:

Text-content p { box-sizing:border-box; max-width:24rem; text-decoration: underline; color: cadetblue; font-weight: bold; }

Add rules

You can add new rules in the Rules view. Just right-click to show the context menu and select "Add rule". This will add a new CSS rule whose selector matches the currently selected node.

There"s also a button that enables you to do the same thing:

Copy rules

To copy rules, and pieces of rules, use one of the following context menu items in the Rules view:

  • Copy Rule
  • Copy Selector
  • Copy Property Declaration
  • Copy Property Name
  • Copy Property Value

See also

  • Complete list of Page Inspector Keyboard shortcuts .
  • The Inspector also includes a number of specialized tools for working with particular CSS features, such as colors, fonts, and animations. To read about these see the list of

Избитая задача: сделать профайл пользователя, расширяющий встроенную модель . Допустим, нужно добавить в профайл юзера поле 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 .

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.

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)


Top