Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display images from database
I am trying to display a list of images on my development page but the only images I am getting are this white-blank image. Here are my Django codes settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR,"static")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn') views.py def imgdownload(request): allimages = ImagefieldModel.objects.all() return render(request, 'main/show.html',{'images': allimages}) urls.py urlpatterns = [ .... .... path("show/", views.imgdownload, name="imgdownload"), .... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media") class Meta: db_table = "imageupload" show.html {% extends "main/header.html" %} {% load static %} {% block content %} <head> <title>Django Display Images</title> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Image</th> </tr> </thead> <tbody> {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td> </tr> {% endfor %} </tbody> </table> </div> </body> {% endblock %} I am not sure what is wrong since I have declared the MEDIA_URL correctly. Some help is much appreciated. -
how to deploy a ML model with django?
if we want to use our ML model with django to use in a website , how we can do that? or is there any better option to do that ? -
Django model viewset built-in delete method does not work
I have model viewset that I did not override it: class RolesAndPermissionsViewSet(ModelViewSet): queryset = RoleModel.objects.all() serializer_class = RoleSerializer the urls: router = routers.DefaultRouter() router.register(r'role', RolesAndPermissionsViewSet, basename='roles_and_permissions') urlpatterns = [] + router.urls serializer: class RoleSerializer(serializers.ModelSerializer): permissions = RequestPermissionSerializer(many=True) class Meta: model = Role fields = ( "id", "name", "permissions", ) def create(self, validated_data): permissions = validated_data.pop('permissions', []) print(permissions) role = super(RoleSerializer, self).create(validated_data) for permission in permissions: role.permissions.add(Permission.objects.get(id=permission['id'])) return role and in the postman: response but it doesn't delete the row from my django admin. Thank you for your help -
cannot call the second view from my template in django
I am creating a web app. In this one button is for getting the user data and another button is for adding a new user. I have successfully added the button which pressed shows the user but the second button is not working. this is my html {% extends "edit_parameter.html" %} {%block title %} <title>User Management</title> {% endblock %} {%block css %} table.table_font{ font-size:10%; } {% endblock %} {% block content %} <h1> <center>User Management Menu</center> </h1> <form method="POST" action="{% url 'get_user_data' %}" > {% csrf_token %} <table BORDER=0 style="float:left; margin-top:1px; margin-left:30px;"> <tr> <td> &nbsp;<label for="user_id">User ID:</label></td> <td>&nbsp;&nbsp;<input id="user_id" name="user_id" type="text" value="{{ user_id }}"><br></td> </tr> <tr> <td> &nbsp;<label for="user_name">User Name:</label></td> <td>&nbsp;&nbsp;<input id="user_name" name="user_name" type="text" value="{{ user_name }}"><br></td> </tr> </table> <button type="submit" class="btn btn-dark" >Get user data</button> <a href="success" class="btn btn-dark" role="button" aria-pressed="true">Menu</a> <button class="btn btn-danger" onclick="location.href={% url 'add_new_user' %}">add_new_user</button> </form> this is my views.py def get_user_data(req): #somecodehere return render('user.html') def add_new_user(req): #somecodehere return render('user.html') -
Why is request.GET always null in cloudfront
I am making website by django $.ajax({ type: "GET", dataType: "json", data: { "input": search__container__input.value, }, url: "{% url 'ko:search-item' %}", success: function (response) { if (response.msg == "success") { window.location.href = `/${response.target_category}/${response.target_item}` } else { Swal.fire("sorry.", "error") console.log(response) } }, error: function () { Swal.fire("sorry", "error") } }) This is my ajax code. def search_item(request): tmp = request.GET search_target = request.GET.get('input') and this is views.py search_target is always null value. this is not null value when i am not using AWS cloudfront. i choose all default option of cloudfront. what should i do -
Django testcase Python exited unexpectedly
Process: Python [909] Path: /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.7.8 (3.7.8) Code Type: X86-64 (Native) Parent Process: Python [899] Responsible: Python [909] User ID: 502 Date/Time: 2020-12-17 14:47:11.551 +0800 OS Version: Mac OS X 10.14.6 (18G103) Report Version: 12 Anonymous UUID: 2B41E719-4681-D496-6AC8-7309D3E78AFF Time Awake Since Boot: 360 seconds System Integrity Protection: disabled Crashed Thread: 0 Dispatch queue: com.apple.root.user-interactive-qos Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000110 Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [909] -
I want to call a function from my views.py on my submit button
I want to call my email function from views.py on the submit button in the index.html file. P.S. I am a beginner at this!! Thanks. My submit line from index.html: <div class="row"> <div class="col-12 mt-5"> <input type="submit" value="Send message" value="Click" class="submit-btn" name="Submit"> </div> </div> Now the views.py email function which I want to call: def email(request): fname = request.GET.get('FirstName', None) lname = request.GET.get('LastName', None) email = request.GET.get('YourEmail', None) phone_no = request.GET.get('PhoneNumber', None) message = request.GET.get('Message', None) name = fname + " " + lname body = message + "\nContact No. " + phone_no # Send Email send_mail( 'Subject - Thanks for contacting', 'Hello ' + name + ',\n' + message + "\n" + phone_no, EMAIL_HOST_USER, [ email, ] ) return redirect('index') -
Django showing percentage of task completed/total task
I'm trying to make a simple django app which is like a todo app, I want to add the percentage of task completed. Here's my model.py from django.db import models from django.urls import reverse class Task(models.Model): title = models.CharField(max_length=200) create_time = models.DateTimeField(auto_now_add=True) complete_time = models.DateTimeField(blank=True, null=True) status = models.BooleanField(default=False) def __str__(self): return self.title and here's the template file <form method="POST" action="/"> {% csrf_token %} {{form}} <input class="btn submit" type="submit" name="save"> </form> {% for task in tasks %} {% if task.status == True %} <strike>{{task}}, {{task.complete_time}}</strike> {% else %} {% endif %} {% endfor %} and this is views.py file def list(request): queryset = Task.objects.order_by('complete_time','complete_time') if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks':queryset, 'form':form, } return render(request, 'tasklist.html', context) -
How to start django-project using postgresql?
There was a need to work with geodata in my project, namely to bind a geodata field to my models. To do this, need to work with postgresQL. I followed the instructions from the documentation, set everything up, but the following error appeared (this happens when I either try to start the server, or perform migrations): django.db.utils.OperationalError File "C:\Users\Пользователь\django\PycharmProjects\usadba\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Пользователь\django\PycharmProjects\usadba\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) So: # ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1', '192.168.1.220', '127.0.0.1:5432'] ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { # 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '5432' } } The construct in the file located along the path C:\Windows\System32\drivers\etc\hosts looks like this 127.0.0.1 localhost. OS windows 10. All required libraries are installed checked through the console. -
user profile image duplicating according to number of users in django
Blockquote Heading class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics',null=True,blank=True) -
Twitter API 2 stream working locally but not on Heroku - Django
I am trying to deploy a live Twitter streaming on my Django web app on Heroku but I am facing an error. It works locally but returns an error page on live. https://twitter--sentiment.herokuapp.com/ I've added the twitter BEARER_TOKEN using heroku config set: Here is my Heroku deployment page. I've also added the directory in my settings.py file BEARER_TOKEN = os.environ['BEARER_TOKEN'] This is my first time deploying an web app! Any help would be appreciated. -
Passing values from our models to ModelForm in Django
I have a payment page were i want the amount for a particular commodity a user picks, to be displayed at default(amount) when the page loads. with that been said, i've def get_total_everything(), were the amount is been calculated. this is the calculated amount i will like to send to the Modelform initial #Form class PaymentForm(forms.ModelForm): def __init__(self,amount, *args, **kwargs): super(PaymentForm, self).__init__(*args, **kwargs) self.amount = amount self.fields["amount"].initial = amount.get_total_everything_payment() class Meta: model = Payment fields = ['firstname', 'lastname', 'email', 'amount'] class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(OrderItem) def __str__(self): return self.user.username def get_total_everything(self): total = 0 for order_item in self.item.all(): total += order_item.get_final_price() return total class Payment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) firstname = models.CharField(max_length=250) lastname = models.CharField(max_length=250) email = models.EmailField() # amount = models.FloatField() amount = models.ManyToManyField(Order) def __str__(self): return self.user.username -
How to pass Rating implemented in HTML to Views in Django
I'm implementing a Movie rating website for my College mini-project using Django and I'm just a beginner so I need some help on this topic. So for movie rating, I created stars using HTML and CSS. But to store them in Model, I don't know how to pass the rating to View which user has chosen from the webpage. Here is my HTML template where I implemented Rating: <div class="rating1"> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="1one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="2one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="3one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="4one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="5one" style="font-size:40px;cursor:pointer;" ></span> <br><br> <button style="margin-top:10px;margin-left:5px;" onclick="showRating()" class="btn btn-lg btn-success">Submit</button> </div> I'm invoking rating given by user in JS function as follows: <script type="text/javascript"> var rating=""; function starmark(item){ var count=item.id[0]; rating=count; var subid=item.id.substring(1); for(var i=0;i<5;i++){ if(i<count){ document.getElementById((i+1)+subid).style.color="orange"; } else{ document.getElementById((i+1)+subid).style.color="black"; } } } function showRating(){ alert(rating); } </script> I tried to implement form but I don't know what should I pass to View on form submission. So, for now my View is: def detail(request, tconst): movie = get_object_or_404(Movie, tconst=tconst) #for rating return render(request, 'web/detail.html', {'movie':movie}) At for rating … -
Django admin script not installed to PATH
I'm on a new computer, and have to install Django again, so I typed the pip install Django command in my VSCode terminal to install it. However, after it downloads, I get this message: WARNING: The script django-admin.exe is installed in 'C:\Users\Xiaow\AppData\Roaming\Python\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Because of this, I can't start any new projects. How would I install this script to PATH? Is there a command I have to do or something? There also seems to be a .vscode folder in 'C:\Users\Xiaow' but I don't know if this is what is making Django not install the admin script to PATH. Everything else works, like I can go to my existing projects (copied over from my old computer) and runserver, and can access all the databases. However, it's just this admin script that is causing problems. I also tried uninstalling and reinstalling Django to no avail. Full terminal message: PS C:\Code> pip install Django Defaulting to user installation because normal site-packages is not writeable Collecting Django Using cached Django-3.1.4-py3-none-any.whl (7.8 MB) Requirement already satisfied: pytz in c:\users\xiaow\appdata\roaming\python\python39\site-packages (from Django) (2020.4) Requirement already satisfied: … -
filter model objects by filed and save it to new model in viewset
I am trying filter and get all objects from one model and save it new model with same fields. how to do this right way? models: class PunchRawData(models.Model): PUNCH_TYPES = [("in", "Punch IN"), ("out", "Punch Out")] employee = models.ForeignKey(Employee, related_name="punch_employee", on_delete=models.CASCADE) shift = models.ForeignKey(WorkShift, on_delete=models.CASCADE) work_location = models.ForeignKey(HRMLocation, blank=True, on_delete=models.CASCADE, null=True, related_name="punch_work_location") punch_type = models.CharField(max_length=255, null=True, blank=True, choices=PUNCH_TYPES) user = models.ForeignKey("useraccounts.User", on_delete=models.CASCADE) actual_clock_datetime = models.DateTimeField(null=True, blank=True) emp_photo = models.ImageField(upload_to="selfies/%Y/%m/%d/%I/%M/%S/") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): strl = "{emp_id} [{shift_id}]".format(emp_id=self.employee.emp_id, shift_id=self.shift.shift_id) return strl class Meta: verbose_name = "Punch Raw Data" verbose_name_plural = "Punch Raw Data" class PunchRawDataProcess(models.Model): PUNCH_TYPES = [("in", "Punch IN"), ("out", "Punch Out")] employee = models.ForeignKey(Employee, related_name="punch_employee_process", on_delete=models.CASCADE) shift = models.ForeignKey(WorkShift, on_delete=models.CASCADE) work_location = models.ForeignKey(HRMLocation, blank=True, on_delete=models.CASCADE, null=True, related_name="punch_work_location_process") punch_type = models.CharField(max_length=255, null=True, blank=True, choices=PUNCH_TYPES) user = models.ForeignKey("useraccounts.User", on_delete=models.CASCADE) actual_clock_datetime = models.DateTimeField(null=True, blank=True) emp_photo = models.ImageField(upload_to="selfies/%Y/%m/%d/%I/%M/%S/") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): strl = "{emp_id} [{shift_id}]".format(emp_id=self.employee.emp_id, shift_id=self.shift.shift_id) return strl class Meta: verbose_name = "Punch Raw Data Process" verbose_name_plural = "Punch Raw Data Process" serializers.py: class PunchRawDataProcessSerializer(serializers.ModelSerializer): class Meta: model = PunchRawDataProcess fields = ['employee', 'shift', 'work_location', 'punch_type', 'actual_clock_datetime', 'emp_photo', 'created_at', 'updated_at'] viewset: here i'm trying to query and filter PunchRawData and trying to save in … -
Can't use get_queryset in combination with context data in Django
I have a class that fetching data from DB based on form value filled by user on previous page. I'm able to access the first page, but when I click on paginator <- next page I'm getting this error: TypeError at ... object of type 'HttpResponse' has no len() context = super().get_context_data(**kwargs) # HERE this is my code class DbTotsugoLook(LoginRequiredMixin, ListView): template_name = 'totsugo_app/db_totsugo_list.html' context_object_name = 'totsugo_data' paginate_by = 5 def get_queryset(self, *args, **kwargs): file_type = self.request.GET.get('fileType', None) if file_type == "hikari": queryset = Hikari.objects.all() elif file_type == "hikan": queryset = Hikanshou.objects.all() elif file_type == "hikarihikan": queryset = HikariHikan.objects.all() elif file_type == "kokyaku": queryset = Kokyaku.objects.all() else: messages.error(self.request, 'DB error') return render(self.request, self.template_name) self.queryset = queryset return self.queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) list_exam = self.queryset #Kaoiro.objects.all().order_by("-id") paginator = Paginator(list_exam, self.paginate_by) page = self.request.GET.get('page') try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context['totsugo_data'] = data context['title'] = "MyPage" return context -
Django Admin stuck meanwhile DB disk size explode, on object change-view admin panel
I have the following model: class ActionModel(models.Model): identifier = models.BigIntegerField( _("identifier"), null=True, blank=True) # target ig id username = models.CharField(_("ClientUsername"), max_length=150, null=True, blank=True) # username of the client account_name = models.CharField(_("AccountName"), max_length=150, null=True, blank=True) # account name of the client date = models.DateField(_("Date"), auto_now=False, auto_now_add=False) # action date target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action keyword = models.CharField(_("Keyword"), max_length=150, null=True, blank=True) # the source where this target found is_followed_back = models.BooleanField(_("Followed Back"), null=True, blank=True) # is target followed back user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, editable=False ) # django user that performed the action class Meta: verbose_name = _("Action") verbose_name_plural = _("Actions") unique_together = [ ['account_name','date','target'], ] def __str__(self): return self.target.username And the following Admin.py: # Custome Admin model for ActionModel Model class ActionModelAdmin(admin.ModelAdmin): # Override queryset method to add count's def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.filter(user=request.user) return qs change_list_template = 'admin/model_history_index.html' list_display = [ 'target', 'account_name', 'date', 'keyword', 'is_followed_back', ] search_fields = ( 'account_name', 'keyword', ) def has_add_permission(self, request, obj=None): return False And have really no Idea why when clicking on: action admin The database free-space is going from 100GB to 0GB !! adding many .temp files on the postgres db folder. … -
Django creates default db tables in all db
I have three databases in my Django project. When I make migration, models from default db gets created in other two databases. But models from other two dbs (which are not default) are not getting in created in any database. Is it possible to tell Django not to create default db tables in other databases? Here is my code router.py class CheckerRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'customers': return 'customerdb' elif model._meta.app_label == 'userchecking': return 'usersdb' return 'default' def db_for_write(self, model, **hints): if model._meta.app_label == 'customers': return 'customerdb' elif model._meta.app_label == 'userchecking': return 'usersdb' return 'default' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'customers' or obj2._meta.app_label == 'customers': return True elif 'customers' not in [obj1._meta.app_label, obj2._meta.app_label]: return True elif obj1._meta.app_label == 'userchecking' or obj2._meta.app_label == 'userchecking': return True elif 'userchecking' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return False def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'customers': return db == 'customerdb' elif app_label == 'userchecking': return db == 'usersdb' return None Settings.py DATABASES = { 'usersdb': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'usersdb', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', }, 'customerdb': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'customerdb', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', }, 'default': … -
sending array data with multipart/form-data post request in Axios vue.js
I'm sending a post request from vue.js project using Axios and it contains a file upload, which requires me to use FormData, I found a nice answer that helped me with FormData: const getFormData = object => Object.keys(object).reduce((formData, key) => { formData.append(key, object[key]); return formData; }, new FormData()); and for the headers: headers: { 'Content-Type': 'multipart/form-data'}. The POST call looks like this: axios.post("http://127.0.0.1:8000/api/document/", getFormData(this.documentData), { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log("Successfully uploaded: ", response.data) }) .catch(err => { console.log("error occured: ", err) }) This is the data I'm sending: documentData: { name: '', file: '', version: '', company: '', author: '', category: [] } When sending the data with single category id, it works fine, but when I send multiple category ids the following error shows: "category": [ "Incorrect type. Expected pk value, received str." ] How can I solve this problem? -
Hey why am i not able to make a raq query in django with non primary key fields it is giving no such table found
I made the models as below this is defined in home/models.py class likes(models.Model): like_id=models.AutoField(primary_key=True) post_id=models.ForeignKey(post,on_delete=models.CASCADE) liker_user=models.ForeignKey(User,on_delete=models.CASCADE) date_liked=models.DateField(default=datetime.date.today) In search I made search/views.py as below and getting error def search_query(request): print(request.POST['search_query']) x=likes.objects.raw("Select Like_id,Post_id from home_likes") # Operational Error: No column found Post_id print(x) print(len(x)) return render(request,'search/search_query_page.html') -
Is it possible to convert an output image url from django backend back to an image file for upload/reupload?
I have an application preview and a console down below Edit Existing Post Instance The first 2 console logs are images of an existing django post instance that are about to be modified in a form of a URL The third console log is an image file when I added a third image with a file input. e.target.files[0] The behavior that I put in the django rest api for updating existing files in a nested relation is to flush out all images and reupload images in whatever it is in the current edit images preview. The question is that is it possible to convert the first two console logs in a form of a third console log for image reupload that will go through axios? -
Django auth password reset not working using on localhost
I am trying to add a password reset functionality to my website. I can only open localhost:8000/password-reset. When I try to enter valid email address to reset the password I get 500 Internal Server Error. I am using Django-3.0. I am using sendgrid's email account for sending emails. Any idea what I am doing wrong? I tried following many tutorials online but no luck. urls.py: . . . urlpatterns = [ . . . path('password-reset/',auth.PasswordResetView.as_view(template_name='user/password_reset_form.html'), name='password_reset'), path('password-reset/done/', auth.PasswordResetDoneView.as_view(template_name='user/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth.PasswordResetConfirmView.as_view(template_name ='user/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done/', auth.PasswordResetCompleteView.as_view('template_name ='user/password_reset_complete.html'), name='password_reset_complete'), ] password_reset_form.html: {% extends "user/index.html" %} {% load crispy_forms_tags %} {% block start %} <div class="container"> <div class="center"> <h4 class="card-title">Password Recovery</h4> <p>Enter your registered email address and we will send you a link to reset your password.</p> <form method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-primary btn-block">Reset</button> </form> <br> <a href="{% url "login" %}" style="text-decoration: none; color: blue; padding:3%; cursor:pointer;">Have an account? Go to login</a> </div> </div> </div> {% endblock start %} password_reset_done.html: {% extends "user/index.html" %} {% load crispy_forms_tags %} {% block start %} <div class="container"> <div class="center"> <p>An email has been sent with instructions to reset your password.</p> <p>Dont forget to check … -
Django online users with rest framework
I had used django-online-users to get online users and it worked fine. But the problem is that i am not able to get online users in django rest framework i.e. users making api calls from react to backend server. I am only getting direct logged in users log in admin panel. Please suggest a way to use it with django rest framework. Thanks. -
Django model- How to use filter through related models
I was trying to build an application in Django. see my requirements. The company will have multiple branches, and staff also work for one more branches in different roles. For example, they may work in branch-A as a sales manager and branch -b as a Branch Manager, I was trying to implement that by Django Group and Permission, ( I use custom permissions instead of Group permission). Please see my model classes #Branches class Branch(models.Model): branch_code=models.CharField(max_length=100,unique=True) address=models.CharField(max_length=200) delete_status=models.IntegerField(choices=BRANCH_CHOICES,default=LIVE) published_date = models.DateTimeField(blank=True, null=True) # Roles on Branch class BranchRole(models.Model): owner_branch = models.ForeignKey(Branch,on_delete=models.CASCADE,related_name='available_groups') available_group = models.ForeignKey(Group,on_delete=models.CASCADE) class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class StaffUser(models.Model): staff_id=models.CharField(max_length=100,null=True,) name=models.CharField(max_length=100,null=True) user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='staffs') class RoleInBranch(models.Model): branch_role=models.ForeignKey(BranchRole,on_delete=models.CASCADE,related_name='assigned_role') permissions=models.ManyToManyField(Permission,related_name='allowed_staffs_in_branch') role_owner=models.ForeignKey(StaffUser,on_delete=models.CASCADE,related_name='roles',null=True) Here I am getting permission id and staff object, but I need to find all branches which are having that particular permission (for that requested staff object). I tried this Branch.objects.filter(available_groups__assigned_role__permissions=permission_obj,available_groups__assigned_role__role_owner=staff_obj) please help me to find the exact solution -
how to send datetime dataframe to django template and plot it in js using plotly
I have a data-frame and I want to send it in my Django template. dummy code in views.py: def graphs(request): df_new = pd.read_excel("/home/cms/cms/static/Sensorik.xlsx") times = df_new.loc[:, df_new.columns[0]].to_json(orient='records') # columns[0] contains datetime values data_color = df_georgian.loc[:, df_georgian.columns[2]] color = data_color.to_json(orient='records') context = { 'times': times, 'data_color': color, ... } return render(request, 'graphs/graphs.html', context) In my template, I get these data like the following: <script> var times = {{ times|safe }}; console.log('index: ', typeof(index)); var color = {{ data_color|safe }}; </script> the color variable is totally ok but the times variable when get to JSON format turns from 2018-05-29 08:09:00 format to something like it: element: 1528108200000 I want to be able to plot the color based on times to get a line graph with plotly. i.e. I want to show times as x-ticks of my plot. any suggeston on 1- how to send datetime dataframe to django template? or 2- how to convert element: 1528108200000 into a datetime in js to plot it as x-ticks?