Django ModelForm validate if input exists in model - python

I have a model Linea with only one field named numero, wich is a charset (the values of numero are supposed to be numbers) . I want to do a form where the user can search for a value of numero. If the number that the user inputs exists in the database the view will redirect to a template that shows information about that value of numero, but if the value that the user search is not in the database it will throw an error.
I'm very new in Django, and I've searched the way to do it but I can't achieve it.
forms.py
from django import forms
from .models import Linea
class LineaForm(forms.ModelForm):
class Meta:
model = Linea
fields = ('numero',)
models.py
from __future__ import unicode_literals
from django.db import models
class Linea(models.Model):
numero = models.CharField(max_length=2)
def __str__(self):
return self.numero
views.py
from django.shortcuts import render, redirect, reverse
from .forms import LineaForm
from django.http import HttpResponseRedirect
import googlemaps
from datetime import datetime
def lineas(request, template="bustopaplineas.html"):
if request.method == "POST":
form = LineaForm(request.POST)
if form.is_valid():
numero = form.save(commit=False)
linea_numero = str(numero)
return redirect('lineas_detalles', linea_numero=linea_numero)
else:
form = LineaForm()
return render(request, 'bustopapp/lineas.html', {'form': form})
Thanks in advance.

You can check in the Linea table if it exists or not:
Linea.objects.get(numero=input)
In case, it doesn't it will throw an exception

Related

How to put the username of the logged-in user in the databse each time a form is submitted

I have an application where a user can submit a form which goes into the database (POSTGRES).
I want to be able to automatically send the username of the user logged in to the same database, so i can keep track of who is submitting. (I do not want to put a form line with the username, i want this to be dealt with in the back-end).
what I managed to do is get the user-id, but it stays null, and I do not know how to get the username in the database and to complete it at each submission.
I hope I am clear,
thanls guys.
Here is my code
models.py
from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models
class Fertidb(models.Model):
user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
area = models.IntegerField()
plot = models.FileField(upload_to='KML_FILES', blank=True)
def __str__(self):
return f' Parcelles de {self.user.username}'
forms.py
from django import forms
from django.contrib.auth.models import User
from .models import Fertidb
class FertidbForm(forms.ModelForm):
class Meta:
model = Fertidb
labels = {
"plot": "Importez votre fichier KML"
}
fields = ['culture', 'area', 'plot']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User
title = 'FERTISAT'
#login_required
def fertisatmap(request):
mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
if request.method == "POST":
o_form = FertidbForm(request.POST, request.FILES)
if o_form.is_valid():
o_form.save(commit=False)
o_form.user = request.user.username()
messages.success(request, f'Vos informations ont été envoyées')
return redirect('fertisat-map')
else:
o_form = FertidbForm()
context = {'title': title, 'o_form': o_form}
return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})
Try to update your view like so:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User
title = 'FERTISAT'
#login_required
def fertisatmap(request):
mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
if request.method == "POST":
o_form = FertidbForm(request.POST, request.FILES)
if o_form.is_valid():
fertidb = o_form.save(commit=False)
fertidb.user = request.user
fertidb.save()
messages.success(request, f'Vos informations ont été envoyées')
return redirect('fertisat-map')
else:
o_form = FertidbForm()
context = {'title': title, 'o_form': o_form}
return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})
(commit=False) use for creating the model instance without submit to database, then assign current user to your new model instance fertidb.user = request.user and then call .save() to commit your data to database
Btw, mapbox_access_token suppose to stay inside settings.py in case you want to load it from environment variable when deploy production. like so:
settings.py
MAPBOX_ACCESS_TOKEN="pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w"
views.py
from django.conf import settings
...
def fertisatmap(request):
mapbox_access_token = settings.MAPBOX_ACCESS_TOKEN
Hope that helps!
There are two issues here:
1. In your Model, you want a User, but in your form, you are assigning it the username, which I think is a string.
user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
and
o_form.user = request.user.username()
Just change the second line to o_form.user = request.user.
2. You are not saving the user anyway.
You have to save your model again after you assign the user.
Thanks fo the help guys.
#Toan Quoc Ho thank you I made the modifications but I still have a problem.
The database displays the user_id, but I would like it to display the username.
I guess my problem is in the model file. How do I modify the following, so I get the username in the database.
user=deb_models.ForeignKey(User,on_delete)models.CASCADE) puts the user_id -> I would like to have the username. How do I call it ?
models.py
*from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models
class Fertidb(models.Model):
user = db_models.ForeignKey(User, on_delete=models.CASCADE)
culture = models.CharField(max_length=50)
area = models.IntegerField()
plot = models.FileField(upload_to='KML_FILES', blank=True)
def __str__(self):
return f' Parcelles de {self.user.username}'*

How to compare models using id's Django

Can anyone please help in tackling the following problem?
Suppose I have a model named Answer and a form for user input named CheckAnswer.
What I want is that when a particular Question page is openend and the user types the answer, it should get checked with the corresponding answer
The answer from the model can be accessed using the id. but how can i specify the id of question page that opens up and link it to the answer id.
Below are the codes attached
forms.py
from django import forms
from .models import Answer
from django.core.exceptions import ObjectDoesNotExist
class CheckAnswer(forms.Form):
your_answer=forms.CharField(label='Answer')
def clean(self):
cleaned_data=super(CheckAnswer,self).clean()
response=cleaned_data.get("your_answer")
try:
p = Answer.objects.get(id=1,answer__iexact=response)
except Answer.DoesNotExist:
raise forms.ValidationError("Wrong Answer.")
views.py
from django.shortcuts import render,redirect
from django.views.generic import *
from . import models
from django import forms
from .forms import CheckAnswer
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def Arena1(request):
if request.method=='POST':
form = CheckAnswer(request.POST)
if form.is_valid():
return redirect('thanks')
else:
form=CheckAnswer()
return render(request,'levels/arena1.html',{'form':form})
models.py
from django.db import models
from django.contrib.auth import get_user_model
User=get_user_model()
users=User.objects.all()
# Create your models here.
class Answer(models.Model):
name=models.CharField(max_length=10,unique=True)
answer=models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
ordering= ["-name"]

