Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
correct using get_or_create?

To my code, which records a contact from the form and adds it to the db, need to add get_or_create, or write another condition (if there is a contact with such a phone — update, no - add), but i'm do it for the first time, please, I'll be glad to read solution to my problem and a brief explanation ♡

views.py

from django.http import HttpResponse

from django.shortcuts import render,redirect
from django.contrib import messages
from .forms import Forms

def main(request):
form = Forms
if request.method == "POST":
form = Forms(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Form has been submitted')
return redirect('/')

return render(request, 'app/main.html', { 'form':form } )

forms.py

from django.forms import ModelForm
from .models import Form

class Forms(ModelForm):
class Meta:
model = Form
fields = '__all__'

urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls'))

] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


models.py

from django.db import models

class Form(models.Model):
name = models.CharField(max_length=30)
phone = models.CharField(max_length=30)

admin.py

from django.contrib import admin
from .models import Form
'''from django.contrib.admin.models import LogEntry
LogEntry.objects.all().delete()'''
'''for delete actions in admin_panel'''
admin.site.register(Form)

apps.py

from django.apps import AppConfig

class AppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app'

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTE-8">
    <meta name="viewport" content="width, initial-scale=1.0">
<title>CHECK DATA</title>
</head>
<body>
    {% for message in messages %}
        <p>{{message}}</p>
    {% endfor %}
    <form action="" method="post">
    {% csrf_token %}
        <table>
            {{form.as_table}}
            <tr>
                <td colspan="2">
                    <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can implement this with:

def main(request):
    if request.method == "POST":
        form = Forms(request.POST)
        if form.is_valid():
            Form.objects.get_or_create(
                phone=form.cleaned_data['phone'],
                defaults={'name': form.cleaned_data['name']}
            )
            messages.success(request, 'Form has been submitted')
            return redirect('/')
    else:
        form = Forms()
    return render(request, 'app/main.html', { 'form': form })

You must be careful however since this means that a user might edit data of another user. Perhaps it is thus worth to check if the (logged in) user has rights to update that item.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda