Dinamic url assumes user logged in to visuzaliation

Asked

Viewed 58 times

0

I have a system that when the user is logged in the top menu that is fixed appears the photo and his name, plus the options since he is logged in, so far so good. and I’m using dynamic url to do example, www.mysite.com.br/user so that whether you are logged in or not you can see the user’s profiles, however, when I type this dynamic url, it shows the user and automatically changes the top menu that was logged in by the user of the visited page. let’s say my user name is Mauricio, I’m logged in and up there appears my photo and my name and I’ll see the user profile Roger, when I visualize the profile of Roger, my login up there passes to the of Roger automatically, and I don’t know how to solve this py views.

from django.shortcuts import render, redirect, HttpResponse
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from .tokens import account_activation_token
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from sistema.tokens import account_activation_token
from django.contrib.sites.shortcuts import get_current_site


from .models import (
    Usuario, 
    Negocio
)

from .forms import (
    UsuarioForm, 
    NegocioForm
)

def profile_detail(request, username):
    if User.objects.get(username=username):
        user = User.objects.get(username=username)
        return render(request, "profile.html", {
            "user": user,
        })
    else:
        return render("User not found")


def index(request):
    usuario = Usuario.objects.all()
    form = UsuarioForm()
    data = {'usuario': usuario, 'form': form}
    return render(request, 'index.html', data)

def perfil(request):
    usuario = Usuario.objects.all()
    form = UsuarioForm()
    data = {'usuario': usuario, 'form': form}
    return render(request, 'perfil.html', data)



def cadastro(request):
    usuario = Usuario.objects.all()
    form = UsuarioForm()
    data = {'usuario': usuario, 'form': form}
    return render(request, 'cadastro.html', data)

