I'm learning django and I'm trying to display all items from a specific user which is the 2003-111
itemid sy sem resolve_by
book 2021-2022 2 2003-111
table 2021-2022 1 2012-455
here's my models.py I'm using customuser to use email as authentication instead of username and replace my id with userid(character)
class ClearanceCustomuser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.BooleanField()
userid = models.CharField(primary_key=True, max_length=9)
email = models.CharField(unique=True, max_length=254)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
managed = False
db_table = 'clearance_customuser'
class ClearanceItem(models.Model):
itemid = models.CharField(primary_key=True, max_length=20)
sem = models.CharField(max_length=1, blank=True, null=True)
sy = models.CharField(max_length=9, blank=True, null=True)
resolve_by = models.ForeignKey('ClearanceCustomuser', models.DO_NOTHING,
db_column='resolve_by', blank=True, null=True)
class Meta:
managed = False
db_table = 'clearance_item'
for now this is my views.py
def index(request):
context = {}
context['items'] = ClearanceItem.objects.all()
return render(request, 'clearance/index.html', context)
which is displaying all items. I was thinking of something like this
select b.cl_itemid,b.sem,b.sy,b.resolve_by
from curriculum.clearance_customuser a
INNER JOIN curriculum.clearance_item b ON a.userid = b.resolve_by
where resolve_by = '2003-221'
if 2003-111 is userid field of ClearanceCustomuser than you go like:
def index(request):
context = {}
context['items'] = ClearanceItem.objects.filter(resolve_by__userid='2003-111')
return render(request, 'clearance/index.html', context)
if you want to pass userid as parameter in yours urls.py edit path to index:
path('<str:userid>/', views.index, name='index')
and in view:
def index(request, userid):
context = {}
context['items'] = ClearanceItem.objects.filter(resolve_by__userid=userid)
return render(request, 'clearance/index.html', context)
Related
I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work,
i am trying to multiple way to solve this issue but still can't find solution.
Models.py # thease are all 3 models
class Problem(models.Model):
Language = models.IntegerField(choices=Language_CHOICE, default=1)
type = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.type
class ChatQuestion(models.Model): # Eding record based on chatquestion id
question = RichTextField(null=True, blank=True)
problem_id = models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
)
def __str__(self):
return self.question
is_first_question = models.BooleanField(default=False)
class Option(models.Model):
option_type = models.CharField(max_length=250, null=True, blank=True)
question_id = models.ForeignKey(
ChatQuestion,
models.CASCADE,
verbose_name='Question',
null=True,
blank=True
)
problem=models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
null=True,
blank=True
)
next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True,
related_name='next_question')
def __str__(self):
return self.option_type
forms.py
class EditQuestionForm(forms.ModelForm):
class Meta:
model = ChatQuestion
fields =('question','problem_id')
class EditOptionForm(forms.ModelForm):
class Meta:
model = Option
fields =('option_type',)
views.py
def question_edit(request,id=None):
if id is not None:
queryset = get_object_or_404(ChatQuestion,pk=id)
queryset1=get_object_or_404(Option,question_id=queryset )
else:
queryset = None
queryset1 = None
if request.method=="POST":
form = EditQuestionForm(request.POST ,instance=queryset)
form1=EditOptionForm(request.POST, instance=queryset1)
if form.is_valid() and form1.is_valid():
question=form.cleaned_data['question']
option_type=form1.cleaned_data['option_type']
if id:
queryset.question=question
queryset.save()
queryset1.option_type=option_type
queryset1.save()
messages.success(request,'Sucessful')
return redirect('/fleet/list_chatbot')
else:
print(form.errors)
messages.error(request,'Please correct following',form.errors)
elif id:
form = EditQuestionForm(instance=queryset)
form1=EditOptionForm(instance=queryset1)
if not queryset1:
form1=EditOptionForm()
else:
form = EditQuestionForm()
form1=EditOptionForm()
context={
'form':form,
'form1':form1
}
return render(request,'chatbot/question_edit.html',context=context)
I created models for companies in my new application in django and have also created the instance for it to show detail page for each company. But when a company is clicked, it shows the id of the company instead of the name in URL like this: http://127.0.0.1:8000/companies/2/
is there a way I can make it return the company name instead like this: http://127.0.0.1:8000/companies/stackoverflow/
this is the code for my model and am using function based views for this:
class Company(models.Model):
Online_Merchant = 'merch'
Education = 'edu'
Transportation = 'trans'
Hospitalism = 'hosp'
Healthcare = 'health'
Construction = 'const'
Blog = 'blog'
Finance = 'fin'
Media = 'media'
Government_Agency = 'agency'
Other = 'other'
Manufacturing = 'manufacturing'
sector = [
(Online_Merchant, 'Online Merchant'),
(Education, 'Education'),
(Transportation, 'Transportation'),
(Hospitalism, 'Hospitalism'),
(Healthcare, 'Healthcare'),
(Construction, 'Construction'),
(Blog, 'Blog'),
(Finance, 'Finance'),
(Media, 'Media'),
(Manufacturing, 'Manufacturing'),
(Government_Agency, 'Government Agency'),
(Other, 'Other')
]
Free = 'Free'
Premium = 'Premium'
package = [
(Free, 'Free'),
(Premium, 'Premium')
]
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Company User')
company_sector = models.CharField(max_length=30, choices=sector, default=Online_Merchant, verbose_name='Sector')
company_name = models.CharField(max_length=100)
company_description = models.TextField()
company_logo = models.ImageField(upload_to='company_logos', blank=True, null=True)
company_address = models.TextField(max_length=2000)
rating_array = ArrayField(models.IntegerField(), size=0, default=list)
average_rating = Int_max.IntegerRangeField(default=0, verbose_name='Avg', min_value=1, max_value=5)
total_views = models.IntegerField(default=0)
company_website = models.CharField(max_length=500, blank=True, null=True)
company_email = models.EmailField(max_length=500, blank=True, null=True)
company_phone = models.CharField(max_length=500)
package_chosen = models.CharField(max_length=8, choices=package, default=Free)
company_views = models.IntegerField(default=0)
featured = models.BooleanField(default=False)
advert = models.BooleanField(default=False)
premium = models.BooleanField(default=False)
def get_absolute_url(self):
"""Returns the url to access a particular instance of the model."""
return reverse("detail", kwargs={ "id": self.id })
def __str__(self):
return self.company_name
def __repr__(self):
return self.company_name
SlugField is designed for this. the django admin will help populate it as well.
models.py
class Company(models.Model):
...other model fields...
company_slug = models.SlugField(max_length=255, allow_unicode=True)
def get_absolute_url(self):
"""Returns the url to access a particular instance of the model."""
return reverse("detail", kwargs={ "slug": self.company_slug })
admin.py
class CompanyAdmin(admin.ModelAdmin):
prepopulated_fields = {"company_slug": ("company_name",)}
...admin code...
and to use it in a query:
company = Company.objects.get(company_slug=kwargs.get('company_slug')
urls.py
urlpatterns = [ path('<slug:company_slug>/', views.dynamic_url, name='detail'), ]
I have the view which displays all transactions. I have a table with contractors and I want to display all rows from this table in the options to <select>. How can i do this?
My view:
class TransactionView(CustomPermissionRequired, ListView):
# Переопределение из MultipleObjectMixin
model = Transaction
context_object_name = 'transactions'
paginate_by = 20
login_url = '/'
permission_required = (
'registration2.can_see_payments',
)
# Переопределение из TemplateResponseMixin
template_name = 'payments.html'
search_fields = [
('contractor_name', 'deal__service__contractor__name__icontains'),
('from_pay_date', 'payment_date__gte'),
('to_pay_date', 'payment_date__lte'),
('tr_id', 'id__icontains')
]
# Переопределение из MultipleObjectMixin
def get_queryset(self):
print('get_def')
filter_args = []
filter_kwargs = {}
for sf in self.search_fields:
if sf[0] is not None:
sf_value = self.request.GET.get(sf[0])
if sf_value:
filter_kwargs[sf[1]] = sf_value
return Transaction.objects.all().select_related('currency',
'payment_source__payment_type',
'deal__service__contractor'
).filter(*filter_args, **filter_kwargs).order_by('-id')
def get_context_data(self, **kwargs):
context = super(TransactionView, self).get_context_data(**kwargs)
for sf in self.search_fields:
if sf[0] is not None:
context[sf[0]] = self.request.GET.get(sf[0])
return context
My models Transaction and Contractors:
class Transaction(models.Model):
id = models.BigIntegerField(blank=True, null=False, primary_key=True)
currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE)
deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE)
# service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE)
payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE)
payment_date = models.DateTimeField(blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
context = models.TextField(blank=True, null=True)
class Contractors(models.Model):
id = models.IntegerField(blank=True, null=False, primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
You don't show your HTML, but you start from a queryset to get the contractor names and ids.
contractors = Contractors.objects.all().order_by('name').values_list('id, 'name')
If you look at list(contractors) you will see it is a list of 2-tuples as required for choices.
You can use it as such if you dynamically build a form, or you can pass it to your template and iterate through it there to build an options list
{% for c in contractors %} <option ... {{c.0}} ... {{c.1}} ... {% endfor %}
There's also forms.ModelChoiceField which IIRC accepts a queryset (without values_list()) as an argument, and returns the selected [Contractor] instance as its entry in form.cleaned_data.
I am having problem with list_display/joining two table for django admin interface.
I want to have columns- program_name and is_active from SchPrograms model with parameter_name, parameter_description from VisVisitParameters model in django admin. I am able to have those columns which i am using with return in each of these models. I tried to take help from the question that already has been asked. But still i could not able to figured this out.
class SchPrograms(models.Model):
program_id = models.AutoField(primary_key=True)
program_name = models.CharField(max_length=200, blank=True, null=True)
creation_timestamp = models.DateTimeField(blank=True, null=True)
is_active = models.IntegerField()
class Meta:
managed = True
db_table = 'sch_programs'
app_label = 'polls'
def __str__(self):
return self.program_name
class VisVisitParameters(models.Model):
vparameter_id = models.AutoField(primary_key=True)
parameter_name = models.CharField(max_length=300, blank=True, null=True)
parameter_description = models.TextField(blank=True, null=True)
is_active = models.IntegerField(choices=STATUS_CHOICES)
class Meta:
managed = False
db_table = 'vis_visit_parameters'
def __str__(self):
return str(self.vparameter_id)
app_label = 'polls'
class VisVisitParameterMappings(models.Model):
vp_map_id = models.AutoField(primary_key=True)
vparameter = models.ForeignKey(VisVisitParameters,on_delete=models.CASCADE)
program = models.ForeignKey(SchPrograms,on_delete=models.CASCADE)
display_order = models.IntegerField(blank=True, null=True)
is_active = models.IntegerField()
class Meta:
managed = False
db_table = 'vis_visit_parameter_mappings'
app_label = 'polls'
def __str__(self):
return str(self.parameter_name)
model.py
class VisVisitParameterMappings_admin(admin.ModelAdmin):
list_display = ('program_name','is_active','parameter_name','parameter_description ')
To display the required items on the list display page you can write your custom methods, as documented here.
For example, for your field named program_name you can have:
def program_name(self, obj):
if obj.program:
return obj.program.program_name
program_name.short_description = 'Program name'
and for another model field named parameter_name , you may have:
def parameter_name(self, obj):
if obj.vparameter:
return obj.vparameter.parameter_name
parameter_name.short_description = 'Parameter Name'
Hope it helps.
I need to save the info of these models with foreign keys, so I created a view for Candidato, InfoPersonal and InfoAcademica, and finally I created a confirm view to save Solicitud but that page shows me:
TypeError at /solicitud/confirmacion/2/
'instance' is an invalid keyword argument for this function
My models.
project/apps/solicitud/models.py
class Candidato(models.Model):
nombre = models.CharField(max_length=50)
apellidos = models.CharField(max_length=70)
email = models.EmailField(unique=True)
def __unicode__(self):
return u'{} {}'.format(self.nombre, self.apellidos)
class InfoPersonal(models.Model):
candidato = models.ForeignKey(Candidato, null=False, blank=False, on_delete=models.CASCADE)
sexo = models.CharField(max_length=9, choices=SEXO_CHOICES)
fecha_nacimiento = models.DateField()
curp = models.CharField(max_length=18, unique=True)
pais_origen = models.CharField(max_length=30, default="México")
lugar_nacimiento = models.CharField(max_length=100)
domicilio = models.CharField(max_length=120)
codigo_postal = models.CharField(max_length=5)
telefono = models.CharField(max_length=20)
def __unicode__(self):
return u'{}'.format(self.curp)
class InfoAcademica(models.Model):
persona = models.ForeignKey(Candidato, null=True, blank=True, on_delete=models.CASCADE)
escuela_procedencia = models.CharField(max_length=50)
programa_solicitado = models.CharField(max_length=50, choices=PROGRAMA_SOLICITADO_CHOICES, default=MAS_ADMIN)
titulado = models.CharField(max_length=10, choices=ESTADO_TITULACION_CHOICES, default=YA_TITULADO)
titulacion_creditos = models.CharField(max_length=2, choices= TITULACION_CREDITOS_CHOICES, default=NO)
def __unicode__(self):
return u'{}'.format(self.programa_solicitado)
class Solicitud(models.Model):
candidato = models.ForeignKey(Candidato, null=True, blank=True)
academica = models.ForeignKey(InfoAcademica, null=False, blank=False)
Personal = models.ForeignKey(InfoPersonal, null=False, blank=False)
def __unicode__(self):
return u'Solicitud id: {}'.format(self.id)
My URLS, here I send a pk for every model to link them in Solicitud
# -*- coding: utf-8 -*-
from django.conf.urls import url
import views
app_name = 'solicitud'
urlpatterns = [
url(r'^datos_candidato/$', views.AddDatosCandidato.as_view(), name='datos_candidato'),
url(r'^datos_personales/$', views.AddDatosPersonales.as_view(), name='datos_personales'),
url(r'^datos_academicos/$', views.AddDatosAcademicos.as_view(), name='datos_academicos'),
url(r'^confirmacion/(?P<pk>\d+)/$', views.AddSolicitud.as_view(), name='datos_confirmacion'),
]
and finally my views, Here I don't know how to send the instancen of the 2 models and save it in Solicitud
project/apps/solicitud/views.py
class AddSolicitud(CreateView):
model = Solicitud, InfoPersonal, InfoAcademica
form_class = Solicitud
template_name = 'solicitud/confirmacion_solicitud.html'
You have form_class = Solicitud, but Solicitud is a model not a form.
Also, you can't specify more than one model in the model = line.