I would like to add the option for customers on my site to cancel their orders, but I'm having trouble getting it to work. I've created the view and the URL, but something is evidently wrong with them. Here's how it looks on the site:
delete_order View:
def delete_order(request, pk):
""" Cancel an order from the profile page """
order = Order.objects.get(id=pk)
if request.method == "POST":
order.delete()
return redirect('/')
return render(request, "delete_order.html", {'item': order})
Order Model:
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
full_name = models.CharField(max_length=50, blank=False)
phone_number = models.CharField(max_length=20, blank=False)
country = models.CharField(max_length=40, blank=False)
postcode = models.CharField(max_length=20, blank=True)
town_or_city = models.CharField(max_length=40, blank=False)
street_address1 = models.CharField(max_length=40, blank=False)
street_address2 = models.CharField(max_length=40, blank=False)
county = models.CharField(max_length=40, blank=False)
date = models.DateField()
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return "{0}-{1}-{2}".format(self.id, self.date, self.full_name)
Django Url:
url(r'^delete_order/(?P<pk>\d+)/$', delete_order, name="delete_order")
Html Url:
<a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Cancel</a>
This is the error I am getting:
Any feedback is greatly appreciated!
Maybe you just forgot to add end slash in the main urls.py file?
When you connect app urls to main urls.py file you need to check that url link looks like:
path('checkout/', include('checkout.urls')),
def order_remove(request,pk):
order = Order.objects.filter(pk=pk).first()
order.delete()
return redirect('#your path#',pk)
user first to get that particular order
path('delete/<int:pk>', views.delete_order, name="delete_order")
Related
How do add new record every time I update the screen? instead it updates the existing record.?
Here are the models.
class Dealer(models.Model):
city = models.CharField('City', max_length=30, blank=True, null=True)
contact_name = models.CharField('Contact name', max_length=250, blank=True, null=True)
dealer_id = models.CharField('dealer_id', max_length=50, primary_key=True)
dealership_name = models.CharField('Dealership name', max_length=100, blank=True, null=True)
dsr = models.CharField('DSR', max_length=50, blank=True, null=True)
email = models.EmailField('Email', blank=True, null=True)
fax = models.CharField('Fax', max_length=20, blank=True, null=True)
dealer_notes = models.TextField('notes', blank=True, null=True)
phone = models.CharField('Phone', max_length=20, blank=True, null=True)
rating = models.CharField('Rating', max_length=20, blank=True, null=True)
state = models.CharField('State', max_length=5, blank=True, null=True)
street = models.CharField('Street', max_length=60, blank=True, null=True)
zip = models.CharField('Zip', max_length=10, blank=True, null=True)
def __str__(self):
return self.dealer_id
class Activity(models.Model):
dealer_id = models.ForeignKey(Dealer, on_delete=models.CASCADE)
activity_number = models.PositiveIntegerField(default=1)
date_created = models.DateField('date created', blank=True, null=True)
created_by = models.CharField('created_by', max_length=50, blank=True, null=True)
type = models.CharField('state', max_length=50, blank=True, null=True)
activity_notes = models.TextField(max_length=500, blank=True, null=True)
def __str__(self):
return f"{self.dealer_id} {self.activity_number}"
When it lands in dealer notes page it will get the details from the user to enter model fields and save.For each record there can be many number of activity notes. But when I tried to add a new note it updates the existing one, i want it create a new record.
def create_notes(request, dealer_id):
item, _ = Activity.objects.get_or_create(dealer_id_id=dealer_id)
form = ActivityForm(instance=item)
if request.method == 'POST':
form = ActivityForm(request.POST, instance=item)
if form.is_valid():
try:
form.save()
except:
pass
else:
return redirect('dealernotes/' + request.post.get('dealer_id_id'))
return render(request,
'dealernotes.html',
{'form': item,},
)
Can you help to create a new note every time? by activity number i should be able to update as well.
urls:
path('dealernotes/<str:dealer_id>?/', views.update_notes, name='dealernotes')
How do I fix this issue?
Don't use get_or_create and instead just use create
item = Activity.objects.create(dealer_id_id=dealer_id)
Edit 2 (scraping Edit1)
Here, Try to restructure it so that Activity is only created when you submit the form.
Note: We're changing the template, don't forget about that
def create_notes(request, dealer_id):
if request.method == 'POST':
form = ActivityForm(request.POST)
if form.is_valid():
try:
form.save()
except:
pass
else:
# debugging error:
print(form.errors.as_data())
return redirect('dealernotes/' + request.post.get('dealer_id_id'))
dealerObj = Dealer.objects.get(pk=dealer_id)
form = ActivityForm(initial={'dealer_id' : dealerObj})
data = {
'form': form,
}
return render(request, 'dealernotes.html', data)
Template
We're going to replace the PK input with a dealer_id, that way the form is valid on the post
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
I have a Django website and part of it lists data in rows with the primary key in one of the columns. This works great except for when I have separate users. I'm using foreign keys in each model to separate the different user's data. My problem is that the data for each user has to have a number in the column that increments numerically and does not have any spacing, for instance, 1,2,3,5 is bad. If User1 is uploading data and halfway through User2 uploads a row of data then if I use the primary key the numbers will not be in numerical order for each user and will read 1,2,3,5 for User1 and 4 for User2. I tried forloop counter but I need the numbers all the be assigned to the row and not change if one is deleted. Ive been at this for 2 weeks and am having a really hard time describing my problem. I think I need somesort of Custom User Primary Key, a primary key for each user. Any help at this point is greatly appreciated, Thanks!
I finally figured it out after about a week.
models.py:
class Sheet_Building(models.Model):
user = models.ForeignKey(User, default=True, related_name="Building", on_delete=models.PROTECT)
count_building = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True, verbose_name='Inspection Date')
time = models.TimeField(blank=True, null=True, verbose_name='Inspection Time')
inspection_type = models.CharField(max_length=16, choices=INSPECTION_TYPE_BI, blank=True, null=True, verbose_name='Inspection Type')
flname = models.CharField(max_length=25, blank=True, null=True, verbose_name='Inspector')
report_date = models.DateField(blank=True, null=True, verbose_name='Report Date')
department = models.CharField(max_length=29, choices=DEPARTMENT_BI, blank=True, null=True, verbose_name='Department')
responsible_name = models.CharField(max_length=25, blank=True, null=True, verbose_name='Responsible Person')
building_address = models.CharField(max_length=52, choices=BUILDING_ADDRESS, blank=True, null=True, verbose_name='Building and Address')
floor = models.CharField(max_length=8, choices=FLOOR_LEVEL_BI, blank=True, null=True, verbose_name='Floor / Level')
room = models.CharField(max_length=35, blank=True, null=True, verbose_name='Area / Room')
location = models.CharField(max_length=10, choices=LOCATION_BI, blank=True, null=True, verbose_name='Location')
priority = models.IntegerField(blank=True, null=True, verbose_name='Priority')
hazard_level = models.CharField(max_length=20, choices=HAZARD_LEVEL_BI, blank=True, null=True, verbose_name='Hazard Level')
concern = models.CharField(max_length=31, choices=CONCERN_BI, blank=True, null=True, verbose_name='Concern')
codes = models.CharField(max_length=51, choices=CODES_BI, blank=True, null=True, verbose_name='Element and Code')
correction = models.TextField(max_length=160, blank=True, null=True, verbose_name='Corrective Action')
image = models.ImageField(blank=True, null=True, verbose_name='Image', upload_to='gallery')
notes = models.TextField(max_length=500, blank=True, null=True, verbose_name="Inspector's note")
class Meta:
ordering = ['-pk']
def __str__(self):
return self.flname or 'None'
def get_absolute_url(self):
return reverse('list_building')
view.py:
def adddata_building(response):
if response.method == 'POST':
form = SheetForm_Building(response.POST, response.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = response.user #User
if Sheet_Building.objects.filter(user=response.user).values_list('count_building'):
instance.count_building = Sheet_Building.objects.filter(user=response.user).aggregate(count_building=Max('count_building'))['count_building'] + 1 #Count
else:
instance.count_building = 1
instance.save()
response.user.Building.add(instance)
return redirect('list_building')
else:
form = SheetForm_Building()
return render(response, 'sheets/add_data/add_data_building.html', {'form': form})
HTML:
{% for post in object_list %}
{{ post.count_building }}
{% enfor %}
[![Nurse admin page[![][1]][1][models.py
from django.db import models
#Work Related aka Department and Work Shift
class Department(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class WorkShift(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
start_datetime = models.DateTimeField(null=True, blank=True)
end_datetime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.name
#Personel Related aka Employees and Patients
class Doctor(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Nurse(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
reports_to = models.OneToOneField(Doctor, default="", blank=True, null=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return str(name)
class Patient(models.Model):
STATUS = (
('Sick', 'Sick'),
('Healing', 'Healing'),
('Cured', 'Cured'),
('Deceased', 'Deceased'),
)
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .models import Doctor, Nurse, Patient
from django.http import HttpResponse
# Create your views here.
def index(request):
patient = Patient.objects.all()
nurse = Nurse.objects.all()
doctor = Doctor.objects.all()
total_patient = patient.count()
sick = patient.filter(status='Sick').count()
healing = patient.filter(status='Healing').count()
cured = patient.filter(status='Cured').count()
total_nurse = nurse.count()
# if request.method == 'POST':
# form =
context = {
'patient':patient, 'nurse':nurse,
'doctor':doctor, 'total_patient':total_patient,
'sick':sick, 'healing':healing, 'cured':cured,
'total_nurse':total_nurse
}
return render(request, 'lifesaver/index.html', context)
def patient(request):
patient = Patient.objects.all()
total_patient = patient.count()
context = {
'patient':patient,
'total_patient':total_patient
}
return render(request, 'lifesaver/patient.html', context)][1]
forms.py
from django import forms
from .models import Doctor, Nurse, Patient
from django.auth.contrib.forms import UserCreationForm
class DoctorForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Doctor',
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=department.objects.all)
class NurseForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
class PatientForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Patient'
'class': 'form-control'
}))
HTML for patient
{% extends 'lifesaver/main.html' %}
{% block content %}
<h1>SUPERSTAR</h1>
{% for patient in patient %}
{{patient.name}}
{% endfor %}
{% endblock content %}
I get this error when I go to try to add another Nurse. The URL is http://127.0.0.1:8000/admin/lifesaver/nurse/add/. Everything else behaves as expected, except the adding the Nurse part.
If I try to remove the def __str___ part, the error still displays. I believe the error lies in the:
work_shift = models.OneToOneField(WorkShift, default="",
blank=True,
null=True,
on_delete=models.CASCADE)
part since when I included that code, the error spawned. Furthermore, the code is to add a work shift to certain employees and the goal is that the employees shift will display in their profile.
How do I fix this issue?
EDIT: When accessing the HTML template, the web page behaves as expected and has no issues.
In your Nurse model replace this:
def __str__(self):
return str(Nurse.name)
with this:
def __str__(self):
return self.name
My problem is have two models job and company and i want to get all jobs in this company
My urls.py:
url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'),
My views.py:
def job_at_company(request, slug):
return render(request, 'jobs.html')
My models.py:
class Company(models.Model):
title = models.CharField(max_length=100, blank=False)
slug = models.SlugField(blank=True, default='')
city = models.CharField(max_length=100, blank=False)
contact_info = models.CharField(max_length=100, blank=False, default=0)
facebook = models.CharField(max_length=100, blank=True)
twitter = models.CharField(max_length=100, blank=True)
linkedin = models.CharField(max_length=100, blank=True)
logo = models.ImageField(upload_to="logo", default=0)
class Jobs(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True, default='')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
price = models.IntegerField(default='')
Description = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')
in the views.py we can add this
def job_at_company(request, slug):
results = Jobs.objects.filter(company__slug=slug)
context = {'items':results}
return render(request, 'jobs.html',context)
Suppose you pass id in the url. The id is the primary key of the company. You would have to modify your url to accept id like -
url(r'^jobs/(?P<slug>[\w-]+)/(?P<pk>[\d]+)$', views.job_at_company, name='job_at_company')
And modify your views.py -
def job_at_company(request, slug, pk):
jobs_qs = Jobs.objects.filter(company__id=pk)
return render(request, 'jobs.html', {'jobs': jobs_qs})
And use it in your html like -
{% for job in jobs %}
{{job.title}}
{% endfor %}
Look at this link. Django's documentation is helpful, follow that
I would like to display only the pictures uploaded by the creator (user) on their individual profiles.
How would I alter my code to display that?
Thank you!
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
def get_image_url(self):
return "%s/%s" %(settings.MEDIA_URL, self.image)
def get_absolute_url(self):
return "%s/%s" %(self.creator, self.slug)
views.py:
#login_required
def account_home(request, username):
try:
u = MyUser.objects.get(username=username)
except:
u = None
photo_set = Photo.objects.all()
context = {
"photo_set": photo_set,
"notifications": notifications,
"transactions": transactions
}
return render(request, "accounts/account_home.html", context)
.html:
{% for photo in photo_set %}
<img src="{{ photo.get_image_url }}" class='img-responsive'>
<hr/>
{% endfor %}
You have a ForeignKey to user, so you can just filter the photos by that:
photo_set = Photo.objects.filter(creator=u)
or even better use the reverse relationship:
photo_set = u.photo_set.all()
Also, never ever ever ever use a blank except statement in your code. The only exception you are expecting the get to raise is MyUser.DoesNotExist, so you should catch that only.