Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda