Python Django forms replaces old inputs - python

I am currently trying to impliment a registration form but everytime I test it out, the new registrant replaces the old registration. So I am unable to have more than one user at a time.
any help would be great because I do not know what to do. Thanks.
My views:
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
new_user = bitcoinUser(first_name=cd['first_name'],
last_name=cd['last_name'],
phone_number=cd['phone_number'])
new_user.save()
my models:
class bitcoinUser(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone_number = models.IntegerField(primary_key=True)

I honestly don't know why that didn't work (I think it is because you are saving the object 'new_user' and not the form), but i will recommend the way that i do forms in Django:
models.py:
from django.forms import ModelForm
class Bitcoinuser(models.Model):
first_name = models.CharField(max_length=36)
last_name = models.CharField(max_length=36)
phone = models.IntegerField(primary_key=True)
def __str__(self):
return self.name
class BitcoinuserForm(ModelForm):
class Meta:
model = Bitcoinuser
fields = ['first_name', 'last_name', 'phone']
views.py:
from .models import BitcoinuserForm
def get_bitcoinuser(request):
if request.method == 'POST':
form = BitcoinuserForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
phone = form.cleaned_data['phone']
form.save()
return HttpResponseRedirect('/database/')
else:
form = BitcoinuserForm()
return render(request, 'appname/get_bitcoinuser.html', {'form': form})
It's simple, straigthfoward and works fine.

Related

Django save form with foreign key

I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database.
models.py
class User(AbstractUser):
pass
def __str__(self):
return self.username
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, default="")
first_name = models.CharField(max_length=200, default="")
last_name = models.CharField(max_length=255, default="")
class Meta:
verbose_name_plural = "Detail"
def __str__(self):
return self.first_name+ " "+self.last_name
forms.py
class Details(forms.ModelForm):
class Meta:
model = Detail
fields = "__all__"
widgets={
"user": forms.TextInput()
}
views.py
def details(request):
if request.method =="POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.user = request.user
detail.first_name = detail.first_name.lower()
detail.last_name = detail.last_name.lower()
detail.save()
return redirect("admin:index")
else:
form = Details(initial={"user":request.user.username})
return render(request, "details.html", {"form":form})
You need to exclue user field from ModelForm like this
form.py
class Details(forms.ModelForm):
class Meta:
model = Detail
fields = "__all__"
exclude =["user"]
views.py
def details(request):
if request.method =="POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.user = request.user
detail.first_name = detail.first_name.lower()
detail.last_name = detail.last_name.lower()
detail.save()
return redirect("admin:index")
else:
form = Details()
return render(request, "details.html", {"form":form})

How to raise error for email field if user is trying to pass just few letters

