Cant save forms to models django - python

i cant save my forms to a models into my database the code work smoothly no errors but if i check in django admin its not save to my database model can you help me
here my code :
forms.py
class InstagramUsernameForm(forms.ModelForm):
class Meta:
model = InstagramUsername
fields = ('nama_orang','username','nama_depan')
nama_orang = forms.CharField(max_length=20)
username = forms.ModelChoiceField(queryset=Instagram.objects.values_list("username", flat=True))
nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan", flat=True))
models.py
from django.db import models
# Create your models here.
class Instagram(models.Model):
nama_depan = models.CharField(max_length=100,blank=True,null=True)
nama_belakang = models.CharField(max_length=100)
username = models.CharField(max_length=100)
def __str__(self):
return self.username
class InstagramUsername(models.Model):
nama_orang = models.CharField(max_length=20)
username = models.CharField(max_length=20)
nama_depan = models.CharField(max_length=100,default='')
def __str__(self):
return self.nama_orang
views.py
def create2(request):
akun_form = InstagramUsernameForm(request.POST or None)
if request.method == 'POST':
if akun_form.is_valid():
akun_form.save()
return redirect('sosmed:awe')
else:
print(akun_form.errors)
context = {
"akun_form":akun_form,
}
return render(request,"sosmed/awe.html",context)
awe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>awe</title>
</head>
<body>
<form method="post">
{% csrf_token %}
<h1>awe</h1>
<table>
{{ akun_form.as_table }}
</table>
<button type="submit">Create</button>
</form>
</body>
</html>
cant save forms to django models

values_list returns a list of tuples, rather than model instances, when used as an iterable.
so use .all() method instead of values_list()
username = forms.ModelChoiceField(queryset=Instagram.objects.all())

Related

Unable to post data to foreign key table in Django

I am an absolute beginner to Django and I am trying to check the POST method by populating the value to the foreign key table. I have two tables. Please guide me on where I am wrong.
Table for Category that has 2 entries, i.e., Coffee(PK = 1) and Desserts (PK = 2)
Table for Items
From models.py:
class Category(models.Model):
cId = models.AutoField(primary_key=True)
categoryName = models.CharField(max_length=20, unique=True)
def __str__(self):
return self.categoryName
# return[self.categoryName, self.cId]
# return self.cId
class Item(models.Model):
Id = models.AutoField(primary_key=True)
itemName = models.CharField(max_length=30,unique=True)
cId = models.ForeignKey(Category,on_delete=CASCADE)
From views.py:
def main(request):
return render(request, "index.html")
def send(request):
if request.method == "POST":
a = request.POST.get("a");
b = request.POST.get("b");
obj = Item(itemName = a, cId =b);
obj.save()
return HttpResponse("sent")
else:
return HttpResponse("form submission failed")
From urls.py(app):
urlpatterns = [
path('', views.main, name="main"),
path('send', views.send, name='send')
]
From HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'css.css' %}">
<title>CHECK-POST-METHOD</title>
</head>
<body>
<div class = "container">
<form method = "post" action = "send" class = "form">
{% csrf_token %}
<label for="a">Item Name</label>
<input type="text" name="a" id="a" maxlength="30">
<label for="b">PASS FOREIGN KEY--CATEGORY ID</label>
<input type="number" name="b" id="b" maxlength="5">
<button type="submit">SUBMIT</button>
</form>
</div>
<script src="{% static 'js.js' %}"></script>
</body>
</html>
I am unable to populate the Item table with the following entry:
I am unable to resolve the following error:
cId expects a Category object, but you have given it '1'. If you want to specify the primary key instead for a ForeignKey named foo, you use foo_id, so in this case cId_id:
def send(request):
if request.method == 'POST':
a = request.POST.get('a')
b = request.POST.get('b')
obj = Item(itemName=a, cId_id=b)
obj.save()
return HttpResponse("sent")
else:
return HttpResponse("form submission failed")
As it indicates in the error, Cid must be instance of category
So your view looks like below:
def send(request):
if request.method == "POST":
a = request.POST.get("a");
b = request.POST.get("b");
c_id = Category.objects.get(pk=b)
obj = Item(itemName=a, cId=b);
obj.save()
return HttpResponse("sent")
else:
return HttpResponse("form submission failed")
Since cId needs to be an object of type Category, you can use Django's get_object_or_404 function. In cases where cId posted from the HTML is not valid, then this function automatically raises the 404 response.
from django.shortcuts import get_object_or_404
def send(request):
if request.method == "POST":
a = request.POST.get("a");
b = request.POST.get("b");
b_obj = get_object_or_404(Category, b)
obj = Item(itemName = a, cId =b_obj)
obj.save()
return HttpResponse("sent")
else:
return HttpResponse("form submission failed")

