I want to add download button in existing view.
For example, I have a list board of fruits,
and when I click on them one by one, I move to the detail page,
such as the apple page, the strawberry page, and the grape page.
I want to create a download button for each detail page, and when I press the download button,
I want the user to download the apple.zip, drawberry.zip, and shape.zip files in database.
But I don't know how to do this in a view that's already been created.
My current view is as follows:
class FruitsDetailView(LoginRequiredMixin, DetailView):
template_name = 'fruits/detail.html'
login_url = 'login'
model = Fruits
def get_context_data(self, **kwargs):
pk = self.object.pk
context = super().get_context_data(**kwargs)
...
...
context['list'] = json.dumps(trace)
return context
I'm only exporting the context in this way, can I add a response related to the download here?
In the case of all the articles I looked for, I was creating a separate View exclusively for download.
But that's not the way I want it to be.
I'm a beginner at django, so I don't know where to start.
I'd appreciate if you give me a hint.
Related
Using Django and I would like to change the order of the display of the objects on click without refreshing the page.
my model
class IndexView(generic.ListView):
template_name = 'movies/index.html'
page_template = 'movies/all_movies.html'
context_object_name = 'all_movies'
model = Movie
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context.update({
'all_genres': Genre.objects.all(),
'our_pick': Movie.objects.get(pk=259)
})
return context
def get_queryset(self):
return Movie.objects.all()
And this is my index.html
<menu class="menu">
<ul>
<li>Newest</li>
<li>Most Popular</li>
</ul>
</menu>
on clink on Newest, the query will become:
Movie.objects.all().order_by('release_date')
and on click on Most popular, the query will become:
Movie.objects.all().order_by('popularity')
How can I achieve that without refreshing the page? any help would be appreciated!
Your question seems to illustrate a misunderstanding of how front-end and back-end languages work: a click event occurs on the front-end, after the data has been sent from the server. The order_by function is run and completed before the request is completed.
To load new data from the server without reloading, you will have to send a new request in the background using AJAX.
This is probably not a good idea, though, since you are sending the same query set ordered in a different way. I recommend using JS or jQuery to order the list on a click event based on a data attribute that you can set in the list itself. For more information about how to do this, see jquery sort list based on data attribute value.
So currently I have something like this:
Model:
class ConfirmEmail(models.Model):
report = models.ForeignKey(Report)
owner = models.CharField(max_length = 100)
emails = models.ManyToManyField(Sdm)
Admin:
#admin.register(ConfirmEmail)
class ConfirmEmailAdmin(admin.ModelAdmin):
change_form_template = 'admin/phone/index.html'
readonly_fields = ('owner',)
filter_horizontal = ('emails',)
list_display = ('owner','report')
I create these objects in code - meaning I set the report object. But what I would like in the Django admin is if I could allow a user to edit that report object but only the one set. They would be allowed to change it (so hopefully the drop down menu would no longer be there) so the nice pencil icon would still be there, but things like that "+" icon would be gone.
And this is not to say the user can't edit all reports, it's just that in the ConfirmEmail Admin they can only view that specific report attached to it.
I've been smacking away at this and can't seem to get it work.
I would also be inclined to just have the current Report Form embedded into the ConfirmEmail form - but don't know how I would go about doing that.
You should first introduce a model admin for your Report model, then override the has_add_permission function of your ReportAdmin.
#admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
# whatever you want here
def has_add_permission(self, request):
return False
You can also remove/disable the + button using javascript in the page, but be aware that the user can cause damage if he knows the add url, or disables javascript.
I am creating this functionality with a Django application I have. I want to log all pages the user visits and display it to him.
I am using a middleware to achieve it.
class LoggingMiddleware:
"""
Class used to register and fetch pages where the user has been visiting.
"""
def process_template_response(self, request, response):
if request.user.is_authenticated():
UserHistory.objects.create(user=request.user, page_name=request.path, url=request.path)
if response.context_data:
response.context_data['user_history'] = UserHistory.objects.filter(user=request.user)
return response
I want to name these UserHistory entries in the database, instead of just set the url as the name (as it i s now).
I have though of adding a variable to all views I have, in a way that the request object has something like request.page_name.
Can someone think of a better way to do it?
Related to this post, I want to populate multiple HTML pages from a single Django view. The difference between this and the link I just mentioned is, I don't want it to be programmatically based. I have links on my template like "Reports" and other company-specific categories. If the user clicks on the Reports link, I want to take them to a new page that will show them the reports. This data is all interrelated, so I initially assumed I would/should be using the same view for all of it. As I started to write this post though, I started wondering if I should in fact use separate views for all of the pages. There shouldn't be more than 3-4 pages total, depending on how I want to split up the categories.
So TL;DR: Should I use separate views for each HTML page in my template, or should/could I use a single view to populate all of the various pages on the site, even if most of the data comes from the same sources?
A possible solution using class based Views is to create a base view class that will collect the common context data and then extend it as necessary for the specific data and template. Actually the base class does not have to be an extension of View, a ContextMixinextension is sufficient
The base class should look like this:
class BaseContextMixin(ContextMixin):
def get_context_data(self, **kwargs):
context_data = super(BaseContextMixin, self).get_context_data(**kwargs)
common_data_1 = ...
context_data["common_key_1"] = common_data_1
common_data_2 = ...
context_data["common_key_2"] = common_data_2
...
return context_data
the views then can be implemented as follows:
class MyFirstView(TemplateView, BaseContextMixin):
template_name = "mir/my_first_template.html"
def get_context_data(self, **kwargs):
context_data = super(MyFirstView, self).get_context_data(**kwargs)
context_data["my_special_key"] = my_special_data
return context_data
class MySecondView(TemplateView, BaseContextMixin):
template_name = "mir/my_second_template.html"
def get_context_data(self, **kwargs):
context_data = super(MySecondView, self).get_context_data(**kwargs)
context_data["my_special_key_2"] = my_special_data_2
return context_data
This way you avoid redundant code and at the same time you can keep the structure simple
I would suggest using separate views, unless you want to have a similar formatting structure throughout, then maybe you would just use one view. Even then, though, you can use separate views with a similar HTML structure. It really depends on how you want your documents structured.
I am new to django. I made a form. I want that if the form is filled successfully then django should redirect to a success page showing the name entered in the form but no parameters should be present in the url itself.
I searched on the internet and the solution I got was to redirect to url with pk as a get parameter which fetches the data and shows in the view. But I don't want to pass any thing in the url itself. and some websites say that http can't redirect with post data.
Here's my views.py
class UserRegistrationView(CreateView):
model = UserForm
template_name = 'userregistration.html'
form_class = UserForm
success_url = 'success'
def get_success_url(self):
return reverse('success',kwargs = {'name' : self.object.firstName})
and here's the template to which I want to redirect:
<h2>Congratualations for registering {{name}} </h2>
Basically what I want is that if the person fill form mentioning his/her firstName as "xyz" then the redirected success page should say that "Congratulations for registering xyz"
You can use django sessions, which I believe installed by default in 1.8
Look here
# Set a session value:
request.session["fav_color"] = "blue"
# Get a session value -- this could be called in a different view,
# or many requests later (or both):
fav_color = request.session["fav_color"]
# Clear an item from the session:
del request.session["fav_color"]
You can pass your pk via session and extract your object in another view without affecting your url.
Make sure you clean up after yourself.
Let me know if more help needed.
One of the possible ways of passing data between views is via sessions. So, in your UserRegistrationView you need to override the form_valid method as shown below.
class UserRegsitrationView(CreateView):
def form_valid(self,form):
self.request.session['name'] = self.object.firstName
return super(UserRegistrationView,self).form_valid(form)
class SuccessView(TemplateView):
template_name = "success_template.html"
def get_context_data(self,**kwargs):
context = super(SuccessView,self).get_context_data(**kwargs)
context['name'] = self.request.session.get('name')
del self.request.session['name']
return context
One more thing that you can modify in your code is that you need not declare success_url if you are overriding get_success_url