def cadastro_novo(request): 
    if request.method == 'POST':
        form = UsuarioForm(request.POST, request.FILES)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.usuario.nome = form.cleaned_data.get('nome')
            user.usuario.sobrenome = form.cleaned_data.get('sobrenome')
            user.usuario.email = form.cleaned_data.get('email')
            user.usuario.telefone = form.cleaned_data.get('telefone')
            user.usuario.cidade = form.cleaned_data.get('cidade')
            user.usuario.endereco = form.cleaned_data.get('endereco')
            user.usuario.cpf = form.cleaned_data.get('cpf')
            user.usuario.numero = form.cleaned_data.get('numero')
            user.usuario.bairro = form.cleaned_data.get('bairro')
            user.usuario.cep = form.cleaned_data.get('cep')
            user.usuario.password1 = form.cleaned_data.get('password1')
            user.usuario.data_nascimento = form.cleaned_data.get('data_nascimento')
            user.usuario.pet = form.cleaned_data.get('pet')
            user.usuario.foto = form.cleaned_data.get('foto')
            user.usuario.sexo = form.cleaned_data.get('sexo')
            user.usuario.estado = form.cleaned_data.get('estado')
            user.save()
            current_site = get_current_site(request)
            subject = 'Ative seu registro no PetAqui'
            message = render_to_string('account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            user.email_user(subject, message)
            return redirect('account_activation_sent')
    else:
        form = UsuarioForm()
    return render(request, 'cadastro.html', {'form': form})


def account_activation_sent(request):
    return render(request, 'account_activation_sent.html')


def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.usuario.email_confirmed = True
        user.save()
        login(request, user)
        # return redirect('home')
        return render(request, 'account_activation.html')
    else:
        return render(request, 'account_activation_invalid.html')

def cadastro_negocio(request):
    negocio = Negocio.objects.all()
    form = NegocioForm()
    data = {'negocio': negocio, 'form': form}
    return render(request, 'cadastro_negocio.html', data)

py.models

from django.db import models
from django.core.files.images import ImageFile
from django.core.mail import send_mail
import math
from multiselectfield import MultiSelectField
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from stdimage.models import StdImageField

STATE_CHOICES = (
    ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'),
    ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'),
    ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'),
    ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'),
    ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'),
    ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'),
    ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'),
    ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'),
    ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'),
    ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins')
)

cat = 'https://www.petz.com.br/blog/wp-content/uploads/2017/07/gato02.jpg'
gato = 'https://www.petz.com.br/blog/wp-content/uploads/2017/07/gato02.jpg'
PET_CHOICES = (
    ('dog', 'Cachorro'), ('cat', 'Gato'), ('bird', 'Pássaros'), ('fish', 'Peixes'), ('rep', 'Reptéis'),
    ('horse', 'Cavalos'), ('rat', 'Roedores')
)

SEXO_CHOICES = (
    ('M', 'Masculino'), ('F', 'Feminino')
)


class Usuario(models.Model):
    nome = models.CharField(max_length=50, blank=False)
    sobrenome = models.CharField(max_length=50, blank=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email_confirmed = models.BooleanField(default=False)
    email = models.EmailField(blank=False)
    foto = StdImageField(blank=False, variations={
        'large': (600, 400),
        'thumbnail': (100, 100, True),
        'medium': (300, 200),
    })
    telefone = models.CharField(max_length=20, blank=False, verbose_name="Celular")
    cpf = models.CharField(max_length=19)
    data_nascimento = models.CharField(max_length=8, blank=False, verbose_name="Data de nascimento")
    sexo = models.CharField(default='M', max_length=2, choices=SEXO_CHOICES)
    pet = MultiSelectField(max_length=30, choices=PET_CHOICES, verbose_name="Selecione seus pets")
    endereco = models.CharField(max_length=50)
    numero = models.CharField(max_length=10)
    bairro = models.CharField(max_length=30)
    cep = models.CharField(max_length=25)
    cidade = models.CharField(max_length=30)
    estado = models.CharField(default='RS', max_length=3, choices=STATE_CHOICES)
    password1 = models.CharField(max_length=15, blank=False)

    def __unicode__(self):
        return self.nome

    @receiver(post_save, sender=User)
    def cadastro_novo(sender, instance, created, **kwargs):
        if created:
            Usuario.objects.create(user=instance)
        instance.usuario.save()

    def __str__(self):
        return str(self.nome) + ' - ' + str(self.email) + ' - ' + str(self.telefone)

Forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

cat = 'https://www.petz.com.br/blog/wp-content/uploads/2017/07/gato02.jpg'
gato = 'https://www.petz.com.br/blog/wp-content/uploads/2017/07/gato02.jpg'
PET_CHOICES = (
    ('dog', 'Cachorro'), ('cat', 'Gato'), ('bird', 'Pássaros'), ('fish', 'Peixes'), ('rep', 'Reptéis'),
    ('horse', 'Cavalos'), ('rat', 'Roedores')
)

STATE_CHOICES = (
    ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'),
    ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'),
    ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'),
    ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'),
    ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'),
    ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'),
    ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'),
    ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'),
    ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'),
    ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins')
)
SEXO_CHOICES = (
    ('M', 'Masculino'), ('F', 'Feminino')
)


class UsuarioForm(UserCreationForm):
    nome = forms.CharField()
    sobrenome = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Sobrenome'}))
    email = forms.EmailField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Email Válido', 'id': 'email'}))
    email2 = forms.EmailField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Repita seu email', 'id': 'email2'}))
    cpf = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': '000.000.000-00', 'class': 'cpf'}))
    telefone = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': '(00)0000-0000', 'class': 'phone_with_ddd'}))
    cidade = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Sua cidade'}))
    endereco = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Rua, Av, Estrada'}))
    numero = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'numero', 'class': 'numero'}))
    bairro = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'seu bairro'}))
    cep = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': '00000-000', 'class': 'cep'}))
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Mínimo 8 digitos', 'id': 'password1'}))
    password2 = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': 'Mínimo 8 digitos', 'id': 'password2', 'label': 'Repita a senha'}))
    data_nascimento = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': '00/00/000', 'class': 'data'}))
    pet = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple, choices=PET_CHOICES)
    foto = forms.FileField(
        widget=forms.ClearableFileInput(attrs={'multiple': 'False'}))
    sexo = forms.ChoiceField(choices=SEXO_CHOICES)
    estado = forms.ChoiceField(choices=STATE_CHOICES)

    def __init__(self, *args, **kwargs):
        super(UsuarioForm, self).__init__(*args, **kwargs)
        self.fields["password1"].label = "Repita a senha"
        self.fields["password2"].label = "Repita o email"
        # pode fazer isso com todos os campos

    class Meta:
        model = User
        fields = (
            'username', 'email', 'email2', 'telefone', 'data_nascimento',
            'sexo', 'foto', 'endereco', 'numero', 'bairro',
            'cidade', 'estado', 'cep', 'pet'
        )

