Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!