I have this view that allows me to delete data. But the I keep getting the this error below whenever I click on the delete button. what I want to archive is when a user clicks the on GUARDAR, that model data should be deleted. But I keep getting the NoReverseMatch error bellow
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'book_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/delete/$']
View.py
def book_delete(request, pk):
envío = get_object_or_404(Control, pk=pk)
data = dict()
if request.method == 'POST':
envío.delete()
data['form_is_valid'] = True
envíos = Control.objects.all().order_by('-fecha')
data['html_book_list'] = render_to_string('includes/partial_envio_list.html', {
'envíos': envíos
})
else:
context = {'envío': envío}
data['html_form'] = render_to_string('includes/partial_envío_delete.html', context, request=request)
return JsonReson
Model.py
class Control(models.Model):
control_id = models.AutoField(primary_key=True)
cliente = models.ForeignKey(Cliente, null=True, blank=True, on_delete=models.CASCADE)
familia = models.ForeignKey(Familia, null=True, blank=True, on_delete=models.CASCADE)
estado = models.ForeignKey(Estado, null=True, blank=True, on_delete=models.CASCADE)
fecha = models.DateField(blank=True, null=True)
Fecha_desde = models.DateField(blank=True, null=True)
Fecha_hasta = models.DateField(blank=True, null=True)
control_id_hash = models.CharField(max_length=260, db_collation='utf8_unicode_ci')
control_codigo = models.CharField(max_length=50, db_collation='utf8_unicode_ci')
URL
path('envío/<int:pk>/delete/', views.book_delete, name='book_delete'),
template
<form method="post" action="{% url 'agric:book_delete' control.pk %}" class="js-book-delete-form">
{% csrf_token %}
<div class="modal-body">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
<div class="modal-status bg-danger"></div>
<div class="modal-body text-center py-4">
<h3>Are you sure?</h3>
<p class="lead">Do you really want to delete envío <strong>{{ control.control_codigo }}</strong>?</p>
</div>
<div class="modal-footer" style="background:#f4f5f7">
<button type="button" class="btn btn-default" data-bs-dismiss="modal">CANCELAR</button>
<button type="submit" class="btn modelbuttun btn-danger ">GUARDAR</button>
</div>
</div>
</fo
Related
I am trying to manually render options for a select filed in a django template. When I submit the form I get an error: "Select a valid choice. That choice is not one of the available choices." The error message also asks for required fields which I have provided.
locations models.py
class Location(models.Model):
name = models.CharField(max_length=20)
is_source = models.BooleanField(default=False)
is_destination = models.BooleanField(default=False)
def __str__(self):
return self.name
orders models.py
class Order(models.Model):
order_number = models.IntegerField(unique=True)
order_date = models.DateField(auto_now_add=True)
type = models.CharField(max_length=15, choices=TYPES)
source = models.ForeignKey(Location, default=1, on_delete=models.SET_DEFAULT, related_name='ordered_here')
destination = models.ForeignKey(Location, default=1, on_delete=models.SET_DEFAULT, related_name='delivered_here')
items = models.TextField()
assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders_to_serve')
customer = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders_made')
status = models.CharField(max_length=15, choices=STATUSES)
orders forms.py
class OrderForm(ModelForm):
source = forms.ModelChoiceField(queryset=Location.objects.filter(is_source=True))
destination = forms.ModelChoiceField(queryset=Location.objects.filter(is_destination=True))
class Meta:
model = Order
fields = ['source', 'destination', 'items']
def save(self, commit=True):
instance = super().save(commit=False)
instance.order_number = math.floor(time.time())
instance.type = 'Purchase'
instance.customer = self.context.get('request').user
instance.status = 'New'
if commit:
instance.save()
return instance
orders create.html
<form class="" method="POST">
{% csrf_token %}
<h1 class='text-center'>Make an order</h1>
<div class='row'>
<div class='col-md-6 px-2'>
<span class="fw-bold mx-2">Buy from</span>
<div class="control-container border-primary d-flex align-items-center">
<i class="fa fa-map"></i>
<select class="control ms-1 flex-grow-1" type="text" name="{{form.source.html_name}}" required >
{% for value,label in form.source.field.choices %}
<option value="{{value}}">{{label}}</option>
{% endfor %}
</select>
</div>
</div>
<div class='col-md-6 px-2'>
<span class="fw-bold mx-2">Receive in</span>
<div class="control-container border-primary d-flex align-items-center">
<i class="fa fa-map"></i>
<select class="control ms-1 flex-grow-1" type="text" name="{{form.destination.html_name}}" required >
{% for value,label in form.destination.field.choices %}
<option value="{{value}}">{{label}}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class='row'>
<div class='col-12 px-2'>
<span class="fw-bold mx-2">List items (e.g. 2 X Luxaire Double Bed matress)</span>
<div class="control-container border-primary d-flex align-items-center">
<textarea class="control ms-1 flex-grow-1" rows="10" name="{{form.items.html_name}}" placeholder='e.g. 2 X Luxaire Double Bed matress' required></textarea>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary w-100 ">Order</button>
</form>
orders view.py
class OrderUpdateView(generic.edit.UpdateView):
model = Order
template_name = 'orders/update.html'
context_object_name = 'order'
form_class = OrderForm
I have eventually solved the problem by making the customer field in the order model nullable. I also had given my textarea in the order create template a wrong field name. All is well now.
you cannot do this even if you managed to make the form ignore this error the model will raise the same error elso because you just tell him to select a value from given values ... if you wanna make it dynammic then make it as noraml CharFied()
I am creating a filter in heatmap where the filter will only extract the date from and to date transaction only. I am not sure with the codes on the filter date but I have not received an error, It only goes top of the page. My HTML for date is MM/DD/YYYY. I am not sure if it helps. But how can I embed filter between dates? Thank you
Views
def index_map(request):
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__date__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
print(df)
# coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1]
map1 = folium.Map(location=[14.676208, 121.043861],
zoom_start=12,
)
# df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date'])
# mapquestopen
fg3=folium.FeatureGroup(name='Map with Markers', show=True)
map1.add_child(fg3)
# marker_cluster = MarkerCluster().add_to(fg)
folium.TileLayer(('openstreetmap'), attr='openstreetmap').add_to(map1)
# folium.TileLayer('mapquestopen', attr='mapquestopen').add_to(map1)
# folium.TileLayer('MapQuest Open Aerial', attr='MapQuest Open Aerial').add_to(map1)
folium.TileLayer('cartodbpositron', attr='cartodbpositron').add_to(map1)
folium.TileLayer('cartodbdark_matter', attr='cartodbdark_matter').add_to(map1)
plugins.Fullscreen(position='topright').add_to(map1)
folium.LayerControl().add_to(map1)
for id,row in df.iterrows():
folium.Marker(location=[row['user_report__latitude'],row['user_report__longitude']], icon=folium.Icon(icon="car", prefix='fa') ,popup=row['accident_factor']).add_to(fg3)
# folium.Marker(coordenadas).add_to(map1)
# df['user_report__date'] = df['user_report__date'].sort_values(ascending=True)
# data = []
# for _, d in df.groupby('user_report__date'):
# data.append([[row['user_report__latitude'], row['user_report__longitude'], row['accident_factor']] for _, row in d.iterrows()])
map1 = map1._repr_html_()
context = {
'map1': map1
}
return render(request, 'index1.html', context)
Views
class UserReport(models.Model):
PENDING = 1
APPROVED = 2
REJECTED = 3
STATUS = (
(PENDING, 'Pending'),
(APPROVED, 'Approved'),
(REJECTED, 'Rejected')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=250, blank=True)
address = models.CharField(max_length=250)
country = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=50, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
pin_code = models.CharField(max_length=6, blank=True, null=True)
latitude = models.FloatField(max_length=20, blank=True, null=True)
longitude = models.FloatField(max_length=20, blank=True, null=True)
upload_photovideo = models.FileField(upload_to='incident_report/image', blank=True, null=True)
date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
time = models.TimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
status = models.PositiveSmallIntegerField(choices=STATUS, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_status(self):
if self.status == 1:
incident_status = 'Pending'
elif self.status == 2:
incident_status = 'Approved'
elif self.status == 3:
incident_status = 'Rejected'
return incident_status
def save(self, *args, **kwargs):
super(UserReport, self).save(*args, **kwargs)
if self.upload_photovideo:
if ".jpg" in self.upload_photovideo.url or ".png" in self.upload_photovideo.url:
#check if image exists before resize
img = Image.open(self.upload_photovideo.path)
if img.height > 1080 or img.width > 1920:
new_height = 720
new_width = int(new_height / img.height * img.width)
img = img.resize((new_width, new_height))
img.save(self.upload_photovideo.path)
HTML
<div class="row">
<!-- Heat Map-->
<div class="col-xl-12">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div
class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Heat Map</h6>
</div>
<!-- Card Body -->
<div class="card-body">
<div>
<div class="container">
<div class="row mt-4">
<div class="col-md-10 offset-md-1">
<form method="post">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title">Filter Reports</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>From</label>
<input type="date" name="fromdate" class="form-control date" required>
</div>
<div class="form-group">
<label>Until</label>
<input type="date" name="todate" class="form-control date" required>
</div>
<label class="text-danger">Please ensure that the correct dates has been selected.</label>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<input type="submit" class="save-myreports-btn" value="Save Changes">
</div>
</form>
{{ map1|safe }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End of Heat Map-->
</div>
I'm guessing what you mean is you want to filter your objects based on the to and from dates.
In that one way is to use the range lookup like you do but the issue is you're using the field date from the user report instead of created_at which you have in your UserReport model.
def index_map(request):
if request.method == "POST":
fromdate = request.POST.get('fromdate')
todate = request.POST.get('todate')
df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__created_at__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
print(df)
# coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1]
map1 = folium.Map(location=[14.676208, 121.043861],
zoom_start=12,
)
# df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date'])
# mapquestopen
fg3=folium.FeatureGroup(name='Map with Markers', show=True)
map1.add_child(fg3)
You can also do:
df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__created_at__date__gte=fromdate, user_report__created_at__date__lte=todate).values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
Hello iam making game administration website with django and i need help with sorting 2 queryes . These are my models.
class Game(models.Model):
game_name = models.CharField(max_length=30, primary_key=True)
stages = models.IntegerField(null=False)
registration_start = models.DateTimeField(null=False, blank=False)
registration_end = models.DateTimeField(null=False, blank=False)
game_start = models.DateTimeField(null=False, blank=False)
game_end = models.DateTimeField(null=False, blank=False)
max_players = models.IntegerField(null=False)
class GameControl(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
game_name = models.ForeignKey(Game,
on_delete=models.CASCADE)
start_time = models.DateTimeField(null=True, blank=True)
end_time = models.DateTimeField(null=True, blank=True)
progress = models.IntegerField(null=True, default=0)
game_time = models.DurationField(null=True, blank=True)
models
and i need to separate from them registered game_names and unregistered game_names
#login_required(login_url='/signin')
def home(request):
current_user = request.user
registered = GameControl.objects.filter(user=current_user)
unregistered = Game.objects.all()
return render(request, "games/home.html", {'unregistered': unregistered ,'registered': registered })
view
I was trying to make this in template but it didnt work
{% for un in unregistered %}
{% if un.game_name in registered.game_name %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">close</i></span></button>
<br>
{% else %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">arrow_forward</i></span></button>
<br>
{% endif %}
{% endfor %}
template
Help Please <3.
Basically, in the view you should just create a list of registered game names:
#login_required(login_url='/signin')
def home(request):
current_user = request.user
registered = GameControl.objects.filter(user=current_user)
unregistered = Game.objects.all()
return render(request, "games/home.html", {'unregistered': unregistered ,'registered_names': [reg.game_name for reg in registered] })
And then the template:
{% for un in unregistered %}
{% if un.game_name in registered_names %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">close</i></span></button>
<br>
{% else %}
<button type="button" class="btn">{{un.game_name}}
<i class="material-icons" style="float:
right;">arrow_forward</i></span></button>
<br>
{% endif %}
{% endfor %}
I have a view complaints page where a user can view the complaints he/she have submitted. When the user clicks on one of the cards, I need a new page to open where the user can view the details of that complaint and edit it as well.
It should go from here:
to here: Where they can view details and make changes as well:
This is my models.py:
class Complaint(models.Model):
user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True)
id = models.AutoField(blank=False, primary_key=True)
reportnumber = models.CharField(max_length=500 ,null = True, blank= False)
eventdate = models.DateField(null=True, blank=False)
event_type = models.CharField(max_length=300, null=True, blank=True)
device_problem = models.CharField(max_length=300, null=True, blank=True)
manufacturer = models.CharField(max_length=300, null=True, blank=True)
product_code = models.CharField(max_length=300, null=True, blank=True)
brand_name = models.CharField(max_length = 300, null=True, blank=True)
exemption = models.CharField(max_length=300, null=True, blank=True)
patient_problem = models.CharField(max_length=500, null=True, blank=True)
event_text = models.TextField(null=True, blank= True)
document = models.FileField(upload_to='static/documents', blank=True, null=True)
def __str__(self):
return self.reportnumber
views.py:
def EditComplaints(request):
complaint = request.user.complaint
form = ComplaintForm(instance=complaint)
if request.method == 'POST':
form = ComplaintForm(request.POST, request.FILES, instance=complaint)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'newcomplaint.html', context)
template (the view history page):
<div class="col right-pro-con">
<div class="img-cir">
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %} {% if request.user.profile.profile_pic.url %}
<img src={{request.user.profile.profile_pic.url}} alt="" width="100px" height="100px" class="pro-img"> {% else %}
<img src="{% static 'profileimages/msi.jpg' %}" alt="" width="100px" height="100px" class="pro-img"> {% endif %}
<p class="my-name">{{request.user.profile.first}}
<p>
<p class="my-email-id">{{request.user.profile.email}}</p>
</form>
</div>
CONTACT US
</div>
template(edit complaint page):
<div class="col-lg middle middle-complaint-con">
<i class="fas fa-folder-open fa-4x comp-folder-icon"></i>
<h1 class="all-comp">New Complaint</h1>
<form class="" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p class="sub-typ-wr">Submit Type</p>
<button type="button" class="btn btn-secondary document-btn">Document</button>
<div class="rep-num">
<label class="written-label" for="">Report Number</label>
<div class="written-txt-field">{{form.reportnumber}}</div>
</div>
<div class="eve-dte">
<label class="written-label" for="">Event Date</label>
<div class="written-txt-field">{{form.eventdate}}</div>
</div>
<div class="eve-typ">
<label class="written-label" for="">Event Type</label>
<div class="written-txt-field">{{form.event_type}}</div>
</div>
<div class="dev-pro">
<label class="written-label" for="">Device Problem</label>
<div class="written-txt-field">{{form.device_problem}}</div>
</div>
<label class="written-label eve-txt" for="">Event Text</label>
<div class="Manufacturer">
<label class="written-label" for="">Manufacturer</label>
<div class="written-txt-field">{{form.manufacturer}}</div>
</div>
<div class="pro-code">
<label class="written-label" for="">Product Code</label>
<div class="written-txt-field">{{form.product_code}}</div>
</div>
<div class="brand-name">
<label class="written-label" for="">Brand Name</label>
<div class="written-txt-field">{{form.brand_name}}</div>
</div>
<div class="exem">
<label class="written-label" for="">Exemption</label>
<div class="written-txt-field">{{form.exemption}}</div>
</div>
<div class="pat-pro">
<label class="written-label" for="">Patient Problem</label>
<div class="written-txt-field">{{form.patient_problem}}</div>
</div>
<div class="comp-textarea">{{form.event_text}}</div>
<button type="button" class="btn btn-secondary attach-btn-1"><div class="fas fa-file-upload">{{form.document}}</div></button>
<button type="submit" name="submit" class="btn btn-secondary save-btn-1"><i class="fas fa-save"></i> Save</button>
</form>
</div>
url:
urlpatterns = [
path('admin/', admin.site.urls),
path('Home/', landing_page.views1.landing, name= 'Home'),
path('Registration/', accounts.views.RegisterPage),
path('Login/', accounts.views.LoginPage, name='Login'),
path('Login/Profile/', accounts.views.profile, name='Profile'),
path('Logout/', accounts.views.LogoutUser, name='Logout'),
path('Login/Add-Complaint/', accounts.views.NewComplaint, name = 'New'),
path('Login/Add-Complaint/Document-Style/', accounts.views.DocComplaint, name='doc'),
path('My-History/', accounts.views.History, name='MyHistory'),
path('Complaint/', accounts.views.EditComplaints, name='Complaint')
]
How do I do this? What should I add in the code for the code to open that particular complaints details and for that complaints page to edit?
okay, so you already have a view. What you need is some sort of unique identifier to help you figure out the actual object that the user wants to edit.
So, in your urls.py you will have to add a pattern similar to:
urlpatterns = [
...
path('complain/<int:pk>/edit/', views.EditComplaint.as_view(), name='edit-complain'),
...
]
Inside your views.py, handle it in a manner something similar to:
from django.views.generics import UpdateView
from django.contrib.auth.mixins import UserPassesTestMixin
from django.http import Http404
from django.utils.translation import gettext_lazy as _
from .models import Complaint
class EditComplaint(UserPassesTestMixin, UpdateView):
model = Complaint
fields = ('info', ) # define whatever field that you want to render
def form_valid(self, form):
# do your form validation here
def test_func(self):
"""ensuring the reporter themselves is updating the complain"""
complain = self.get_object()
if self.request.user == complain.user:
return True
raise Http404(_('This complain does not exist'))
def success_url(self):
# this is only required if your model doesn't have a `get_absolute_url` method
# return the actual url of the instance
All you need now is to add a link inside your template for the EditComplaint view(assuming you already have the list of donations inside your list template as donations).
Something along the lines should do the job
{% for complaint in complaints %}
Edit Complaint
{% endfor %}
I have created small stock web app.
I created a stock model with unique part_number field. In my update template I send all item information to be displayed. Then I get an error in the part_number field that it is already there.
How can I avoid this validation for that part_number only?
I mean for same part_number suppose validation will not work. But if I modified to another part_number that already exists I get an error that it's being duplicated.
Model:
class Stock(models.Model):
part_number = models.CharField(max_length=30, blank=False, unique=True)
part_name = models.CharField(max_length=70)
quantity = models.IntegerField(blank=False)
location = models.CharField(max_length=3, blank=True)
model = models.CharField(max_length=40, blank=True, null=True, default="")
min_quantity = models.IntegerField(unique=False, blank=True, default=0)
max_quantity = models.IntegerField(unique=False, blank=True, default=0)
class Meta:
ordering = ['part_number']
def clean(self):
self.part_number = self.part_number.upper()
def __str__(self):
return self.part_number
Form.py:
class StockUpdateModelForm(forms.ModelForm):
class Meta:
model = models.Stock
fields = ['part_name', 'quantity', 'location','part_number']
views.py:
def stock_update_form_view(request, part_id):
item = Stock.objects.get(id=part_id)
item_id = Stock.objects.get(id=part_id).pk
form = StockUpdateModelForm({
'part_number' : item.part_number,
'part_name' : item.part_name,
'quantity' : item.quantity,
'location' : item.location
})
if request.method == 'POST':
form = StockUpdateModelForm(request.POST)
if form.is_valid():
s = Stock.objects.get(pk=item_id)
s.part_name = form.cleaned_data['part_name']
s.part_number = form.cleaned_data['part_number']
s.quantity = form.cleaned_data['quantity']
s.location = form.cleaned_data['location']
print("form is valid")
s.save()
return redirect('/stock/')
return render(request, 'stock/stock_update.html', {'form': form, 'pn': item.part_number})
html:
<form class="bg-light shadow" method="POST">
<div style="margin-left:10%; margin-top:30px">
<h4>Part Number : {{ pn }}</h4>
</div>
<hr style="width:100%">
{% csrf_token %}
<div class="row" style="margin-left:30px; margin-top:40px ">
<div class="col-sm-4" style="margin-left:6%">
{{ form.part_name|as_crispy_field }}
</div>
<div class="col-sm-4" style="margin-left:15%">
{{ form.part_number|as_crispy_field }}
</div>
<div class="col-sm-4" style="margin-left:6%">
{{ form.quantity|as_crispy_field }}
</div>
<div class="col-sm-4" style="margin-left:15%">
{{ form.location|as_crispy_field }}
</div>
<div class="col-sm-4" style="height: 100px; margin-top:30px ; margin-left:6%">
<hr style="width:100%">
<input class="btn btn-primary" type="submit" value="Save"
style="width: 150px;">
</div>
</div>
</form>
try this
if request.method == 'POST':
form = StockUpdateModelForm(request.POST, instance=item)
if form.is_valid():
form.save()