Hi guys I have something that I do not know how to make it work.
I am working on a questionnaire like, where on a page will show up the questionn and a radio like form list of answers that the user can select.
I gave it a try but I do not know how to link a question to my form, could you please help ?
models.py:
from django.db import models
# Create your models here.
class Questionnaire(models.Model):
question = models.CharField(max_length=600)
multiple_answer = models.BooleanField(default=False)
def __str__(self):
return self.question
class Answers(models.Model):
question_id = models.ForeignKey('Questionnaire', on_delete=models.CASCADE)
answer = models.CharField(max_length = 600)
def __str__(self):
return self.answer
class Test(models.Model):
user = models.ForeignKey('registration.MyUser')
created_at = models.TimeField(auto_now_add=True)
closed = models.BooleanField(default=False)
class UserAnswer(models.Model):
test_id = models.ForeignKey('Test')
question = models.ForeignKey('Questionnaire')
answer = models.ForeignKey('Answers')
views.py:
def AnswerChoiceSelect(request):
#import pdb; pdb.set_trace()
if request.method == "POST":
answer_form = QuestionChoices(request.POST)
if answer_form.is_valid():
print("working")
else:
print('Non Valid form')
else:
answer_form = QuestionChoices(request.user)
return render(request,'question_template.html',
{'answer_form':answer_form })
forms.py:
from django import forms
from django.contrib.auth.models import User
from registration.models import MyUser
from .models import Questionnaire, Answers, Test, UserAnswer
from django.contrib.auth import get_user_model
User = get_user_model()
class QuestionChoices(forms.Form):
question_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None)
def __init__(self,questionnaire, *args, **kwargs):
super(QuestionChoices, self).__init__(*args, **kwargs)
current_question = Questionnaire.objects.get(id = question_id)
self.fields['question_choice'].queryset = Answers.objects.filter(question_id = Current_question.id)
Related
please help me in making this application in django project
Here is models.py file code
from django.db import models
from bio.models import Profile
class Question(models.Model):
name = models.TextField(max_length=500)
def __str__(self):
return self.name
class Answer(models.Model):
question = models.ForeignKey(Question, related_name='question', on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE)
text = models.TextField(max_length=400)
created_on = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return "{0} on {1}".format(self.question, self.profile)
class Meta:
db_table = 'answer'
constraints = [
models.UniqueConstraint(fields=['profile', 'text', 'question'], name='unique answer')
]
here is views.py file code
class DetailViewMixin(object):
details_model = None
context_detail_object_name = None
def get_context_data(self, **kwargs):
context = super(DetailViewMixin, self).get_context_data(**kwargs)
context[self.context_detail_object_name] = self.get_detail_object()
return context
def get_detail_object(self):
return self.details_model._default_manager.get(pk=self.kwargs['pk'])
class AnswerCreate(DetailViewMixin, CreateView):
details_model = Question
context_detail_object_name = 'question'
model = Answer
form_class = NewAnswerForm
template_name = "qna/answer.html"
success_url = reverse_lazy('qna:list')
def form_valid(self, form):
form.instance.profile_id = self.kwargs.get('pk')
form.instance.question_id = self.kwargs.get('pk')
return super().form_valid(form)
here is my forms.py code
from django import forms
from .models import Answer
class NewAnswerForm(forms.ModelForm):
class Meta:
model = Answer
fields = ['text',]
def clean(self):
try:
Answer.objects.get(text=self.cleaned_data['text'].lower())
raise forms.ValidationError('Answer exists!')
except Answer.DoesNotExist:
pass
return self.cleaned_data
where am I going wrong????
I want that if user answers one question then he couldn't answer it again
how can i do form validation if object is already created
Add a UniqueConstraint to Answer so no combination of Question and Profile can be repeated:
https://docs.djangoproject.com/en/3.1/ref/models/constraints/#django.db.models.UniqueConstraint
can anyone tell me how combine detailview with list view and show info in the same template, i'll explain you, i'm learning Django and i am trying to create a Questions and Answer web app, and i need to show the question with all its awnsers, i need in my detailview for a specific question show below all it awsers, something like stackoverflow does
#models.py
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
# Create your models here.
class Question(models.Model):
# user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="question", null=True)
name = models.CharField(max_length=100)
description = models.TextField(max_length=100)
date = models.DateTimeField(auto_now_add=True)
cant_resp = models.IntegerField(default=0)
question_type = models.CharField(max_length=50, choices=QUESTION_TYPES_CHOICES)
def __str__(self):
return self.description
class Anwser(models.Model):
# user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="anwser", null=True)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
text = models.TextField(max_length=400)
date= models.DateTimeField(auto_now_add=True)
#and this are my views.py
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from .forms import QuestionForm, AnwserForm
from .models import Question
# Create your views here.
class QuestionListView(LoginRequiredMixin, generic.ListView):
template_name = 'anwserquestions/question_list.html'
context_object_name = 'questions'
def get_queryset(self):
return Question.objects.all()
def createquestion(response):
if response.method == "POST":
print("Its POST method")
form = QuestionForm(response.POST)
# user =response.user
if form.is_valid():
name = form.cleaned_data["name"]
description=form.cleaned_data['description'],
question_type=form.cleaned_data['question_type'],
# date=form.cleaned_data['date'],
t = Question(name=name, description=description, question_type=question_type, cant_resp=0)
t.save()
response.user.question.add(t) # adds the to do list to the current logged in user
# return HttpResponseRedirect("/%i" %t.id)
return redirect('anwserquestions:question-list')
else:
form = QuestionForm()
return render(response, "anwserquestions/question_create.html", {"form":form})
class QuestionDetailView(LoginRequiredMixin, generic.DetailView):
model = Question
template_name = 'anwserquestions/question_detail.html'
context_object_name = 'question'
def get_queryset(self):
return Question.objects.all()
class QuestionDeleteView(LoginRequiredMixin, generic.DeleteView):
template_name = 'anwserquestions/question_delete.html'
context_object_name = 'question'
success_url = reverse_lazy('anwserquestions:question-delete')
# def get_queryset(self):
# return Question.objects.all()
You can get the related answers by including it in the views context, so you QuestionDetailView becomes
class QuestionDetailView(LoginRequiredMixin, generic.DetailView):
model = Question
template_name = 'anwserquestions/question_detail.html'
context_object_name = 'question'
def get_context_data(self, **kwargs):
context = super(QuestionDetailView, self).get_context_data(**kwargs)
context['answers'] = Answer.objects.filter(post=self.get_object())
return context
class Setting(models.Model):
id=models.AutoField(primary_key=True, unique=True)
ldap_server = models.CharField(max_length=100, default='ldap://yourDomain.in')
ldap_server_username = models.CharField(max_length=100, null=True)
ldap_server_password = models.CharField(max_length=100, null=True)
def save(self, *args, **kwargs):
ldap_server=self.ldap_server
ldap_server_username = self.ldap_server_username
ldap_server_password = self.ldap_server_password
try:
l = ldap.initialize(ldap_server)
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s(ldap_server_username, ldap_server_password)
super(Setting, self).save(*args, **kwargs)
except:
messages.error(request, "You have logged in..!")
here I faced the error in
messages.error(request, "You have logged in..!")
I can't use
messages.error(request, "You have logged in..!")
Anybody know alternative way to show error
message.
Try this in admin.py:
#admin.py
from models import Setting
from django.contrib import admin
from django import forms
class SettingForm(forms.ModelForm):
class Meta:
model = Setting
def clean(self):
ldap_server = self.cleaned_data.get('ldap_server')
ldap_server_username = self.cleaned_data.get('ldap_server_username')
ldap_server_password = self.cleaned_data.get('ldap_server_password')
# your ldap logic here
if your_condition:
raise form.ValidationErro('You have logged in..!')
return self.cleaned_data
class SettingAdmin(admin.ModelAdmin):
form = SettingForm
list_display = ('ldap_server', 'ldap_server_username', 'ldap_server_password')
admin.site.register(Setting, SettingAdmin)
Remove save() method from your model.
You can move SettingForm in forms.py file and then import it in admin.py
I hope this will help
I am working on a django project, The model CaseRegister i am trying to submit values using model form. My model class belo
- model.py
from django.db import models
from core.models import ProviderMaster,FacilityMaster,ProviderMaster,CaseMaster,CasestatusMaster
from patient.models import PatientMaster
from django.contrib.auth.models import User
from django.forms import ModelForm
from account.models import Profile
def update_id(func):
def decorated_function(*args):
data_object = args[0]
sequence_name = 'seq_%s' % data_object._meta.db_table
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT nextval(%s)", [sequence_name])
row = cursor.fetchone()
data_object.caseid = row[0]
return func(*args)
return decorated_function
class CaseRegister(models.Model):
caseid = models.DecimalField(primary_key=True, max_digits=8, decimal_places=0)
patient = models.ForeignKey(PatientMaster, on_delete=models.CASCADE, db_column='patientid')
case_startdate = models.DateField()
case_enddate = models.DateField(blank=True, null=True)
providerid = models.ForeignKey(ProviderMaster, models.DO_NOTHING, db_column='providerid', blank=True, null=True)
facilityid = models.ForeignKey(FacilityMaster, models.DO_NOTHING, db_column='facilityid', blank=True, null=True)
casetypeid = models.ForeignKey(CaseMaster, models.DO_NOTHING, db_column='casetypeid', blank=True, null=True)
casestatus = models.ForeignKey(CasestatusMaster, models.DO_NOTHING, db_column='casestatus', blank=True, null=True)
approved_date = models.DateField(blank=True, null=True)
last_modifieduser = models.ForeignKey(Profile,on_delete=models.CASCADE, db_column='last_modifieduser')
class Meta:
managed = False
db_table = 'case_register'
def __str__(self):
return self.caseid
#update_id
def save(self):
# Now actually save the object.
super(CaseRegister, self).save()
The form is created as below and mapped query set for all FK fields
- The form.py
from django import forms
from .models import CaseRegister
from patient.models import PatientMaster
from django.contrib.auth.models import User
from account.models import Profile,ProfileFaciltiyMembership
from core.models import FacilityMaster,CasestatusMaster,ProviderMaster,ProviderCategory,RoleMaster
from django.db.models import Q
import datetime
class CaseRegisterForm(forms.ModelForm):
class Meta:
model = CaseRegister
fields = ('caseid', 'patient', 'case_startdate',"case_enddate","facilityid","providerid","casetypeid","casestatus","last_modifieduser" )
def __init__(self, p,profile,request, *args, **kwargs):
super(CaseRegisterForm, self).__init__(*args, **kwargs)
print("request.method "+request.method)
if (request.method=='GET'):
print("request.method "+request.method)
self.fields['patient'].empty_label = None
self.fields['patient'].label="Patient"
self.fields['patient'].queryset = PatientMaster.objects.filter(patientid=p.patientid)
self.fields['patient'].widget.attrs = {'maxlength': 10}
self.fields['patient'].widget.attrs = {'disabled': True}
self.fields['case_startdate'].widget.attrs = {'class': 'vDateField'}
self.fields['case_startdate'].label="Date"
self.fields['case_startdate'].initial=datetime.datetime.now().date()
#self.fields['last_modifieduser'].queryset = Profile.objects.filter(user=profile.user)
self.fields['last_modifieduser'].queryset = Profile.objects.all()
self.fields['last_modifieduser'].empty_label = None
#self.fields['last_modifieduser'].widget = forms.HiddenInput()
self.fields['caseid'].required = False
self.fields['caseid'].widget = forms.HiddenInput()
self.fields['case_enddate'].widget = forms.HiddenInput()
fid = request.session["currfacility"]
self.fields['facilityid'].empty_label = None
self.fields['facilityid'].queryset = FacilityMaster.objects.filter(facilityid=fid)
self.fields['facilityid'].widget.attrs = {'disabled': True}
self.fields['casestatus'].empty_label = None
self.fields['casestatus'].queryset=CasestatusMaster.objects.filter(casestatusid=1)
facility=FacilityMaster.objects.get(pk=fid)
profiles=Profile.objects.filter(facilities=facility)
providercat = ProviderCategory.objects.get(pk=2)
self.fields['providerid'].empty_label = None
self.fields['providerid'].label="Physician"
self.fields['casetypeid'].label="Type"
self.fields['casetypeid'].empty_label = None
self.fields['casestatus'].label="Status"
criterion1 = Q(profile__in=profiles)
criterion2 = Q(pcategoryid=providercat)
rid = request.session["currrole"]
print(rid)
if rid == str(2) :
print("if")
profile = request.user.profile
pfid = profile.provider.providerid
print(pfid)
criterion3 = Q(providerid=pfid)
self.fields['providerid'].queryset = ProviderMaster.objects.filter(criterion3 & criterion2)
else:
print("else")
self.fields['providerid'].queryset = ProviderMaster.objects.filter(criterion1 & criterion2)
The below is the view and inthe GET method i am assigning a patient id and in
POST request i am not doing anything to the modelform.
- view.py
from django.shortcuts import render,redirect
from .forms import CaseRegisterForm
from .models import CaseRegister
from patient.models import PatientMaster
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView, DetailView, UpdateView
def caseregister(request):
pid =1413963
if request.method == "POST":
form = CaseRegisterForm(None,request.user.profile,request,request.POST)
#form = CaseRegisterForm(request.POST)
print(form.is_valid())
print(form.errors)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('{% url "createcase" %}')
else:
pid =1413963
p = PatientMaster.objects.get(pk=pid)
form = CaseRegisterForm(p,request.user.profile,request)
return render(request, "case_register.html", {'form': form})
While submitting the form i am getting the error - patient -This field is required message.
I tried to map query set patient in post method same as like get. I am getting the same error.
I have exhausted all avenues in trying to put together a solution for this, but my current knowledge of Python and Django can only get me so far.
I'm creating a basic ticketing system and CreateView used to work until I created a Profile model and then separated the Ticket model into its own app. There were already a couple of tickets created when I refactored my code which is why I know ListView works, DeleteView works as well as DetailView. CreateView works until I hit the save button.
My views and models are below; I hope someone can please help me sort this out.
Ticket Model
from django.db import models
from django.contrib.auth.models import User
....
from qcapp.models import Profile
class Ticket(models.Model):
# Relations
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="tickets", verbose_name="user")
# Attributes
title = models.CharField(max_length=250, verbose_name="Title", help_text="Enter a Ticket Title")
color = models.CharField(max_length=7,
default="#ffffff",
validators=[RegexValidator("(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)")],
verbose_name="Color",
help_text="Enter the hex color code, like #ccc or #cccccc")
description = models.TextField(max_length=1000)
created_date = models.DateTimeField(default=timezone.now, verbose_name='Created Date')
created_by = models.ForeignKey(User, related_name='created_by_user')
# Attributes
# Object Manager
objects = managers.ProjectManager()
# Meta and String
class Meta:
verbose_name = "Ticket"
verbose_name_plural = "Tickets"
ordering = ("user", "title")
unique_together = ("user", "title")
def __str__(self):
return "%s - %s" % (self.user, self.title)
def get_absolute_url(self):
return reverse('ticket_detail', args=[str(self.id)])
Ticket View (CreateView Only)
# -*- coding: utf-8 -*-
...
from django.views.generic import CreateView, UpdateView, DeleteView
...
from .models import Ticket
...
class TicketCreate(CreateView):
model = Ticket
template_name = "tickets/ticket_form.html"
fields = ['title', 'description']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super(TicketCreate, self).form_valid(form)
...
Profile Model(Imported Into Ticket Model)
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from . import managers
class Profile(models.Model):
# Relations
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile", verbose_name="user")
# Attributes
interaction = models.PositiveIntegerField(default=0, verbose_name="interaction")
# Attributes
# Object Manager
objects = managers.ProfileManager()
# Custom Properties
#property
def username(self):
return self.user.username
# Methods
# Meta and String
class Meta:
verbose_name = "Profile"
verbose_name_plural = "Profiles"
ordering = ("user",)
def __str__(self):
return self.user.username
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile_for_new_user(sender, created, instance, **kwargs):
if created:
profile = Profile(user=instance)
profile.save()
It looks like you need to add the following to your TicketCreate class in the form_valid function:
form.instance.user = Profile.objects.get(user=self.request.user)
Let me know if that works!