py.

from django.conf.urls import url
from django.urls import include, path
from . import views
from django.conf import settings
from django.conf.urls.static import static

from .views import (
    index,
    cadastro,
    cadastro_novo,
    cadastro_negocio,
    activate,
    account_activation_sent,
    perfil,
    profile_detail

)

urlpatterns = [
  url(r'^index/$', index, name='sistema_index'),
  url(r'^cadastro/$', cadastro, name='sistema_cadastro'),
  url(r'perfil/$', perfil, name='sistema_perfil'),
  url(r'^cadastro-novo/$', cadastro_novo, name='sistema_cadastro_novo'),
  url(r'^cadastro-negocio/$', cadastro_negocio, name='sistema_cadastro_negocio'),
  url(r'^account_activation_sent/$', views.account_activation_sent, name='account_activation_sent'),
  url(r'^profile/(?P<username>[\w.@+-]+)/$', views.profile_detail, name='sistema_profile'),
  path('activate/<uidb64>/<token>/', views.activate, name='activate'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

profile html.

{%extends 'bases/base.html' %}
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
{{usuario.id}}
<div class="card text-white bg-primary">
    <div class="card-header">
        <p class="card-text">
            <small class="text-muted">
                <a href="{% url 'sistema_index' %}" class="text-white ">Home /</a>
                <a class="text-white">Perfil </a>
            </small>
            </a></p>
        {{ user.usuario.nome }} {{ user.usuario.sobrenome }}{{ user.usuario.id }}
    </div>
    <div class="card title  ">
        <div class="card-body text-secondary">
            {{ user.usuario.nome}}
            <img src="{{ user.usuario.foto.medium.url}}" class="rounded-circle" width="150" height="150">
            {{ user.usuario.cpf}}
            {{ user}}
        </div>
    </div>
</div>
{% endblock main %}

menu

{% if user.is_authenticated %}
    <ul class="nav navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">Mensagens |</a>
        </li>
        <li class="nav-item">
            <img src="{{ user.usuario.foto.thumbnail.url}}" class="rounded-circle" width="35" height="35">
        </li>
        <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown"
               aria-haspopup="true" aria-expanded="false">
                <img src="{% static 'svg/settings.svg' %}" width="20" height="20" alt="">{{user}} |
            </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                <a class="dropdown-item" href="#">Ver perfil</a>
                <a class="dropdown-item" href="#">Avaliações</a>
                <a class="dropdown-item" href="#">Configurações</a>
                <a class="dropdown-item" href="{% url 'logout' %}"><img src="{% static 'svg/log-out.svg' %}" width="20"
                                                                        height="20" alt="">Sair</a>
        </li>
    </ul>
</div>
{% else %}
<div class="form-row">
    <div class="col">
        <form class="form-inline">
            <a class="btn btn-outline-info btn-sm" href="{% url 'sistema_cadastro_negocio' %}" role="button"> Cadastre
                seu negócio </a>
        </form>
    </div>
    <div class="col">
        <form class="form-inline">

            <a class="btn btn-outline-primary btn-sm" href="{% url 'sistema_cadastro' %}" role="button">
                Cadastre-se </a>
        </form>
    </div>

    <div class="col">
        <form class="form-inline">
            <a class="btn btn-primary btn-sm" href="{% url 'login' %}" role="button"> Entrar </a>
    </div>
    </form>
{% endif %}
  • 1

    Apparently in view.profile_detail you are returning "user" that ends up getting confused with the user logged in user that loads the Infos in the header, no?

  • 1

    in the profile_detail view change "user" to "user_detail" and in the profile.html template as well, I think this way the user of this context will not get confused with the logged in user.

  • It was perfect thanks!!!!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.