Hey I got this Code to remove my keys:
class AKeysRemove(DeleteView, ProgramContextMixin):
model = AKeys
template_name = 'administration/keys/remove.html'
def dispatch(self, request, *args, **kwargs):
return super(AKeysRemove, self).dispatch(request, *args, **kwargs)
def get_success_url(self):
return reverse('akeys_index', args=[self.get_program_id()])
def delete(self, request, *args, **kwargs):
# Get the query parameters from the request
is_active = request.GET.get('is_active')
category = request.GET.get('category')
# Build a Q object to filter AccessKeys by is_active and category
q_filter = Q()
if is_active is not None:
q_filter &= Q(is_active=is_active)
if category is not None:
q_filter &= Q(category=category)
# Check if there are any filters
has_filters = is_active is not None or category is not None
# Delete the AKeys that match the filter, or just the one AKey
if has_filters:
queryset = self.get_queryset().filter(q_filter)
deleted_count, _ = queryset.delete()
if deleted_count == 1:
messages.success(request, f"One AKey deleted.")
else:
messages.success(request, f"{deleted_count} AKeys deleted.")
else:
obj = self.get_object()
obj.delete()
messages.success(request, f"AKey {obj} deleted.")
return redirect(self.get_success_url())
My url looks like this:
re_path(r'^p/(?P<p_id>[0-9]+)/keys/(?P<pk>[0-9]+)/delete/?$', AKeysRemove.as_view(), name='akeys_delete'),
Deleting one Single Key works fine, but I build myself a filter to delete Keys from a certain category or if they're active or not (is_active)
<div class="row" style="margin-top: 10px">
<div class="col-md-12">
<form method="POST" action="{% url 'akeys_delete' p.id %}" id="delete-akeys-form">
<div class="form-group">
<label for="category-filter">Category:</label>
<select name="category" id="category-filter" class="form-control">
<option value="">All</option>
{% for category in acategories %}
<option value="{{ category.name }}">{{ category.name }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="active-filter">Status:</label>
<select name="is_active" id="active-filter" class="form-control">
<option value="">All</option>
<option value="true">Active</option>
<option value="false">Inactive</option>
</select>
</div>
<button type="submit" class="btn btn-default">Delete</button>
</form>
</div>
</div>
The problem now is that when I open my site I get the obvious error:
Reverse for 'akeys_delete' with arguments '(3,)' not found. 1 pattern(s) tried: ['admin/p/(?P<p_id>[0-9]+)/keys/(?P<pk>[0-9]+)/delete/?$']
Which I understand, since its missing the key.pk, I just can't really figure out how I could re-write my code to accept both single objects to delete and multiple?
I'm thankful for any help :)
I assume you want to support multiple functionality with same view. In that case, why not write two urls pointing to the same view, like this:
re_path(r'^p/(?P<p_id>[0-9]+)/keys/(?P<pk>[0-9]+)/delete/?$', AKeysRemove.as_view(), name='akeys_delete'),
re_path(r'^p/(?P<p_id>[0-9]+)/keys/delete/?$', AKeysRemove.as_view(), name='akeys_multi_delete'),
And update the url in template:
<form method="POST" action="{% url 'akeys_multi_delete' p.id %}" id="delete-akeys-form">
Related
I am new in Django. I want to add product against the category which I select, but I don't know how can I do that. I select the category and add product but nothing happened. I don't know how can I do this. Thank you in advance
Model.py
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
price = models.IntegerField()
view.py
class SelectCategory(TemplateView):
template_name = 'purchase/selectCategory.html'
def get(self, request, *args, **kwargs):
categories = CategoryModel.objects.all()
args = {'categories': categories}
return render(request, self.template_name, args)
def post(self, request):
try:
data = self.request.POST.get
categoryId = ProductModel.category['category.id'].id
product = ProductModel(
category_id=data(categoryId),
name=data('name'),
price=data('price')
)
product.save()
return redirect('menu')
except Exception as e:
return HttpResponse('failed{}'.format(e))
Template
{% extends 'auth/home.html' %}
{% block content %}
<form method="get">
{% csrf_token %}
<label> Select Category
<select name="Select Category">
<option disabled="disabled" selected> Select Category</option>
{% for category in categories %}
<option value={{ category.id }}>
{{ category.name }}
</option>
{% endfor %}
</select>
</label>
<input type="submit" value="Select">
</form>
<form method="post">
{% csrf_token %}
<label for="name">Name
<input type="text" name="name" id="name" placeholder="Enter Product name">
</label>
<label for="price">Price
<input type="number" name="price" id="price" placeholder="Enter Price of Product">
</label>
<button type="submit">Submit</button>
<button>Menu</button>
</form>
{% endblock %}
Get the category instance first using data selected category id and then push that instance to as a parameter to productmodel.
def post(self, request):
try:
data = self.request.POST.get
categoryObj= CategoryModel.objects.get(I'd=data[])
product = ProductModel(
category_id= categoryObj
name=data('name'),
price=data('price')
)
product.save()
return redirect('menu')
except Exception as e:
return HttpResponse('failed{}'.format(e))
I'm trying to save a object 'Animal' with the data from my form but im getting a error.
This is my view:
def addAnimal(request):
if request.user.id == None:
return render(request, "deny.html")
else:
if request.method == 'POST':
animal_name = request.POST['animal_name']
animal_type = request.POST['animal_type']
animal_age = request.POST['animal_age']
animal_port = request.POST['animal_port']
animal = Animal(animal_name=animal_name, animal_age=animal_type, animal_type=animal_age, animal_port=animal_port)
animal.save()
return render(request, "home.html", args)
This is the model im trying to save:
class Animal(models.Model):
animal_name = models.CharField(max_length=255)
animal_age = models.ManyToManyField(Age)
animal_type = models.ManyToManyField(Type)
animal_port = models.ManyToManyField(Port)
def __str__(self):
return self.animal_name
And this is my form:
<form method="post" class="form-signin" action="{% url 'addAnimal' %}">
{% csrf_token %}
<img class="mb-4" src="{% static 'images/logo_transparent.png' %}" alt="" width="300" height="300">
<h1 class="h3 mb-3 font-weight-normal text-white">Adicione o seu Animal de Estimação</h1>
<input type="text" id="animal_name" name="animal_name" class="form-control"
placeholder="Nome do Seu Animal de Estimação">
<select class="form-control" id="animal_type" name="ration_type">
<option value="Cão">Cão</option>
<option value="Gato">Gato</option>
</select>
<select class="form-control" id="animal_age" name="animal_age">
<option value="Junior">Junior</option>
<option value="Adulto">Adulto</option>
<option value="Senior">Senior</option>
</select>
<select class="form-control" id="animal_port" name="animal_port">
<option value="Pequeno">Pequeno</option>
<option value="Médio">Médio</option>
<option value="Grande">Grande</option>
</select>
<div>  </div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Adicionar</button>
</form>
And a print if you nedd so:
Update
Im getting a new error:
TypeError at /addAnimal/
Direct assignment to the forward side of a many-to-many set is prohibited. Use animal_age.set() instead.
How can I solve it?
This is because of your POST request.
Try request.POST.get() instead. And/or when you're taking in attributes from POST, try typing for example request.POST['animal name', None] or request.POST.get('animal name', None) Where None can be replaced with any default value. It's a null checking issue I think.
I'm a learner in Python and Django.
I am trying to pass selected checkboxes to my views and then make a get() call to fetch related objects, but keep getting the error DoesNotExist, even though the object is present in the database.
I tried changing the get() parameters but it still shows the same error, as if it just cannot fetch the database. Please help!
ERROR IS IN THE #ed LINE
Here is my views.py
def manage(request):
if request.POST.get('taskname'):
name = request.POST.get('taskname')
end = request.POST.get('enddate')
emp = User.objects.get(username = request.user.username)
print emp.username
try:
newtask = Task(taskname = name, deadline = end, status = 'incomplete', empid = emp)
newtask.save()
except:
print "not saved"
my_tasks = Task.objects.filter(empid = emp)
return render(request, 'ellipse/dashboard.html', {'employee': emp, 'tasks': my_tasks})
else:
selected = request.POST.get('dropdown')
if selected == 'Delete':
tasks = request.POST.getlist('t')
emp = User.objects.get(username = request.user.username)
for seltask in tasks:
#deltask = Task.objects.get(taskname=seltask)
deltask.delete()
my_tasks = Task.objects.filter(empid = emp)
return render(request, 'ellipse/dashboard.html', {'employee': emp, 'tasks': my_tasks})
And, my html:
<div>
<form action="/ellipse/manage/" method="post">
{% csrf_token %}
<p>Taskname <input type="text" name="taskname"></p>
<p>Deadline <input type="date" name="enddate"></p>
<select name="dropdown">
<option selected="selected" disabled>Select action :</option>
<option value="Add">Add</option>
<option value="Delete">Delete</option>
<option value="Mark as complete">Mark as complete</option>
<option value="Mark as incomplete">Mark as incomplete</option>
</select>
{% if tasks %}
{% for tasko in tasks %}
<p><tr><td><input type="checkbox" name="t" value={{ tasko.taskname }}/></td><td>{{ tasko.taskname }}</td><td>{{ tasko.deadline }}</td><td>{{ tasko.status }}</td></tr></p>
{% endfor %}
{% endif %}
<p><button type="submit" name="modify">Modify</button></p>
</form>
</div>
I am clueless on how to proceed further and it'd be great help if this issue can be resolved. Thanks in advance!
Well your get looks jacked up.
emp = User.objects.get(username = request.user.username)
should probably be something like this.
emp = User.objects.get(id=request.user.id)
You could probably do this to...
emp = User.objects.get(user=request.user)
First of all, I am generically creating my form from the database. Here are my codes:
template:
{% block wizard_form_content %}
<div id="alt-list">
<div id="alt-list-header">
<h4>Grids List</h4>
</div>
<div id="alt-list-data" class="container">
{% for grid in data.grids %}
<input type="checkbox" name="{{ grid.name }}" id="id_{{ grid.name }}" tabindex="{{ forloop.counter}}" size="30">{{ grid.name }}<br>
{% endfor %}
</div>
</div>
{% if wizard.form.errors %}
<div class="form-errors-wrapper">
<div class="error">
{% for error in wizard.form.non_field_errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
</div>
{% endif %}
<input type="hidden" name="num-grids" value="{{ data.grids|length }}" id="num-grids" />
<input type="hidden" name="user" value="{{ data.user }}" id="user" />
{% endblock wizard_form_content %}
And this is the corresponding form:
class WhichGridsForm(forms.Form):
# Override the initialize in order to dynamically add fields to the form in order to be saved,
# the fields are saved only when the user selects 'Next Step'.
def __init__(self, *args, **kwargs):
super(WhichGridsForm, self).__init__(*args, **kwargs)
if len(self.data) > 0:
self.num_grids = self.data['num-grids']
user_name = self.data['user']
user1 = User.objects.filter(username=user_name)
gridtype = Grid.GridType.USER_GRID
templateData = ShowGridsData()
templateData.grids = Grid.objects.filter(user=user1, grid_type=gridtype)
for grid in templateData.grids:
gridName = grid.name
# Every time, alternative fields are added with the name 'alternative..', and this because django
# always adds '1-' % (where 1 the number of the step with zero index) prefix in the name,
# with this the names are kept always the same.
self.fields[gridName] = forms.BooleanField(required=False)
Keeping in the mind that this is step 2, when I am trying to reach this step 2 data from step 3 with this line of code:
elif self.steps.step1 == 3:
try:
grids_data = self.get_cleaned_data_for_step('1')
print grids_data
All of the fields seems "False" even though I checked them all.
{u'Cars': False, u'grid11': False, u'deneme11': False, u'asd': False}
Do you have any idea why this would happen?
Edit:
But If I print the form fields in the 'done' method, I get the correct results:
<MultiValueDict: {u'num-grids': [u'4'], u'deneme11': [u'on'], u'Cars': [u'on'], u'composite_wizard-current_step': [u'1'], u'grid11': [u'on'], u'user': [u'muratayan'], u'asd': [u'on'], u'csrfmiddlewaretoken': [u'JYIT5gHs35ZBvk7rCITfpMIPrFleUYXF']}>
Sorry I gave you the wrong field class. Instead MultipleChoiceField it should be ModelMultipleChoiceField, since you select from models.
Something like this works in my case:
forms.py (form for first step)
class FirstStepForm(forms.Form):
def __init__(self, *args, **kwargs):
super(FirstStepForm, self).__init__(*args, **kwargs)
self.fields['countries'] = forms.ModelMultipleChoiceField(queryset=Country.objects.all())
views.py
class MyWizard(SessionWizardView):
def render(self, form=None, **kwargs):
response = super(MyWizard, self).render(form, **kwargs)
grids_data = self.get_cleaned_data_for_step('0') or {}
print grids_data
return response
Form HTML
<form action="" method="post" class="form-horizontal"><div style="display:none"><input type="hidden" name="csrfmiddlewaretoken" value="6b3d58df7bd4f6d10975462aaf3bd42d"></div>
<input type="hidden" name="paper" value="5225" id="id_paper"><fieldset><div id="div_id_priority" class="control-group">
<label class="control-label" for="id_priority">Priority</label>
<div class="controls">
<select name="priority" id="id_priority">
<option value="1" selected="selected">Primary</option>
<option value="2">Secondary</option>
</select>
<p class="help-block"><span class="help_text">Primary - 1st Choice. Secondary - 2nd Choice.</span></p>
</div>
</div> <!-- /clearfix -->
<div id="div_id_topic" class="control-group">
<label class="control-label" for="id_topic">Topics</label>
<div class="controls">
<select name="topic" id="id_topic">
<option value="6">A</option>
<option value="7" selected="selected">B</option>
<option value="9">C</option>
</select>
</div>
</div> <!-- /clearfix -->
<div id="div_id_subtopic" class="control-group error">
<label class="control-label" for="id_subtopic">SubTopics</label>
<div class="controls">
<select name="subtopic" id="id_subtopic">
<option value="29">KEEPER</option></select>
<span class="help-inline">Select a valid choice. 29 is not one of the available choices.</span>
</div>
</div> <!-- /clearfix -->
</fieldset>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
VIEW
#login_required
#event_required
def add_topic(request, paper_id):
event = request.event
paper = get_object_or_404(SubmissionImportData, pk=paper_id)
form = TopicForm(request.POST or None, event=event, paper=paper)
print request.POST # i see subtopic here
print form.errors
if request.method == 'POST' and form.is_valid():
cd = form.cleaned_data
subtopic = request.POST.get('subtopic')
if subtopic:
subtopic_obj = get_object_or_404(SubTopic, pk=subtopic)
else:
subtopic_obj = None
paper_topic = PaperTopic.objects.get_or_create(
submission_import_data=paper,
priority=cd['priority'],
topic=cd['topic'],
sub_topic=subtopic_obj)[0]
msg = 'Topic Successfully Added'
messages.success(request, msg)
url = reverse('submissions_nonadmin_view_topic',
args=[event.slug, paper.id])
return redirect(url)
FORM CLASS
class TopicForm(BootstrapForm):
topic = forms.ModelChoiceField(label='Topics',
queryset=None, required=False, empty_label=None)
subtopic = forms.ChoiceField(label='SubTopics',
widget=forms.Select(attrs={'disabled': 'disabled'}),
required=False)
paper = forms.IntegerField(widget=forms.HiddenInput())
priority = forms.ChoiceField(label='Priority',
choices=PaperTopic.PRIORITY, required=False)
class Meta:
fields = (
'priority', 'topic', 'subtopic', 'paper',
)
layout = (
Fieldset('', 'priority', 'topic', 'subtopic', 'paper',),
)
def __init__(self, *args, **kwargs):
event = kwargs.pop('event')
#paper_topic = kwargs.pop('paper_topic')
paper = kwargs.pop('paper')
super(TopicForm, self).__init__(*args, **kwargs)
self.fields['paper'].initial = paper.id
self.fields['topic'].queryset = Topic.objects.\
filter(setting=event.setting)
self.fields['priority'].help_text = 'Primary - 1st Choice. Secondary - 2nd Choice.'
#if paper_topic:
#self.fields['topic'].initial = Topic.objects.\
#get(pk=paper_topic.topic.id)
def clean(self):
'''
Limit topic associations to 2
'''
print 111, self.cleaned_data # subtopic field is missing here
cleaned_data = self.cleaned_data
topic = cleaned_data.get('topic', None)
subtopic = cleaned_data.get('subtopic', None)
paper = cleaned_data.get('paper', None)
priority = cleaned_data.get('priority', None)
paper_obj = get_object_or_404(SubmissionImportData, pk=paper)
if topic:
topic_count = PaperTopic.objects.\
filter(submission_import_data=paper_obj).count()
if topic_count >= 2:
raise forms.ValidationError("You can only select up to two sets of topic and subtopic associations.")
if PaperTopic.objects.filter(submission_import_data=paper_obj,
priority=priority).exists():
raise forms.ValidationError("You have already chosen that priority level.")
if PaperTopic.objects.filter(submission_import_data=paper_obj,
topic=topic, sub_topic=subtopic).exists():
raise forms.ValidationError("You have already chosen that set of Topic and Subtopic association.")
print 999999000000
return cleaned_data
When I'm trying to submit my form, I'm getting this error:
<span class="help-inline">Select a valid choice. 29 is not one of the available choices.</span>.
I am generating the options for the subtopic dropdown list dynamically via AJAX based on the chosen value in topic.
I am able to get see subtopic in my request.POST but when it gets to the clean method, the subtopic field disappears.
I'm not too sure what's going on..
UPDATE
Another thing, when there are no values for subtopic, the select element is set to disabled=disabled. When I try to submit my form like this, I am able to get subtopic field in my clean method. Whereas when the field is not disabled, I am not able to get it in my clean method. That's like the opposite behaviour of what I'm expecting..
ChoiceField() needs a list of choices to validate against to. Although you do
this for topic
self.fields['topic'].queryset = Topic.objects.\
filter(setting=event.setting)
subtopic is initialized as an empty list, thus no option will be valid.
You'll have to initialize the self.fields['subtopic'].choices with every possible subtopic instance and decide with Javascript which subtopics will be shown/hidden(depending on which topic is selected).