How can I rise the error and information, if user is puting only "dummy date" without "#"?
Email model is email = models.EmailField(max_length=254) but is only preventing passsing empty field, and nothing else. Can someone advice ?
def addContact(request):
form = ContactForm
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
Forms:
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
Models:
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number = models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
If you use EmailField then it has a built-in validator. Here is the code (https://docs.djangoproject.com/en/3.1/ref/validators/#emailvalidator)
You can use this validator to check the user input.
Here is the source code: https://docs.djangoproject.com/en/2.2/_modules/django/core/validators/#EmailValidator

How can I add custom fields when creating a sign up form using Django form?

I am very much a beginner to Django and just Python overall, but I am trying to create a relatively simple web app and I seem to be running into some obstacles.
I would like to add custom fields to my Django UserCreationForm like first name, last name, email and ID number? Should I create a separate Profile model and if so how should I do that, or is there some other way to achieve this?
Like I said, I am a beginner so I would appreciate as much detail as possible!
For first name, last name and email fields you won't need to do anything. But for ID I suggest you create a separate model, that's really simple actually!
models.py
from django.contrib.auth.models import User
class IdNumber(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
id_number = models.TextField(max_length=9)
forms.py
from django.contrib.auth.models import User
class SignUpForm(forms.ModelForm):
id_number = forms.CharField(max_length=9, required=True)
password = forms.CharField(max_length=15, required=True)
password_confirm = forms.CharField(max_length=15, required=True)
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', 'username', 'password']
def clean(self):
cleaned_data = super(SignUpForm, self).clean()
password = cleaned_data.get('password')
password_confirm = cleaned_data.get('password_confirm')
if password != password_confirm:
raise forms.ValidationError('Passwords do not match!')
views.py
from .models import IdNumber
from .forms import SignUpForm
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
id_number = form.cleaned_data['id_number']
user.set_password(password)
id_model = IdNumber(user.id)
id_model.user = user
id_model.id_number = id_number
id_model.save()
form.save()
return HttpResponseRedirect('some_url')
else:
return render(request, 'your_app/your_template.html', {'form': form})
else:
form = SignUpForm()
return render(request, 'your_app/your_template.html', {'form': form}

Django simple queryset in form field

I couldn't find any solution in previous answers so i'm here asking how to register the result of a form field made by a queryset. Maybe i'm doing wrong something simple here how ever my model are:
#python_2_unicode_compatible
class Choice(models.Model):
choice_text = models.CharField(max_length=100)
def __str__(self):
return self.choice_text
#python_2_unicode_compatible
class Contatto(models.Model):
contatto_choice = models.ForeignKey(Choice, on_delete=models.PROTECT)
phone_number = models.CharField(max_length=12)
email = models.CharField(max_length=100)
text = models.CharField(max_length=250)
def __str__(self):
return self.email
class ContactForm(ModelForm):
class Meta:
model = Contatto
fields = ['contatto_choice', 'phone_number','email','text']
My forms.py is:
class ContactForm(forms.Form):
contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all())
phone_number = forms.CharField(max_length=12)
email = forms.CharField(max_length=100)
text = forms.CharField(widget=forms.Textarea, max_length=500)
and my views is:
def contatti(request):
if request.method=="POST":
form = ContactForm(request.POST)
if form.is_valid():
contatto = Contatto()
contatto.phone_number = form.cleaned_data['phone_number']
contatto.email = form.cleaned_data['email']
contatto.text = form.cleaned_data['text']
contatto.contatto_choice = form.cleaned_data['contatto_choice']
contatto.save()
recipients = ['cercaservizi#gmail.com']
send_mail("Contatto Cercaservizi", contatto.phone_number+' '+contatto.email+' '+contatto.text,contatto.email, recipients)
return HttpResponseRedirect('/')
else:
form = ContactForm()
return render(request, 'form.html', {'form': form})
The view of the submitted form complains about the fact that a contatto_choice should be an instance of a choice i cannot find any tutorial about how to solve this. If you could help it would be appreciated.
Edit Your ContactForm
class ContactForm(ModelForm):
contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all())
class Meta:
model = Contatto
fields = ['contatto_choice', 'phone_number','email','text']
and you will not need other form

Django Forms Updating Record Issues

I am getting an error when I try to update a record in Django using a form. I get an error that a record with that number already exists. Below is my model and view. This is really driving me nuts. I though that Django would just update the record instead of trying to write a new record.
class Report(models.Model):
report_number = models.CharField(max_length=4, unique=True)
detected = models.CharField(max_length=40)
computer_name = models.CharField(max_length=40)
username = models.CharField(max_length=15)
cab_date_time = models.CharField(max_length=40)
collector = models.CharField(max_length=40)
addresses = models.TextField()
fault = models.CharField(max_length=40)
known_malware = models.TextField(default='No')
collected_files = models.TextField(default='None')
registry_keys = models.TextField()
service_number = models.CharField(max_length=15, blank=True)
notes = models.TextField(blank=True)
sample_requested = models.CharField(max_length=4, blank=True)
action = models.CharField(max_length=35, blank=True)
And View
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
form = ReportForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
return render(request, 'reports/report.html', {'form': form})
Here is the Form defination
from django.forms import ModelForm
from reports.models import Report
class ReportForm(ModelForm):
class Meta:
model = Report
exclude = ('moderator',)
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
if request.method == 'POST':
form = ReportForm(request.POST, instance=instance)
if form.is_valid():
form.save(force_update=True)
return HttpResponseRedirect('/')
else:
form = ReportForm(instance=instance)
return render(request, 'reports/report.html', {'form': form})

Categories

Resources