Putting additional data to CRUD django model- iterating with id,pk/ Python3/Django/CRUD - html

this is in models.py
class Word(models.Model):
english = models.CharField( max_length=100)
polish = models.CharField( max_length=100)
this is in views.py
words=[]
def dictionary(request):
words= Word.objects.all()
context={'words':words}
return render(request, 'base/dictionary.html', context) `
``
def word(request, pk):
word= Word.objects.get(id=pk)
context={'word':word}
return render(request, 'base/word.html', context)
I would like to add this dictionary from my workplace to already existing database with models - English-Polish pair. I've created a CRUD model of this type of simple dictionary, yet I am wondering if I have to put all the words inside by myself , or there will be a possibility to append each pair with specific id , ready to be rendered into html template and database ?
words=['fallopian tube' : 'jajowód',
'mrsa bacteria' : 'bakteria gronkowca złocistego',
'carotid aneurysm': 'tętniak tętnicy szyjnej',...]

Related

Validation erorr raise for the form that validates its value from another model

I am trying to raise validation error for the entry field in the forms.py
My models.py
class StudBackground(models.Model):
stud_name=models.CharField(max_length=200)
class Student(models.Model):
name=models.CharField(max_length=200)
My forms.py
class StudentForm(forms.ModelForm):
name = forms.CharField(max_length=150, label='',widget= forms.TextInput)
class Meta:
model = Student
fields = ['name',]
where i tried to apply clean method :
def clean_student(self,*args,**kwargs):
name=self.cleaned_data.get("name")
if not studBackground.stud_name in name:
raise forms.ValidationError ( "It is a not valid student")
else: return name
I tried to incorporate stud_name from the StudBackground model to the form but it does not work it raises following error when i try to type student name that is not in DB:
Profiles matching query does not exist
however it supposed to return near the name field "It is a not valid student"
How to make it work? What is the wrong with the code?
You can try like this:
def clean_student(self):
name=self.cleaned_data.get("name")
if not StudBackground.objects.filter(stud_name=name).exists():
raise forms.ValidationError("It is a not valid student")
return name
I am using filter(...) function from queryset to check if a name exists in StudBackground. I am also running exists() to check if entry exists in DB.
Update
I think your indentations are not correct for the view. But, you can try like this:
def home(request):
form = StudentForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
instance = form.save()
name = instance.name
class_background=StudBackground.objects.get(stud_name=name)
context={'back':class_background}
return render(request, 'class10/background.html', context)
# Now let us handle if request type is GET or the form is not validated for some reason
# Sending the form instance to template where student form is rendered. If form is not validated, then form.errors should render the errors.
# How to show form error: https://docs.djangoproject.com/en/3.0/topics/forms/#rendering-form-error-messages
return render(request, 'your_student_form_template.html', context={'form':form})

How do I populate my form fields with data from the database Django

Hello I have a form page and I only need users to fill in certain fields, with the rest of the fields being pre-filled for them based on the module they pick.
While I can fetch the objects from my database -- i.e. the dropdown list shows Module Object (1), Module Object (2) -- I need only certain fields in these objects, which is why this similar sounding post couldn't answer my question:
Populate a django form with data from database in view
Here's my forms.py
class inputClassInformation(forms.Form):
module = forms.ModelChoiceField(queryset=Module.objects.all())
duration = forms.CharField(disabled=True, required=False)
description = forms.CharField()
assigned_professors = forms.ModelChoiceField(queryset=Class.objects.filter(id='assigned_professors'))
models.py -- not the full models are shown to reduce the post's length
class Module(models.Model):
subject = models.CharField(max_length=200, default="")
class Class(models.Model):
module = models.ForeignKey(Module, on_delete=models.CASCADE, default="")
duration = models.CharField(max_length=200, default="")
description = models.CharField(max_length=200, default="")
assigned_professors = models.CharField(max_length=200, default="")
So an expected result would be:
1) The Module field shows the subjects, instead of Module objects in its dropdown list and
2) The duration field is automatically filled in for the user, based on the module they picked. The reason is so that the user only has to manually fill in certain fields, while the rest are automatically generated.
This has had me stuck for a long while, help is appreciated. Thanks!
So an expected result would be:
1) The Module field shows the subjects, instead of Module objects in its dropdown list and
2) The duration field is automatically filled in for the user.
These are essentially two different questions.
To answer the first: you can override the:
__str__ method for your Model class for python 3 and django 1.8) and the
__unicode__ method for your Model class for django <1.8 and not python3.
For example, to make subjects appear instead of "XXXX Object" for your class do:
class Module(models.Model):
subject = models.CharField(max_length=200, default="")
def __unicode__(self):
return self.subject
Similarly, change __unicode__ for __str__ as appropriate for your django version.
Now, to answer your second question:
2) The duration field is automatically filled in for the user.
You need to do two things:
Do not display the duration field in your form (unless you want to give the users the chance to sometimes fill it in manually)
Override the save method
An example:
class Class(models.Model):
module = models.ForeignKey(Module, on_delete=models.CASCADE, default="")
duration = models.CharField(max_length=200, default="")
description = models.CharField(max_length=200, default="")
assigned_professors = models.CharField(max_length=200, default="")
def save(self, *args, **kwargs):
self.duration = #The value you'd want to automatically set here#
super(Model, self).save(*args, **kwargs)

How to call in django index.html fle for "GET" "POST" method for get data from id (fields)?

In django I have create query like wise if someone want information:
In district parameter select Pune, then output gives data for pune district only.
for example :
http:127.0.0.1/api/?district=Pune
htt:127.0.0.1:8000/?crop = groundnut
and so on.
Next,I want to create a Html page for my starting django page(index.html)
if I runserver http:127.0.0.1:8000/
display my html file , where Our models fields(paramter) is id and then user submit the question "if" condition will be trigger and searching information for that parameters.
like wise:
District = __________ submit
gives data only for selected district name only
also
Crop = ______________ submit
gives data only for selected crop name only
likewise run this query
http:/api/?crop=groundnut
if user choose crop name is groundnut,
if use choose crop name is guava, then http:/api/?crop=guava query will be run.
So,now I want to create index.html file multiple parameters works.(AND query will apply)
http:/api/district=Pune&crop=groundnut
So, I want to create html page which call to this query and its show me this type
Distrcit : ________ Crop : __________ submit
here is my models.py
from django.db import models
from mongoengine import Document, fields
class Tool(Document):
crop = fields.StringField(required=True)
district = fields.StringField(required=True)
def __str__(self):
return self.crop
def save(self,*args, **kwargs):
super().save(*args, **kwargs)
class Meta:
verbose_name_plural ='tool'
project/urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from django.contrib import admin
from app.views import *
from routers import HybridRouter
router = HybridRouter()
router.register(r'tool', ToolViewSet, r"tool")
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls, namespace='api')),
url(r'^$', index_view, {}, name='index'),
]
app/views.py
from django.template.response import TemplateResponse
from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet
from app.serializers import *
class ToolViewSet(MongoModelViewSet):
serializer_class = ToolSerializer
my_filter_fields = ('crop', 'district',) # specify the fields on which you want to filter
def get_kwargs_for_filtering(self):
filtering_kwargs = {}
for field in self.my_filter_fields: # iterate over the filter fields
field_value = self.request.query_params.get(field) # get the value of a field from request query parameter
if field_value:
filtering_kwargs[field] = field_value
return filtering_kwargs
def get_queryset(self):
queryset = Tool.objects.all()
filtering_kwargs = self.get_kwargs_for_filtering() # get the fields with values for filtering
if filtering_kwargs:
queryset = Tool.objects.filter(**filtering_kwargs) # filter the queryset based on 'filtering_kwargs'
return queryset
from .models import Tool
from django.shortcuts import render
def index_view(request):
questions=None
if request.GET.get('crop'):
crop = request.GET.get('crop')
questions = Tool.objects.filter(crop__icontains=crop)
district = request.GET.get('district')
query = Tool.object.create(crop=crop, district=district)
query.save()
return render(request, 'index.html',{
'questions': questions,
})
what I have to change in views.py file for index.html to get parameter and gives exact information after user click on submit button ?
index.html
<form method="GET">
Crop: <input type="text" name="crop"><br/>
Taluka: <input type="text" name="taluka"><br/>
<input type="submit" value="Submit" />
</form><br/><br/>
{% for question in questions %}
<p>{{question}}</p>
{% endfor %}
can you help me how to get data and run the query ?
where I need to changes ?
Its a TYPO error in this line :
query = Tool.object.create(crop=crop, district=district)
object should be objects ,like this :
query = Tool.objects.create(crop=crop, district=district)
Update your code like this :
from .models import Tool
from django.shortcuts import render
def index_view(request):
questions=None
if request.GET.get('crop'):
crop = request.GET.get('crop')
questions = Tool.objects.filter(crop__icontains=crop)
district = request.GET.get('district')
query = Tool.objects.create(crop=crop, district=district)
query.save()
return render(request, 'index.html',{
'questions': questions,
})
And, Update the save method of your Tool model like this :
class Tool(Document):
crop = fields.StringField(required=True)
district = fields.StringField(required=True)
def __str__(self):
return self.crop
def save(self,*args, **kwargs):
super(Tool, self).save(*args, **kwargs)
In your index.html file, change {{question}} to {{question.crop}}. You have to refer to the field (in your case crop) on the model you want to render on your page.
Also, the default manager is located at Tool.objects not Tool.object.
In your models.py, super should be super(Tool, self). Also model Tool should inherit from django.db.models.Model. Your fields must be from django.db.models
class Tool(Model):
crop = models.CharField()

django queryset limited choice filed by FK

I have two models
Notification
Asset
To display data using the django-filter.
Unfortunately, when you create a form in the select-field all the values of the model Asset, and I would just those related to FK model Notification.
def get_queryset(self):
try:
self.filter = NotificationListFilter(
self.request.GET,
queryset = Notification.objects.all()
)
return self.filter
except :
return Notification.objects.order_by('-asset__system')
In some way I can build queryset this to happen?

Display multiple related Django models in a templates

Hi I am having the models.py like this
from django.db import models
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
author_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
def __unicode__(self):
return "%d %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name)
class Author(models.Model):
author_id=models.AutoField(primary_key=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age=models.IntegerField()
book=models.ForeignKey(Book)
def __unicode__(self):
return u'%d %s %s' % (self.author_id,self.first_name, self.last_name)
i waant to display these two tables in a single order in a html template.I am new to django..i am learning now..plz help me with a design of views.py and an "htmlfile.html templates".Plz give me the procedure also
check your latest question for answer,
Retrieve data from two tables with foreign key relationship in Django?
key-relationship-in-django