I have a problem in the relation between two tables in Sqlite using python/Django

Asked

Viewed 43 times

0

I am making a simple CRUD, using 2 tables, the default user of Django and the citizen I created, I am using a foreinkey username to link the two, but in the form, instead of appearing a username (that is the logged-in user), appears of all registered users.

code models.py

from django.db import models
from django.contrib.auth.models import User


class Cidadao(models.Model):
    nomecompleto = models.CharField(max_length=100)
    endereco = models.CharField(max_length=100)
    email = models.EmailField()
    nomebens = models.CharField(max_length=100)
    numSerie = models.CharField(max_length=100)
    observacao = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.user

code views.py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from cidadania3.forms import CidadaoForm
from cidadania3.models import Cidadao


# Create your views here.
def home(request):
    data = {}
    search = request.GET.get('search')
    if search:
        data['db'] = Cidadao.objects.filter(email__icontains=search, user=request.user)

    else:
        data['db'] = Cidadao.objects.all().filter(user=request.user)
    return render(request, 'index.html', data)


@login_required
def form(request):
    Cidadao.objects.all().filter(user=request.user)
    data = {}
    data['form'] = CidadaoForm()
    return render(request, 'form.html', data)


def create(request):
    form = CidadaoForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('home')


@login_required
def view(request, pk):
    data = {}
    data['db'] = Cidadao.objects.get(pk=pk)
    return render(request, 'view.html', data)


@login_required
def edit(request, pk):
    data = {}
    data['db'] = Cidadao.objects.get(pk=pk)
    data['form'] = CidadaoForm(instance=data['db'])
    return render(request, 'form.html', data)


@login_required
def update(request, pk):
    data = {}
    data['db'] = Cidadao.objects.get(pk=pk)
    form = CidadaoForm(request.POST or None, instance=data['db'])
    if form.is_valid():
        form.save()
    return redirect('home')


@login_required
def delete(request, pk):
    db = Cidadao.objects.get(pk=pk)
    db.delete()
    return redirect('home')

Forms.py code

from django.forms import ModelForm
from cidadania3.models import Cidadao

# Create the form class.
class CidadaoForm(ModelForm):
   class Meta:
      model = Cidadao
      fields = ['nomecompleto', 'endereco', 'email', 'nomebens', 'numSerie', 'observacao', 'user']

inserir a descrição da imagem aqui

In the user part was to be only the registered user (which is the name set in the button above ) Thanks in advance.

Code Urls.py

from django.contrib import admin
from django.urls import path, include
from cidadania3.views import home, form, create, view, edit, update, delete

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('form/', form, name='form'),
    path('create/', create, name='create'),
    path('view/<int:pk>/', view, name='view'),
    path('edit/<int:pk>/', edit, name='edit'),
    path('update/<int:pk>/', update, name='update'),
    path('delete/<int:pk>/', delete, name='delete'),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
]


  • You could update your post with.py urls as well?

1 answer

0

It seems your method form is mistaken. On first call I suggest changing the name of the method to something more intuitive for understanding (e.g. cadas_cidadao)

@login_required()
def cadastro_cidadao(request):
    if request.method == 'POST':
        form = CreateCidadao(request.POST)
        if form.save(request.user):
            return redirect(reverse('core:home'))  # Ou para onde vc quiser retornar
    else:
        cidado_instance = Cidadao.objects.all().filter(user=request.user)
        form = CreateCidadao(instance=cidadao_instance)
    return render(request, 'cidadao.html', {'form': form})

Already cidadao.html would be something like:

{% extends 'base.html'%}

{% load static from static %}

{% block content %}
    <h1>Cidadao</h1>
    <form method="POST">
        {% csrf_token %}
        {% form %}
    </form>
{% endblock content %}

Browser other questions tagged

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