Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying Foreign Key Options in django restframework view
I'm having trouble displaying all the jobs as options in the apply url view see image below. I am getting the error which says Lists are not currently supported in HTML input The main function I am looking for is for a list of jobs that were posted to be available for selection when applying for the job. models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() job_type = models.CharField(max_length=12, choices=JOB_TYPE_CHOICES, default='Full-Time') city = models.CharField(max_length=255) def __str__(self): return self.description[:50] class Applicant(models.Model): """A applicant that can apply to a job""" job = models.ForeignKey(Job, related_name='applicants', on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=254) phone_number = PhoneNumberField() resume = models.FileField(upload_to=resume_file_path, validators=[validate_file_extension]) def __str__(self): return self.first_name I've removed some of the attributes in Job so that the code is not so long. serializers.py from rest_framework import serializers from django.utils.translation import ugettext_lazy as _ from core.models import Job, Applicant class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" applicants = serializers.StringRelatedField(many=True) class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active', 'applicants') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" return … -
How to fix manytomany field in django
How to make a one to many relationship in Django/Mysql? I have an identical situation to this post, yet, my django returns errors on the admin page: get() returned more than one order2pizza-- it returned 5! order2pizza with that pizza already exists. My mysql database have composite keys on a tertiary table to order and pizza to link multiple pizzas to an order. models.py: class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_name = models.CharField(max_length=100, blank=True, null=True) class Pizza(models.Model): Pizza= models.AutoField(primary_key=True) Pizza_name= models.CharField(max_length=50, blank=True, null=True) class order2pizza(models.Model): order = models.ManyToManyField(Orders, models.DO_NOTHING, ) pizza_id= models.IntegerField() class Meta: unique_together = (('order ', 'pizza_id'),) -
Error in hosting Django app with AWS Elastic Beanstalk
I was trying to host my Django app with AWS Elastic Beanstalk. I took help from their very own documentation here Upon doing whatever written there, I faced an error saying: "Internal Server Error" I tried finding out the solution. I found an answer in StackOverflow itself that removing the following part from my settings.py does the job. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Well, it did for the very basic trial. I tried to host my eCommerce website on AWS using the same thing I learned. It showed the same internal server error. So I removed the DATABASE part from my settings.py. Now it shows the very obvious error: ImproperlyConfigured at / settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'my-secret-key' DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # installed apps 'ckeditor', 'ckeditor_uploader', 'eshop', 'product', 'order', 'user', 'mptt', 'paywix', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ebdjango.urls' TEMPLATES = [ … -
Why doesn't href from HTML to CSS work correctly with Django?
I have the next problem: Im ceating a basic django webpage using HTML and CSS. The issue is that when I try to make the href from the HTML file to the CSS one: <link rel="stylesheet" type="text/css" href="modelado.css"> It doesn't work correctly. my HTML file called "inicio.html" and "modelado.css" are in the same folder, but once I make the href, the console says this: Not Found: /inicio/modelado.css I think that the console is trying to find a folder called "inicio", but that's impossible since inicio is the HTML file from where I am running the program. What I want to know is if there is another way to write the direction, because that directory doesn't exist. I also think that this is a django related problem, because when I only use HTML, that line of code actually works when the files are in the same folder. Thanks! -
Do i need to manipulate DRF if only im using the built-in template django system?
I have some troubles understanding Django and DRF, if for instance I want to integrate a frontend framework along with Django, do I really need to use Django itself or will I touch DRF; and in the other hand, if I use the built in template django system, do I need to use DRF? please someone help me since I don't know the answer yet since I want to integrate a frontend framework such as Angular to developer my web page but I think I don't need Django, instead I need to use DRF! -
Issue with passing a file object as an argument of Django command
I'm trying to test a Django command by passing a file object as an argument: a_file = open('Sample.xml', 'rb') call_command("process_xml", a_file, self.valdate) and parse the xml file in the command: from lxml import etree, objectify from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command class Command(BaseCommand): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( 'a_file', ) def __init__(self, **kwargs): super(BaseCommand, self).__init__(**kwargs) def handle(self, *args, **options): xml_file = options["a_file"] print(str(xml_file)) result = objectify.parse(xml_file) I got the error: File "/mnt/ccl/management/commands/process_xml.py", line 20, in handle result = objectify.parse(xml_file) File "src/lxml/objectify.pyx", line 1842, in lxml.objectify.parse File "src/lxml/etree.pyx", line 3521, in lxml.etree.parse File "src/lxml/parser.pxi", line 1859, in lxml.etree._parseDocument File "src/lxml/parser.pxi", line 1885, in lxml.etree._parseDocumentFromURL File "src/lxml/parser.pxi", line 1789, in lxml.etree._parseDocFromFile File "src/lxml/parser.pxi", line 1177, in lxml.etree._BaseParser._parseDocFromFile File "src/lxml/parser.pxi", line 615, in lxml.etree._ParserContext._handleParseResultDoc File "src/lxml/parser.pxi", line 725, in lxml.etree._handleParseResult File "src/lxml/parser.pxi", line 652, in lxml.etree._raiseParseError OSError: Error reading file '<_io.BufferedReader name='/mnt/ccl/Sample.xml'>': failed to load external entity "<_io.BufferedReader name='/mnt/ccl/Sample.xml'>" However, if I open the file within the command module, with open('/mnt/ccl/Sample.xml', 'rb') as xml_file: result = objectify.parse(xml_file) There was no issue. Would appreciate if anyone can shed some light on this. -
What's the best way to run R script and use the results given in the output(csv file) using ReactJs
I have a React code that as an input 2 groupes of textes go then to the database to search for result and gives back 2 csv files. Then i should run an R script which uses these 2 csv files, make analysis then gives back a third csv file which i am going to render its content using react Js. Does anyone knows how to do such thing? Is it possible to launch all this cycle using a button? For now the button make first part only (outputes 2 csv files) but i didn't know how to launch the R script automatically when pressing the same button. Also i want to delete the 3 csv files because it will creates other files when doing the process again. I am using ReactJs and Django for the backend. If anyone can help would be appreciated -
Django Get content from FK of FK
I'm facing troubles with my django project. I have a three layer model: model.py class PLC(models.Model): name = models.CharField(max_length=50) class Measure(models.Model): class Meta: unique_together = ('PLC', 'address', 'is_bit') PLC = models.ForeignKey(PLC, on_delete=models.CASCADE) address = models.IntegerField() is_bit = models.BooleanField() class MeasureValue(models.Model): measure = models.ForeignKey(Measure, on_delete=models.CASCADE) value = models.TextField() In my view.py, I want to be able to get measures values out of the plc class PLCViewSet(viewsets.ModelViewSet): queryset = PLC.objects.all() serializer_class = PLCSerializer def measures(request, id): plc = PLC.objects.get(id=id) measures = Measure.objects.filter(PLC=id) values = MeasureValue.objects.filter(measure__PLC=id) context = { 'PLC': plc, 'MEASURES': measures, 'VALUES': values } return render(request, 'measures.html', context) Unfortunately, i cannot make a correct filter() (data are stored in sqlite base). -
How to automatically create new Profile once a new User is created in Django?
Currently running into this issue with my Django app that I am working on. I have a model class Profile that I want to be automatically created and assigned to a new user. Was wondering how I can do this? I do have a custom user model that I have set up as well. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
How do I open a terminal in a Spyder project?
I am trying to publish my Django project to localhost but I cant' seem to open a terminal to do python manage.py runserver after that, my localhost is not working. Can someone help with that too? Thanks -
How can i use button to execute a view in Django?
Im using django to display some data of a database in a table, in that table a have a horizontal partition which separate data by date(old data and new data.) On top of the table ive created 2 button, "partition 1" and "partition 2" so when i click "partition 1" it displays me the data of the old partition. I would like to know how can when i click the button "old" to change the data in the main table(contains both new and old data) to the datas of old partition. Note: I have all views created for 3 of them. -
How to pass get object pk_ to inside of form valid function
I want to update an Article. i also get the Article(pk) data inside of Article(pk) form. when i try to submit the form data i'm getting this error FileModel.post" must be a "Article" instance because i need to pass the article(primary key) with FileModel (post=pk_) when i create new files which is related with Article, but i don't understand how can i pass the primary key from get_object function? I would be grateful for any help. VIEWS class UpdateViews(UpdateView): form_class = FileForm template_name = 'update.html' success_url = '/' def get_object(self): pk_ = self.kwargs.get('pk') FileModel.objects.filter(post=pk_).delete() return get_object_or_404(Article, pk=pk_) def form_valid(self, form): form.instance.author = self.request.user for f in self.request.FILES.getlist('file'): FileModel.objects.create(post=self.get_object.pk_, file=f) # here is the error return super().form_valid(form) -
Django Dependent Dropdown from API Response
I'm new to Django and developing an app for internal use. I've been following this scenario for getting a dependent dropdown to work, but not everything is relevant to what I'm trying to accomplish. I've got the first dropdown populated from my postgreSQL database. When a user selects the item (server), I want an API call to pull the latest information from that selected server to populate the second dropdown. So far I have been able to create the API session, but the GET request is sending the object ID rather than the object Name. I appreciate any ideas on how to get this to work. Below is what I have so far: forms.py class CreateForm(forms.ModelForm): class Meta: model = Argument fields = ('server', 'serv_cluster', 'number') labels = {'server':'Choose Server'} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'server' in self.data: try: server_id = int(self.data.get('server')) except (ValueError, TypeError): pass views.py def load_clusters(request): server = request.GET.get('server') # getting obj ID but I want the obj Name session = create_session(server) # creates API session clusters = mgr(session).serv_cluster_list() # returns cluster names as a list return render(request, 'cluster_dropdown_list_options.html', {'cluster': cluster}) cluster_dropdown_list_options.html <option value="">---------</option> {% for cluster in clusters %} <option value="{{ cluster }}">{{ cluster … -
Redirect PasswordResetConfirm to Login on success
For a password reset, I'd like to redirect the user directly to the login screen, and skip the final "complete" screen. I've setup a view to use instead of the Django one: class CustomPasswordResetConfirmView(SuccessMessageMixin, PasswordResetConfirmView): success_url = reverse_lazy("login") success_message = "Your new password has been set. You may log in now." In urls.py path( "reset/<uidb64>/<token>/", CustomPasswordResetConfirmView.as_view(), name="password_reset_confirm", ), The same approach has worked just fine for the password change, when I link to a differnet "front" screen, and display a message, but here I am always linked to the standard "admin site" password_reset_complete view, with it's link back to login. How can I skip this and implement what I hope my custom view makes it obvious I'd like to do? -
How to connect tables that don't have direct link, using foreign key of other table in Django?
current connection of the tables Hello guys, Let sey I have three tables, Table1, Table2 and Table3. Table1 has foreign key of Table2 and Table3 has foreign key of Table2, but Table1 and Table3 aren't directly connected (as it seems redundant) - how can I access table3 from table1, using connection between Table1 and Table2, and then Table2 to Table3? More specifically, I want to add one column from Table3 to Table1 view in Django Admin and I am not sure how can I do it. Usually I would just add it as Table 3 foreign key in Table1 class, but that connection seems redundant, as they can connect through Table2. So my code looks something like that now: class Table2(models.Model): ... class Table3(models.Model) column_foreign_key2 = models.ForeignKey(table2) ... class Table1(models.Model): column_foreign_key = models.ForeignKey(table2) ... I want to achieve result as I would add class table1(models.Model) column_foreign_key3 = models.ForeignKey(table3) but without adding it, but going through table2 Sorry if that seems confusing -
Need to get access key and access token variable over to function in celery
I have a function working in celery that I want to work with the Twitter API however when trying to access I have to use request to get the oauth keys from the user. This won't work in celery tasks so I need some other way of getting the variables and using them. celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from django.shortcuts import render import time import tweepy os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoTweetLiker.settings') app = Celery('AutoTweetLiker') app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='redis://:pf133827b9d431528f1158e82e1b04a8bda7b3555544882d8f0e3b963bd0f85a1@ec2-18-207-19-49.compute-1.amazonaws.com:13609', CELERY_RESULT_BACKEND='redis://:pf133827b9d431528f1158e82e1b04a8bda7b3555544882d8f0e3b963bd0f85a1@ec2-18-207-19-49.compute-1.amazonaws.com:13609') app.autodiscover_tasks() @app.task(bind=True) def liker(self): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth, wait_on_rate_limit=True) * does function with twitter api * and the views.py with the function and auth def like(request): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = request.session['access_key_tw'] access_secret = request.session['access_secret_tw'] oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) user = api.me() username = request.user.get_username() muting.delay() return render(request, "home.html") def auth(request): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) request.session['request_token'] = oauth.request_token return response def callback(request): verifier = request.GET.get('oauth_verifier') oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) token = request.session.get('request_token') request.session.delete('request_token') oauth.request_token = token try: oauth.get_access_token(verifier) except tweepy.TweepError: print('Error, failed to get access token') request.session['access_key_tw'] = oauth.access_token request.session['access_secret_tw'] = oauth.access_token_secret print(request.session['access_key_tw']) print(request.session['access_secret_tw']) api = get_api(request) response = HttpResponseRedirect(reverse('mute')) return response The … -
Form POST using Ajax doesn't populate database in Django, but gives success message
VIEW: class AddFoo(BSModalCreateView): template_name = 'qualitylabs/add_foo.html' form_class = AddFooForm success_message = 'Success: Foo was created' success_url = reverse_lazy('Home') FORM: class AddFooForm(BSModalModelForm): class Meta: model = Foo fields = '__all__' widgets = { 'part_number': PartNumberWidget, 'operation': OperationNumberWidget, } JAVASCRIPT: function sendToServer(machine, before, after) { var modified_form_data = before + "&inspection_machine=" + encodeURIComponent(machine) + after $.ajax({ type: $('#AddFooForm').attr('method'), url: $('#AddFooForm').attr('action'), data: modified_form_data, success: function (data) { console.log('did it!!!!!') } }); } I'm trying to post a form to the server, which should populate the database. I have to send it in Ajax because I have to iterate multiple times, changing variables each time (poorly set up database). The weirdest thing is that when I run the code, I get: "POST /add_foo/ HTTP/1.1" 302 0 which is the same result that you get when the server responds properly. The page does not redirect to the success_url, and when I check the data in the admin page, the items have not been added. However, in the admin page I do get the success message of "Sucess: Foo was created" Any ideas? It's quite strange. -
How to set a date from date picker and fetch it from the REST API?
on the backend. I set a filter for my data. Where I can filter the dates from the REST API url. class RainfallFilter(filters.FilterSet): start_date = DateFilter(field_name='timestamp', lookup_expr='gt') end_date = DateFilter(field_name='timestamp', lookup_expr='lt') date_range = DateRangeFilter(field_name='timestamp') class Meta: model = Rainfall fields = [] class RainfallView(generics.ListCreateAPIView): serializer_class = RainfallSerializer queryset = Rainfall.objects.all() filterset_class = RainfallFilter def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = RainfallSerializer(queryset, many=True) return Response(serializer.data) What I want to happen is from my chart.js, I want to display to my chart what I selected start and end dates. or date_range. That I have a date picker on my frontend UI that If I select, dates start_date=2020-01-20 to end_date=2020-01-25. it will only show data from 20-25. How am I gonna do it? var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in qs %}'{{i.timestamp}}',{% endfor %}], datasets: [{ label: 'Rainfall Graph', data: [{% for i in qs %}'{{i.amount}}',{% endfor %}], lineTension: 0, backgroundColor: 'transparent', borderColor: '#c9c5c5', borderWidth: 2, pointRadius: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: false } }] }, legend: { display: false } } }) }()); -
how to change the background color of the particular row in python Django
the below code is table.py class StColumn(tables.Column): def render(self, value, record): if record.status == 'warning': self.attrs ={"td": {"bgcolor": "DeepSkyBlue"}} elif record.status == 'ok': self.attrs ={"td": {"bgcolor": "SandyBrown"}} return u"%s" % (record.status.id) class resultTable(BaseTable): class Meta(BaseTable.Meta): model = resultModel attrs = {'class': 'table table-striped table-bordered table-hover row-color=green' , 'width': '70%'} status= StColumn(accessor='status.id') print(status) fields = ( "field1", "field2", "field3", "status", "field5", ) **how we can change the color of row when the status==warning and status ==ok ** -
Images not appearing in virtual environment
I'm currently working on an application on my virtual environment (Pycharm) and I've dropped three different png. images into my "img" folder which sits in a projects folder static>projects>img. Through the script path in my venv all folders are recognized telling me the path way is functioning, I can't seem to figure why the images aren't showing up. Thank you for your time and assistance. -
|as_crispy_field got passed an invalid or inexistent field in CharField
I am building a BlogApp and while trying to styling the forms i got this error. :- |as_crispy_field got passed an invalid or inexistent field edit.html {% load crispy_forms_tags %} {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ allowance_form|as_crispy_field }} </table> <button type="submit">Save Changes</button> </form> </div> {% endblock content %} views.py def edit_allowance(request,user_id): if request.method == 'POST': allowance_form = ProfilePhotoAllowForm(request.POST, request.FILES, instance=request.user.profile) if allowance_form.is_valid(): custom_form = allowance_form.save(False) custom_form.save() return redirect('profiles',user_id=user_id) else: allowance_form = ProfilePhotoAllowForm(instance=request.user.profile) context = {'allowance_form':allowance_form} return render(request, 'edit.html', context) Whenever i run the page it keep showing me this |as_crispy_field got passed an invalid or inexistent field Error. I don't know what's wrong in this Code. I checked all answered on StackOverFlow BUT they didn't help me in this. Any help would be appreciated. Thank You in Advance. -
DRF Serializer behaves differently when using as nested serializer
I have a model serializer for a date field and a time field. The model and serializer look like this: class OrderDate(TimeStampedModel): order = models.ForeignKey(Order, related_name='dates', on_delete=models.CASCADE, null=True, blank=True) date = models.DateField() from_hour = models.TimeField() to_hour = models.TimeField() class OrderDateSerializer(serializers.ModelSerializer): class Meta: model = OrderDate fields = ['id', 'date', 'from_hour', 'to_hour'] Now I use this serializer as a nested serializer in my order model and I added a validator like this: class BaseOrderSerializer(serializers.ModelSerializer): dates = OrderDateSerializer(many=True) @staticmethod def validate_dates(value): return OrderService.validate_dates(value) The value object inside the validated_dates method is an ordereddict which has datetime objects as value. Example value like this: [OrderedDict([('date', datetime.date(2020, 12, 16)), ('from_hour', datetime.time(11, 0)), ('to_hour', datetime.time(15, 0))])] Now I want to use the OrderService.validate_dates method a second time outside the serializer like this: date_serializer = OrderDateSerializer(data=request.data, many=True) date_serializer.is_valid(raise_exception=True) OrderService.validate_dates(date_serializer.data) The problem here is, that the serialized data now is an ordered dict with string values instead of datetime objects. [OrderedDict([('id', None), ('date', '2020-12-16'), ('from_hour', '11:00:00'), ('to_hour', '15:00:00')])] That results in an type error inside my method. Is there any way to change this and have the same value types in the ordered dicts? -
Where to best execute database operations using Django framework?
Thanks in advance for any help. I am new to django specifically as well as web development in general. I have been trying to teach myself and develop a website using the Django framework and while everything is working so far, I am not sure if I am really doing things in the best possible way. Typically, within my django app, I will have certain points where I want to modify the contents of my database model in some way. A typical use case is where I have button on my site that says "Add an article": models.py: from django.db import models # data model import from django.contrib.auth.models import User # Create your models here. class Post(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) post = models.CharField(max_length=1024) urls.py: from django.urls import include, path from . import views urlpatterns = [ path('', views.post, name='new_post'), path('post_exec', views.post_exec, name='post_exec'), ] views.py: from django.contrib import messages from django.shortcuts import render, redirect # import data models from django.contrib.auth.models import User from .models import Post def post(request): # make sure the user has privileges user = User.objects.get(id = request.user.id) if not user.is_superuser: return redirect('home') return render(request, 'post.html') def post_exec(request): # make sure the user has priveledges user = User.objects.get(id … -
404 on http://@ but not https://
I'm very new to everything web development. I've developed a site with Django and deployed it on digital ocean. Here's the problem: I can ping both my @ and www. domains (they both correctly point to the IP address), and I have a certbot certificate that lists both. When trying to load the website on www.example.com, it correctly redirects to https://wwww.example.com - beautiful. However, when I try to load it from example.com, I get a "404 Not Found // nginx/1.18.0 (Ubuntu)"-error. What's weird is that if I manually try and load https://example.com, then it loads correctly (that is, on https://example.com, proving that the certbot certificate is indeed catching both). It thus seems that I ought to try and redirect example.com requests to www.example.com, since everything will then go through smoothly. By the way, the ALLOWED HOSTS is ".example.com". From what I can gauge, this involves manipulating the /etc/nginx/conf.d/example.com file, and making a server block complete the redirect, but I'm lost as to how. I don't much care if example.com redirects to https://example.com, or to https://www.example.com (I'm just learning, SEO is of no consequence to me), I just need my website to load correctly. So sorry if this has already been … -
How can I logout user in Django when he closes my page tab?
I have this code: SESSION_EXPIRE_AT_BROWSER_CLOSE = True which logout user on browser close, but is there anything similar to this code for logout user on window tab close?