How to get the id of a form in Django?

I am trying to develop a page in Django where there is multiple form that the user can modify.
For this, I need to get the id of the form the user ask to modify.
There is my code:
models.py:
class Order(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
date = models.DateField()
forms.py:
class OrderForm(ModelForm):
class Meta:
model = Order
fields = ["date"]
views.py:
def order(request, identifiant):
user_orders = []
form_user_orders = []
user = User.objects.get(username=identifiant) #We use identifiant from the url to get the user
user_orders.append(Order.objects.filter(user=user.id)) #We get all order of the user
if request.method == "POST":
form = OrderForm(request.POST)
if form.is_valid():
order_instance = Order(
id = None, #This is where I have a problem
user=User(id=user.id),
date=form.cleaned_data["date"],
)
order_instance.save()
return HttpResponseRedirect(f"/forms/orders/{identifiant}")
else:
for order in user_orders[0]: #We iterate on all orders and put them in another list as form instances
form_user_orders.append(OrderForm(instance=order))
return render(request, "forms/orders.html", {"identifiant": identifiant, "forms": form_user_orders})
urls.py:
urlpatterns = [
path("orders/<identifiant>", views.order)
]
order.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Order</title>
</head>
<body>
{% for form in forms %}
<form method="POST">
{% csrf_token %}
<div>
<label>Date</label>
<div>
{{ form.date }}
</div>
</div>
</form>
{% endfor %}
</body>
</html>

Model is not throwing(Saving) data to the backend in Django

This is function for updating user's info.
views.py
def UpdateProfile(request):
context = {}
user = request.User
if not user.is_authenticated:
return redirect('login')
if request.POST:
form = PersonalInfo(request.POST, instance=user)
if form.is_valid():
obj = form.Save(commit=False)
user = user.id
obj.user = user
obj.save()
return redirect('profile')
else:
#messages.error(request, ('Please correct the error below.'))
context['personal_form'] = form
else:
form = PersonalInfo(instance=user)
context['personal_form'] = form
return render(request, 'admission/signup.html', context)
This is the model I have created for storing user info.
models.py:
class ApplicantInfo(models.Model):
infield = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
profile_pic = models.ImageField(upload_to='media/', blank= True, null= True)
father_name = models.CharField(max_length=30)
user = models.OneToOneField(User, on_delete=models.CASCADE)
This is the form class I have created.
forms.py:
from .models import Applicant, ApplicantInfo
from django import forms
class PersonalInfo(forms.ModelForm):
class Meta:
model = ProfileInfo
fields = [
'first_name',
'last_name',
'profile_pic',
#'date_birth',
'father_name',
'street_adr',
'city',
'zip_code',
]
This is the frontend template which I have created, this is working fine.
Template
{%block content%}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST">
{% csrf_token %}
{% for field in personal_form %}
<p>
{{field.label_tag}}
{{field}}
{% if field.help_text %}
<small style="color:gray">{{field.help_text}}</small>
{% endif %}
</p>
{% endfor %}
{% for field in personal_form %}
<p>
{% for error in field.errors %}
<p style="color:red">{{error}}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Submit</button>
</form>
</body>
</html>
{% endblock content %}
The app has been able to load the form without any trouble but it just not throwing data to the backend.
Updated function for UpdateProfile
views.py
def UpdateProfile(request, id=None):
context = {}
user_obj = request.user
if not user_obj.is_authenticated:
return redirect('login')
if request.method == "POST":
form = PersonalInfo(request.POST)
if form.is_valid():
obj = form.save()
user_id = Applicant.objects.filter(app_id = user_obj.app_id).first()
obj.user = user_id
obj.save()
return redirect('profile')
else:
#messages.error(request, ('Please correct the error below.'))
context['personal_form'] = form
elif request.method == 'GET':
form = PersonalInfo(instance=user_obj)
context['personal_form'] = form
return render(request, 'admission/signup.html', context)
Updated code for forms method, only add #def cleaned_data function
forms.py
class PersonalInfo( forms.ModelForm):
class Meta:
model = ProfileInfo
fields = [
'first_name',
'last_name',
'profile_pic',
#'date_birth',
'father_name',
'street_adr',
'city',
'zip_code',
]
def clean(self):
if self.is_valid():
first_name = self.cleaned_data['first_name']
last_name = self.cleaned_data['last_name']
father_name = self.cleaned_data['father_name']
street_adr = self.cleaned_data['street_adr']
city = self.cleaned_data['city']
zip_code = self.cleaned_data['zip_code']
And model does not need to be change, you have choice either to add and autofield(PrimaryKey) or use the default one
The problem was in view.py where i just removed instance attribute from the form object, then I called user_id from user model which is in this case #Applicant model, then assigned to the obj object and saved obj.
Thanks to all of you who has spent precious time in this problem.
Cheers!!!

How can i order my votes by vote count? Django

so i made it that my books will show in my admin but i dont know how to order the books(in the admin) by votes and not by last voted. I found some answers here on overflow but i wasnt able to integrate them by myself. Here are my files:
admin.py
from django.contrib import admin
from .models import Vote
admin.site.register(Vote)
apps.py
from django.apps import AppConfig
class SurveyConfig(AppConfig):
name = 'survey'
forms.py
from django import forms
from .models import Vote
class VotingForm(forms.Form):
chosen_books_options = forms.MultipleChoiceField(choices=[], label='Book Name', required=False,
widget=forms.SelectMultiple(
attrs={
'class': 'form-control'
}
))
other_book_name = forms.CharField(label='Other', max_length=100, required=False,
widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Did we miss something?'
}
))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
unique_books_names = Vote.objects.order_by('book_name').values_list('book_name', flat=True).distinct()
self.fields['chosen_books_options'].choices = [(book_name, book_name) for book_name in unique_books_names]
models.py
from django.db import models, transaction
class Vote(models.Model):
book_name = models.CharField(max_length=200)
count = models.IntegerField(default=0)
def __str__(self):
return '%s: %d votes' % (self.book_name, self.count)
#classmethod
def bulk_vote(cls, book_names):
with transaction.atomic():
for book_name in book_names:
if len(book_name) == 0:
continue
if Vote.objects.filter(book_name=book_name).exists():
Vote.objects.filter(book_name=book_name).update(count=models.F('count') + 1)
else:
Vote.objects.create(book_name=book_name, count=1)
views.py
from django.shortcuts import render
from .forms import VotingForm
from .models import Vote
def index(request):
if request.method == 'POST':
form = VotingForm(request.POST)
if form.is_valid():
chosen_books_options = form.cleaned_data.get('chosen_books_options', [])
other_book_name = form.cleaned_data.get('other_book_name', '')
Vote.bulk_vote(chosen_books_options + [other_book_name])
message = 'Thank You For Your Contribution!'
elif request.method == 'GET':
message = ''
form = VotingForm()
return render(request, 'templates/survey.html', {'form': form, 'message': message})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<title>Document</title>
<style>
.form-control{
width: 50%;
}
</style>
</head>
<body>
<div class="container" id="thisone">
<h3>Select which books you'd like us to get started with.</h3>
<h5>{{ message }}</h5>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
thank you for reading
note: this is not fully my code
Within your admin, you can use the ordering attribute like so...
from django.contrib import admin
from .models import Vote
class VoteAdmin(admin.ModelAdmin):
ordering = ('count',)
admin.site.register(Vote, VoteAdmin)

