R
R
RussianGuf2021-01-21 14:06:13
Django
RussianGuf, 2021-01-21 14:06:13

How to not save empty values ​​in django form?

Good afternoon, on the site I made the function of adding a telegram address. The addition itself is not mandatory, so there was a problem when the form is empty and the user presses "save settings", then an empty line is saved in the database, which erases the previous one. Question - How to disable the ability to save an empty string if there is already a string in the database, but not including the field in the required fields or how to add the html value tag to the string with the string already saved from the database in the input field.

views

from django.shortcuts import render
from .forms import Telegramform
from .models import Profile
# Create your views here.

def settingsprofiles(request):
    error = ''
    if request.method == "POST":
        form = Telegramform(request.POST)
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.id = request.user.id
            profile.email = request.user.email
            w = Profile.objects.get(id=profile.id)
            profile.btcadress = w.btcadress
            form.save()
        else:
            error = "Ошибка, телеграм не был изменен"
    form = Telegramform()
    data = {
        'form': form,
        'error': error,
    }
    return render(request, 'profiles/settings.html', data)


html
<div class="bg-white p-5 rounded shadow ml-auto mr-auto mt-5 ">

            <div class="text-center">
                <h1>Ваш профиль</h1>
            </div>
            <hr>
            <div class="text-center">
                <h1>Настройки профиля</h1>
            </div>
        <form method="post">
           {% csrf_token %}
            <label class="fw-normal mt-1">Телеграм (необязательно):</label>
            {{ form.telegram }}
                 <span>{{ error }}</span>
            <button class="btn btn-lg btn-success mt-3" type="submit"><i class="fas fa-save"></i> Сохранить</button>
       </form>
    </div>

forms
from .models import Profile
from django.forms import ModelForm, TextInput

class Telegramform(ModelForm):
    class Meta:
        model = Profile
        fields = ['telegram']
        widgets = {
            'telegram': TextInput(attrs={
                'class': 'form-control',
                'placeholder': '@Телеграм',
            }),
        }

models
class Profile(models.Model):
    user = models.OneToOneField(User, verbose_name='Пользователь', on_delete=models.CASCADE)
    telegram = models.CharField("Телеграм", blank=True, null=True, max_length=50)
    email = models.CharField("Почта", blank=True, null=True, max_length=50)
    btcadress = models.CharField("Биткоин адресс", blank=True, null=True, max_length=50)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-01-21
@bacon

Because for editing I use the instance parameter of the form, and do not fence my bicycles.
ZY what for to keep mail in two places profile.email = request.user.email?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question