Django Views: DoesNotExist isn't working - django

In the view below, I prevent creation of a meeting with the same date and time. But anyhow, this code results in creating a recurrent meeting.
def new_meeting_board(request):
if User.is_authenticated:
username = request.user.username
else:
return HttpResponseRedirect('/login/board/')
if request.method == 'POST':
form = new_meetingForm(request.POST)
now = datetime.datetime.now()
if form.is_valid():
clash = 1
user = User.objects.get(username = username)
try:
meet_check = meeting.objects.get(date = form.cleaned_data['date'], time = form.cleaned_data['time'])
except meeting.DoesNotExist:
clash = 0
if clash == 1:
form = new_meetingForm()
variables = RequestContext(request, {
'username': username,
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
else:
mem = memo(
snd_username = user,
rcv_username = form.cleaned_data['reciever'],
subject = 'Meeting',
date = str(now.year) + '-' + str(now.month) + '-' + str(now.day),
time = str(now.hour) + ':' + str(now.minute),
)
mem.save()
mee = mem.meeting_set.create(
snd_username = username,
rcv_username = mem.rcv_username,
status_username = '0',
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
venue = form.cleaned_data['venue'],
)
mee.save()
return HttpResponseRedirect('/dashboard/board/' + username)
else:
form = new_meetingForm()
variables = RequestContext(request, {
'username': username,
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
The except portion of the try/except block does not seem to work for some reason. Please help.

meeting.objects should probably be Meeting.objects

There are multiple reformatting and optimization can be done in your code. Rather than using get(), you can use get_or_create to optimize code. You can write the code like this:
def new_meeting_board(request):
if not request.user.is_authenticated(): # there is a mistake in your code, its not User.is_authenticated.
return HttpResponseRedirect('/login/board/')
if request.method == 'POST':
form = new_meetingForm(request.POST)
now = datetime.datetime.now()
if form.is_valid():
user = request.user
meet_obj, meet_check = meeting.objects.get_or_create(
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
subject = 'Meeting',
snd_username=user,
rcv_username = form.cleaned_data['reciever']
)
if meet_check is True:
form = new_meetingForm()
variables = RequestContext(request, {
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
else:
mee = meet_obj.meeting_set.create(
snd_username = username,
rcv_username = meet_obj.rcv_username,
status_username = '0',
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
venue = form.cleaned_data['venue'],
)
mee.save()
return HttpResponseRedirect('/dashboard/board/' + username)
else:
form = new_meetingForm()
variables = RequestContext(request, {
'form': form, # no need to send username, You can access it in the template by putting {{ request.user.username }}
})
return render_to_response('new_meeting_board.html', variables)

Related

the pgAdmin4 save null value

I want to save the data of the textfiled that take the location name and other filed from the html and save it in pgadmin4 by using the def in my view when I enter the value in html it is add but it shows me null in pgAdmin
this is my view
def location(request):
if request.method == 'POST':
form = request.POST
location_id = form.get(' location_id')
location_name = form.get('location_name')
location_address = form.get('location_address')
lat = form.get('lat')
lag_y = form.get('lag_y')
user_id = request.session['user_id']
print(form)
data_insert = MapModel.objects.create(location_id=location_id,
location_name=location_name,
location_address=location_address,
lat_x=lat,
lag_y=lag_y,)
if data_insert:
json_data = {'msg': " data added succssfully",
'id': data_insert.location_id
}
return JsonResponse(json_data)
else:
json_data = {'msg': " try agine",
'id': '',
}
return JsonResponse(json_data)
else:
return render(request, 'new_file.html')

Django - when 1 user accesses the same view with different url kwargs - why am I getting cross over of data?

I have a django app that contains samples. On my home page, it displays a table with many samples, containing hyperlinks to the 'Sample page' - which is a view get request.
When I click on several of these samples in tandem, to open new tabs, each to a specific tab - I am getting cross over of data - I.e the url sample_id kwargs is different, but the page is displaying the same results which is incorrect. When i refresh the page, the correct sample data appears.
Is there any way around this happening is a user is to open several different sample tabs at the same time? This would impact on results and could cause errors in the workflow offered by the django app.
*is this because my view is processing too much, so the different view request=s ends up over lapping ?
Edit: adding view:
class FilterVariantSampleView(ReportView, ReportPDFGenerator, FileGenerator, limsQuery):
template_name = os.path.join(
'results',
'filter_templates',
'sample_page.html'
)
type = 'sample'
choice = False
group_required = ['filter']
def get(self, request, *args, **kwargs):
self.user = request.user
self.obtain_sample_information(kwargs)
self.obtain_patient_information()
self.obtain_header()
# create sample notes form
sample_notes_form = SampleNotesForm(
instance=self.sample_obj)
self.context['sample_notes_form'] = sample_notes_form
self.create_variant_filter_formset()
panel_list = [o.run_id.machine_panel_id.panel_id
for o in self.all_sr_obj]
if len(panel_list):
self.panel_obj = panel_list[0]
# self.generate_hotspot_form()
self.assess_fails()
crs_qs = ClinicallyReportedSample.objects.filter(
sample_id=self.sample_obj)
crs_qs = crs_qs.exclude(
reported_on_panel__parent_panel__isnull=False,
primary_technical_report=False,
final_technical_report=False
)
remove_report_form_list = []
lims_molecular_results = self.query_lims_clone_molecular(
qs=crs_qs)
mol_df = lims_molecular_results[0]
summary = lims_molecular_results[1]
self.context['summary'] = summary
if crs_qs.count() == 1:
crs_obj = crs_qs[0]
self.context['crs_qs'] = crs_qs
remove_report_form = RemoveDiagnosticReportForm(
instance=crs_obj)
remove_report_form_list.append(remove_report_form)
else:
messages.add_message(self.request, messages.WARNING,
'This sample has been sequenced on multiple panels.')
self.context['crs_qs'] = crs_qs
lims_molecular_results = self.query_molecular_lims(
sample_obj=self.sample_obj)
for crs_obj in crs_qs:
remove_report_form = RemoveDiagnosticReportForm(
instance=crs_obj)
remove_report_form_list.append(remove_report_form)
if crs_obj.diagnostic_report_required == False:
messages.add_message(self.request, messages.WARNING,
f'This sample does NOT require a diagnostic reoprt '
f'for the {crs_obj.reported_on_panel} panel.')
self.context['remove_report_form_list'] = remove_report_form_list
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
"""
"""
self.define_variant_filter_formset()
submit = request.POST.get('submit', None)
if submit:
if submit == 'Modify sample':
logger.info('')
logger.info('Sample: {}'.format(self.sample_obj))
logger.info("Submit: '{}'".format(submit))
# pass POST dict to formset
modify_formset = self.CRVFormSet(request.POST, prefix='crv')
# validate
if modify_formset.is_valid():
logger.info('Modify Variant Formset valid')
logger.info('')
self.modify_variants(modify_formset)
self.modify_sample()
return HttpResponseRedirect(
reverse('results:filter_variant_sample',
kwargs={'sample_id': self.sample_obj.id}))
else:
msg = ('Modify ClinicallyReportedVariant '
f'Formset NOT valid: {modify_formset.errors}')
logger.error(msg)
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(
reverse('results:filter_variant_sample',
kwargs={'sample_id': self.sample_obj.id}))
elif submit == 'Update':
form = RemoveDiagnosticReportForm(request.POST,
instance=ClinicallyReportedSample.objects.get(
sample_id=kwargs['sample_id'],
reported_on_panel=request.POST['reported_on_panel'])
)
if form.is_valid():
logger.info('RemoveDiagnosticReportForm is valid')
try:
form.save()
except Exception as e:
logger.error(e)
else:
msg = f'RemoveDiagnosticReportForm is NOT valid: {form.errors}'
logger.error(msg)
messages.add_message(self.request, messages.ERROR, msg)
return HttpResponseRedirect(request.path_info)
elif 'Download' in submit:
panel_name = submit.split(' ')[1]
self.panel_obj = Panel.objects.get(panel_name=panel_name)
self.crs_obj = ClinicallyReportedSample.objects.get(
sample_id=self.sample_obj, reported_on_panel=self.panel_obj)
if 'panel data' in submit:
logger.info(f'Downloading data for {self.sample_obj}')
if self.crs_obj.sample_id.external_dept.site in ['Newcastle', 'Sheffield']:
downloaded_data = self.download_yne_data()
if downloaded_data:
self.crs_obj.downloaded_data = True
self.crs_obj.downloaded_data_user = request.user
self.crs_obj.downloaded_data_date = timezone.now()
self.crs_obj.save()
return downloaded_data
else:
return HttpResponseRedirect(self.request.path_info)
elif 'report' in submit:
logger.info(f'Downloading report for {self.sample_obj}')
# update crs_obj
self.crs_obj.download_technical_report = True
self.crs_obj.download_technical_report_user = self.user
self.crs_obj.download_technical_report_date = timezone.now()
self.crs_obj.save()
# return HttpResponseRedirect(self.request.path_info)
lims_molecular_results = self.query_molecular_lims(
sample_obj=self.sample_obj)
mol_df = lims_molecular_results[0]
summary = lims_molecular_results[1]
if mol_df.empty:
logger.info('No molecular tests done')
self.latex_context['gene_status'] = False
else:
gene = mol_df[
(mol_df['test_name'] == 'gene') &
(mol_df['status'] == 'complete')
]
if gene.empty:
self.context['gene'] = False
else:
msg = ("gene Sanger in-fill test has been completed.{}")
result = gene['result'].to_string(index=False)
if result == 'normal or wild-type':
msg = msg.format(' No detectable variants.')
msg_info = messages.INFO
gene_df = pd.DataFrame()
elif result == 'failed':
msg = msg.format(' Unfortunately the test failed.')
msg_info = messages.WARNING
gene_df = pd.DataFrame()
elif result == 'mutated' or result == 'suspicious':
gene_df = self.get_gene_result(gene, technical_report=True)
if result == 'suspicious':
msg = msg.format(' There is suspicion of a variant '
'(see below for more information).')
else:
msg = msg.format(' A variant was detected '
'(see below for more information).')
msg_info = messages.INFO
else:
msg = msg.format(' Error - contact administrator.')
msg_info = messages.ERROR
result = 'error'
gene_df = pd.DataFrame()
self.latex_context['gene_status'] = result
self.latex_context['gene_df'] = gene_df
logger.info(msg)
messages.add_message(self.request, msg_info, msg)
print(self.latex_context)
# call method from TechnicalReportPDFGenerator
self.generateReport(report_type='technical')
response = self.download_technical_report()
return response
return render(request, self.template_name, self.context)
This may be due to the cache of your browser, are you sure the calls are going through the first time ?

I am getting object has no attribute update in my Django Website

I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks
views.py
def UpdateReservation(request, pk):
table_exists = Reservation.objects.get(id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
if request.POST['table']:
request.POST = request.POST.copy()
table_exists = Reservation.objects.get(id=pk)
try:
if table_exists:
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists)
resrv.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
except Exception as e:
messages.error(request, "Unknown error" + str(e))
return redirect(request.path)
context = {"form":form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update'
It is better to validate the form and update the individual fields with respective values and then save the object. The view should be as follows:
from django.shortcuts import get_object_or_404
def UpdateReservation(request, pk):
table_exists = get_object_or_404(Reservation, id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
form = ReservationForm(request.POST, instance=table_exists)
if form.is_valid():
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
context = {"form": form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
You should use model like this:
table_exists = Reservation.objects.get(id=pk)
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.table = table_exists
table_exists.save()

Django. Contains 2 slightly different forms but second form's data being saved in both

Here are my lines dealing with the two forms :
user = request.user
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
The data submitted in second form is being saved in both liked and disliked.
I have used User foreignkey in both the liked and disliked models.
Here is the complete function :
def collect(request):
context = RequestContext(request)
submitted = False
if request.method == 'POST':
data = request.POST
user_liked_form = UserLikedForm(data = request.POST)
user_disliked_form = UserDislikedForm(data = request.POST)
# user_id = data["user_id"]
user = request.user
if user_liked_form.is_valid() and user_disliked_form.is_valid():
# user_liked_form.save(commit = True)
# user_disliked_form.save(commit = True)
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
submitted = True
else:
print user_liked_form.errors, user_disliked_form.errors
else:
user_liked_form = UserLikedForm()
user_disliked_form = UserDislikedForm()
return render_to_response(
'collect.html',
{'user_liked_form': user_liked_form, 'user_disliked_form': user_disliked_form, 'submitted': submitted},
context)
It sounds like your UserLikedForm and UserDislikedForm have the same field names and when the form is submitted, only the second value comes through in request.POST. To fix this, you will need to add a prefix to the forms:
user_liked_form = UserLikedForm(prefix='liked')
user_disliked_form = UserDislikedForm(prefix='disliked')
That way when the forms are rendered, each form will have unique field names.

Django Can't save form data on database

I'm trying write a small app while I'm learning django.However, when I try to save the form data in database, some problems happen to me.I use python3.4 and django 1.8.4, my database is MySql
The first problem I met is that the database doesn't have any data
this is my model code:
SUBJECT_CHOICES = (
('computerscience', '计算机科学导论'),
('C-sharp', 'C#'),
('cplusplus', 'C++'),
('CCNA', 'CCNA'),
('ACM', 'ACM'),
('linux', 'linux'),
('java', 'java'),
('python', 'python')
)
class Homework(models.Model):
handin_date = models.DateTimeField('交作业时间')
subject = models.CharField(verbose_name = '课程', default = '计算机科学导论', max_length = 20, choices = SUBJECT_CHOICES)
code = models.TextField(verbose_name = '代码', default = '')
xuehao = models.CharField(verbose_name = '学号', default = '', max_length = 9)
name = models.CharField(verbose_name = '姓名', default = '', max_length = 10)
this is my view code:
def cshomework(request):
if request.method == 'POST':
form = HomeworkForm(request.POST)
if form.is_valid():
return render(request, 'blog/success.html', { 'title': '交作业成功' })
else:
form = HomeworkForm(initial = { 'xuehao': '学号', 'name': '姓名', 'subject': '计算机科学导论', 'handin_date': dt.now(), 'code': '你的代码' })
return render(request, 'blog/cshomework.html', { 'title': '交作业', 'form': form })
In this way there's nothing in my database
The seconde question is when I tried another way, I get a None value in my datebase
The same model code as before
Here is my view code:
def cshomework(request):
if request.method == 'POST':
form = HomeworkForm(request.POST)
if form.is_valid():
return render(request, 'blog/success.html', { 'title': '交作业成功' })
else:
homework = Homework.objects.create(xuehao = '学号', name = '姓名', subject = '计算机科学导论', handin_date = dt.now(), code = '你的代码')
form = HomeworkForm(instance = homework)
return render(request, 'blog/cshomework.html', { 'title': '交作业', 'form': form })
the '课程' means 'subject'
How can I deal with these problems?
I' really appriciate your help!
After all check if form.is_valid(), you need save the form.
def cshomework(request):
if request.method == 'POST':
form = HomeworkForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'blog/success.html', { 'title': '交作业成功' })
else:
form = HomeworkForm(initial = { 'xuehao': '学号', 'name': '姓名', 'subject': '计算机科学导论', 'handin_date': dt.now(), 'code': '你的代码' })
return render(request, 'blog/cshomework.html', { 'title': '交作业', 'form': form })
At the second way, you are creating a new HomeWork everytime a URL is accessed, without submit any post data.