input fields not displaying on templates

i am new to django when i try to run this project i wasn't getting any input fields in my template current page was only showing the given labels
i don't know where i've gone wrong
can any of you guys help??
these are my models.py file
from django.db import models
# Create your models here.
class Student(models.Model):
sid = models.CharField(max_length=100)
sname = models.CharField(max_length=100)
sclass = models.CharField(max_length=100)
semail = models.EmailField(max_length=100)
srollnumber = models.CharField(max_length=100)
scontact = models.CharField(max_length=100)
saddress = models.CharField(max_length=100)
class Meta:
db_table = "student"
the are my forms.py file
from django import forms
from student.models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = "__all__"
these are my views.py file
from django.shortcuts import render
from student.models import Student
from student.forms import StudentForm
def student_home(request):
return render(request, 'employee/dash.html')
def add_student(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
try:
form.save()
return render(request, 'employee/dash.html')
except:
pass
else:
form = StudentForm()
return render(request, 'student/addstudent.html')
template
<!DOCTYPE html>
<html lang="en">
<head>
<title>addstudent</title>
</head>
<body>
<a href="/home" >home</a>
<form method="POST" action="/add_student">
{% csrf_token %}
<label>Student ID:</label>
{{ form.sid }}
<label>Name :</label>
{{ form.sname }}
<label>Class :</label>
{{ form.sclass }}
<label>Email ID:</label>
{{ form.semail }}
<label>Roll Number :</label>
{{ form.srollnumber }}
<label>Contact :</label>
{{ form.scontact }}
<label>Address :</label>
{{ form.saddress }}
<button type="submit">Submit</button>
</form>
</body>
</html>
You forget to give the context to the render function:
return render(request, 'student/addstudent.html',context={'form':form})
should work
You have not included any context in your render functions. Your view should be:
def add_student(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
try:
form.save()
return render(request, 'employee/dash.html', context={'form': form})
except:
pass
else:
form = StudentForm()
return render(request, 'student/addstudent.html', context={'form': form})

Categories

Resources