how to fill an author field with current username

I have looked at a lot of different places but none of their solutions work. This is most likely to do them being for older versions of django or my own stupidity. So I am making a blog type of app that for some reason is called reviews instead of blog... anyway I need to automatically fill up an author field with the username of the logged in user. Here is my models.py:
from django.db import models
from django.contrib.auth.models import User
#vars
# Create your models here.
class reviews(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.PROTECT,)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True, blank=True)
and forms.py:
from django import forms
from django.forms import ModelForm
from .models import reviews
from django.contrib.auth.decorators import login_required
class CreatePost_form(ModelForm):
class Meta:
model = reviews
exclude = ['author']
fields = ['title', 'body',]
and views:
from django.shortcuts import render, render_to_response
from .forms import CreatePost_form
from django.http import HttpResponseRedirect
# Create your views here.
def reviewlist(request):
return render
def index(request, ):
return render(request, template_name="index.html")
def CreatePost(request):
form = CreatePost_form(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/reviews/succesfulpost')
return render(request, "reviews/CreatePostTemplate.html", {'form':form})
def succesfulpost(request):
return render(request, "reviews/succesfulpost.html")
def CreatePost(request):
form = CreatePost_form(request.POST)
if form.is_valid():
form.save(commit=False)
form.author = request.user
form.save()
return HttpResponseRedirect('/reviews/succesfulpost')
As simple as that. Rather than actually saving and committing the data, you simply save without committing then you're able to change the value of the excluded field.

Can't assign a value (user id) to a ForeignKey field

I am getting the following error:
Cannot assign "<django.db.models.fields.related.ForeignKey>": "Worry.user" must be a "User" instance.
I trying to assign the id of the current user to an object I have just created.
This is part of my models.py:
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.db import models
class UserForm (ModelForm) :
class Meta:
model = User
class Worry(models.Model) :
user = models.ForeignKey(User) #Many worries to 1 user relation
This is part of my views.py:
from django.db import models
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.models import User
from holaProy.models import UserForm, Worry, WorryForm, Statistics, StatisticsForm
def worry_add (request):
form = WorryForm (request.POST or None)
if form.is_valid():
wform.user = models.ForeignKey('User') #HERE IS THE PROBLEM I THINK
wform.save()
return redirect (index)
return render_to_response ('holaProy/worry_add.html', {'worry_form': form}, context_instance = RequestContext(request))</code>
How should I do it in order to succesfully assign the current user id to the "user" field for the actual worry instance?
The issue is, indeed, on that line:
wform.user = models.ForeignKey('User')
wform.user should be set to a User instance. Something like this:
user = request.user # Retrieve proper user according to your needs
wform.user = user
Try:
def worry_add(request):
form = WorryForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
worry = form.save(commit=False)
worry.user = #assign this to an instance of a User object
worry.save()
That's the line where you are having your problem.
Basically, you are searching for a string. You need to get the actual database object before.
Try this:
User = User.objects.get(pk='User')
wform.user = models.ForeignKey('User') #Now User refers to the database object, not a string

How to save the email and name fields in the Django deafult User table

I want to save the email and name fields in django default table called UserSignup
my models.py is:
from django.db import models
class UserSignup(models.Model):
mailid = models.CharField(max_length=100)
name = models.CharField(max_length=100)
my views.py is:
from django import views
from django.shortcuts import render_to_response
from django.template import RequestContext
from Deals.signup.forms import signup
from django.contrib.auth.models import User
from django.http import HttpResponse
def usersignup(request,form_class=signup):
form = form_class()
print form
if form.is_valid():
mail= UserSignup(mailid=request.POST['mailid'])
mail.save()
name= UserSignup(name=request.POST['name'])
name.save()
else:
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
and forms.py is
from django import forms
from django.contrib.auth.models import User
from Deals.signup.models import *
from django.utils.translation import ugettext_lazy as _
class signup(forms.Form):
email = forms.EmailField(widget=forms.TextInput(),
label=_("Email address:"))
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(),
label=_("Name:"))
def save(self,request,update):
name = self.cleaned_data['name']
name.save()
email = self.cleaned_data['email']
email.save()
Please help me in saving my forms input in database
Check the Django documentation properly http://docs.djangoproject.com/en/dev/topics/forms/
Just change your code in views.py.
def usersignup(request,form_class=signup):
if request.method == 'POST': #If its a form submission, the method is POST
form = form_class(request.POST)
if form.is_valid():
newuser = form.save()
else: #Else display the form
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
The 'save' function in your forms file is incorrect and is not needed.
On a side note, your "UserSignup" is not a default User Table. That would be the user model provided by Django. And that already has the fields that you are creating in UserSignup. Why don't you use that feature of Django?
It might be better to save the model elements in the form in one time.
def save(self):
new_user = User.objects.create_user(name = self.cleaned_data['name'],
email = self.cleaned_data['email'])
return new_user

Categories