Django, display count of unread messages in base template - django

I am working on a project in which I have implemented messaging system like facebook where users can send messages to each other. The number of unread messages of a particular thread is also displayed on the messages page.
Now what I want is to display the count of unread messages in the navigation bar (which is there in base.html) each time user logs in. How to do this whenever a user logs in?
Please suggest, and I don't want to use any other app for this purpose. Thanks

You can write a simple tag which can do this for you.
def unread_messages(user):
return user.messages_set.filter(read=False).count()
#replace the messages_set with the appropriate related_name, and also the filter field. (I am assuming it to be "read")
register.simple_tag(unread_messages)
and in the base template:
{% load <yourtemplatetagname> %}
{% if request.user.is_authenticated %}
{{ request.user|unread_messages }}
{% endif %}

Related

Change Celery task to run on-demand with clicking a button

I have a celery task that runs periodically and fetches some data for all companies that use a certain accounting service. I now need to make that task run on-demand with a click of a button, and fetch only the current company's data.
Modified celery task:
#APP.task
def import_data_for_company(company_id):
for integration in settings.INTEGRATIONS:
if integration["owner"]["company_id"] == company_id:
print("omlette du fromage")
Current button in Django template
{% for integration in settings.INTEGRATIONS %}
{% if company.company_id == integration.owner.company_id %}
<div class="button">
<a class="btn" href="#">Import Data</a>
</div>
{% endif %}
{% endfor %}
I need to trigger that task from the Django template and pass a company ID as an argument while doing it. But according to this comment, I cannot pass arguments from the Django template. Writing a custom template tag/filter seems not to help here.
What are my options for calling that function via this button?
Have to note, that I'm very green at this still.
You should create a view that takes your company id. Within this view, you will trigger import_data_for_company. Then you can redirect back to your initial view. Or you can trigger the view with AJAX as well.
Add the URL in your template accordingly: {% url 'some_name' company.company_id %}
urls.py:
path(
"your_desired_trigger_url/<id:company_id>/",
trigger_company_data,
name="some_name",
),
views.py:
def trigger_company_data(request, company_id):
import_data_for_company(company_id)
return HttpResponseRedirect(reverse("your_initial_view"))

How do I look in a list of items, find the user and see if it exists in a different table and change the template as a result?

I have a simple follow/following setup running.
When a user (request.user) see's an object she likes, she can click the follow button and follow that user.
When she returns I want that button on the object to now not be enabled cause she is already following that user.
What is happening is that in the background, the follower/followee record is being made. The object in question has the id of the followee. I just can't figure out how to add that representation to the object_list.
In REST I would add a field to the serializer and that would take care of it. I could then evaluate the truthiness of the new field.
Any ideas on how to accomplish this?
You should do it as a separate query and make the test in the template.
view:
def objects_list(request):
...
return render(request, "the_template_path.html", {
'objects': ObjectName.objects.all()[0:100],
'followed_object_ids': ObjectName.objects.filter(follower=request.user).values_list('id', flat=True)
})
template:
{% for object in objects %}
{% if object.id in followed_object_ids %}
...
{% else %}
...
{% endif %}
{% endfor %}
That will get you started. Obviously you don't want to use generic names like object.
It would then probably be better to move the followed_object_ids query in a middleware so you don't always do it (really useful if you have featured objects widgets everywhere for instance).

How to add calendar events with Django-Bootstrap-Calendar?

Django-Bootstrap-Calendar (https://github.com/sandlbn/django-bootstrap-calendar) is a Django implementation of this calendar application: http://bootstrap-calendar.azurewebsites.net/
However, I can't figure out how to add events to the calendar via Django. The "non-Django" bootstrap calendar is rather simple, you just add events to the JSON file that gets loaded.
Has anyone here added events to Django-Bootstrap-Calendar before? I emailed the author of the project, however, he never responded to me.
The closest post I found to my question is here: Getting a bootstrap-calendar component to work with Django However, the author figured out how to add entries to the non-Django calendar only.
Edit: I figured out how to add events via the Admin panel.
In models.py, you simply add:
###Admin
class CalendarEventAdmin(admin.ModelAdmin):
list_display = ["title", "url", "css_class", "start", "end"]
list_filler = ["title"]
admin.site.register(CalendarEvent,CalendarEventAdmin)
Then, in the admin panel you can add events (ultimately, I want non-admin users and anonymous visitors to be able to register events on the Calendar.)
However, this reveals a larger problem: the calendar doesn't display.
Edit 2: I have the calendar loading now by adding
{% load bootstrap_calendar %}
{% bootstrap_calendar_css %}
{% bootstrap_calendar_js language="template" %}
{% bootstrap_calendar_init language="template" %}
<!-- {% bootstrap_controls 'optional-css-classes' %} -->
{% bootstrap_calendar 'optional-css-classes' %}
to my index.html file. However, the calendar doesn't display the event(s) created with the Admin Panel.
Simply put
{% bootstrap_calendar_init language="template" %}
after
{% bootstrap_calendar 'optional-css-classes' %}

How to pass parameters to HttpResponseRequest elsewhere than in the url in Django

I'm trying to code a form in Django that redirect to itself, the display changing according to what you entered in the form. To do so, I retrieve the POST data in the backend and want to display a message this way: {% if message %} {{ message }} {% endif %}
The problem is how to pass the message argument.
I know I could use
#urls.py
url(r'^form/(?P<message>)$', 'app.form', name='form')
#views.py
...my_message...
return HttpResponseRedirect(reverse('app:form', args=(my_message,))
but it would display the message in the url, which isn't suitable for my purpose.
Would you know how I could do it and stay hidden in my backend, something like
#views.py
return HttpResponseRedirect(reverse('app:form'), {'message': my_message})
Use sessions to store the message - or even, the built-in messages framework.

Django authentication logic

Where is the appropriate place to distinguish between logged in and not logged in users?
ie. Should there be separate templates for logged in and not logged in users? or one template with if/else statements?
Generally, only small bits of the page will be different for logged in users (though this depends completely on the type of site or system you're building). So the most common situation is to do it as a conditional in the template, e.g.:
{% if user.is_authenticated %}
Show this
{% else %}
Show that
{% endif %}
If you wanted to distinguish in the view logic, e.g. sending different data to the template, it would be something like:
if request.user.is_authenticated:
foo="bar"
else:
foo="baz"