Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to django graphql framework add social account in google and facebook login?
how to use social account in django graphql framework Google login Facebook login I'm trying to implementation of django social account add query and mutation on graphql rest framework. I don't know use graphql framework. Any one answer me, very kind thankful mine -
How to post an image on Django Rest server using fetch API?
I have a Django Rest Framework view that accepts an image and a style sting: class PostImage(APIView): serializer_class = GetImageSerializer parser_classes = [MultiPartParser] def post(self, request, format=None): print(request.data) # debug img = request.data.get('image') ... response = FileResponse(img) return response I get the correct output using Postman. Here's the curl command that it executes: curl --location --request POST 'http://127.0.0.1:8000/style_transfer/style/' \ --form 'image=@"/C:/User/949690-kg.jpg"' \ --form 'style ="models\\\\tokyo_ghoul\\\\tokyo_ghoul_aggressive.pth"' Here's the javascript snippet generated by postman for the same task. I've added content-type because it is required by DRF. var formdata = new FormData(); formdata.append("image", fileInput.files[0], "/C:/Users/949690-kg.jpg"); formdata.append("style\n", "models\\\\tokyo_ghoul\\\\tokyo_ghoul_aggressive.pth"); var requestOptions = { method: 'POST', body: formdata, redirect: 'follow', headers: { "Content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" } }; fetch("http://127.0.0.1:8000/style_transfer/style/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); On executing the above snippet on postman, I get the following error: { "detail": "Unsupported media type \"application/javascript\" in request." } The strange part is that the curl command generated by postman work as expected. I have also asked this question a few days back here, and it has some more context. Why does this happen and how to fix this? -
Two way replication of data between two postgresql 13.1schemas
All, I have a Django multitenant application with PostgreSQL (13.1) as a backend. I’m in a situation where I need to replicate the data between “table 1” and “table 2”. Right now, I’m using logical replication (publish-subscribe) for this one-directional replication. But, we need to replicate the data in two ways (ie. From A B and BA). I have some questions for the experts while learning more about this situation. This would help me in finding a solution Context We have a user with permission in both schemas Uses logical replication (Publish subscribe) Logical replication from table 1 to Table 2 is working fine But need to replicate data in both directions (ie. From A B and BA) Simultaneous data medication won’t happen in (in schema 1 or Schema 2) Questions Will this result in an infinite loop? Is there any way to avoid this looping? -
user = get_user_model().objects.create_user(email,password)
I am getting this error while executing .I have made a test models file to test my models using TDD.I could find the error i have also tried models.User.create_user but that also didnt work. Here is my test_models.py ''' class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with email""" email = 'hassansahi6464@gmail.com' password = 'admin' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Test the email for user is normalized""" email = 'hassansahi6464@GMAIL.COM' user = get_user_model().objects.create_user(email,'admin') self.assertEqual(user.email,email.lower()) and here is my models from django.db import models from django.contrib.auth.models import UserManager , AbstractBaseUser , BaseUserManager , PermissionsMixin from django.db.models.base import Model # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): user = self.model(email=self.normalize_email(email) , **extra_fields) user.set_password(password) user.save(using = self._db) return user class User(AbstractBaseUser,PermissionsMixin,Model): email = models.EmailField(max_length=100,unique=True) name = models.CharField(max_length=150) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager USERNAME_FIELD = 'email' Settings.py AUTH_USER_MODEL = 'core.User' -
Django cannot find CSS when deployment
I have an issue with my deployment. When I run my project in my localhost it works perfect. But when I deploy iti cannot find css files. That's why looks bad and doesn't get any style. How can I fix it? settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join('static'),) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... Note: And I don't know if it is related but there is an error in console: Refused to apply style from 'https://...ing.com/static/css/signup.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. -
I am looking for some final year web project unique ideas ? please do let me know some new web project ideas?
Please let me know the best topics for building A web application. -
How to add weeks to a datetime column, depending on a django model/dictionary?
Context There is a dataframe of customer invoices and their due dates.(Identified by customer code) Week(s) need to be added depending on customer code Model is created to persist the list of customers and week(s) to be added What is done so far: Models.py class BpShift(models.Model): bp_name = models.CharField(max_length=50, default='') bp_code = models.CharField(max_length=15, primary_key=True, default='') weeks = models.IntegerField(default=0) helper.py from .models import BpShift # used in views later def week_shift(self, df): df['DueDateRange'] = df['DueDate'] + datetime.timedelta( weeks=BpShift.objects.get(pk=df['BpCode']).weeks) Error BpShift matching query does not exist. Commentary I used these methods in hope that I would be able to change the dataframe at once, instead of using df.iterrows(). I have recently been avoiding for loops like a plague and wondering if this is the "correct" mentality. Is there any recommended way of doing this? Thanks in advance for any guidance! -
Django Admin redirects to a looped URL
when I'm trying to open Django admin in my project, it redirects to a weird URL that looks some kind of loop happened. I've unregistered all models from the admin module but the problem is still the same. at this moment there's no models added to Django admin and its URL looks like this: path('admin', admin.site.urls) but when I'm trying to open the admin URL (localhost:8000/admin), it redirects me to this URL: http://localhost:8000/adminlogin/?next=/adminlogin%3Fnext%3D/adminlogin%253Fnext%253D/adminlogin%25253Fnext%25253D/adminlogin%2525253Fnext%2525253D/adminlogin%252525253Fnext%252525253D/adminlogin%25252525253Fnext%25252525253D/adminlogin%2525252525253Fnext%2525252525253D/adminlogin%252525252525253Fnext%252525252525253D/adminlogin%25252525252525253Fnext%25252525252525253D/adminlogin%2525252525252525253Fnext%2525252525252525253D/adminlogin%252525252525252525253Fnext%252525252525252525253D/adminlogin%25252525252525252525253Fnext%25252525252525252525253D/adminlogin%2525252525252525252525253Fnext%2525252525252525252525253D/adminlogin%252525252525252525252525253Fnext%252525252525252525252525253D/adminlogin%25252525252525252525252525253Fnext%25252525252525252525252525253D/adminlogin%2525252525252525252525252525253Fnext%2525252525252525252525252525253D/adminlogin%252525252525252525252525252525253Fnext%252525252525252525252525252525253D/adminlogin%25252525252525252525252525252525253Fnext%25252525252525252525252525252525253D/adminlogin%2525252525252525252525252525252525253Fnext%2525252525252525252525252525252525253D/admin I'm troubling with this issue for some days and couldn't find any solution! any ideas? -
how to add related product list in django on my ecommerce website
I have a ecommerce website an d it my project detail page I want to load related product list of that subcategories of which the current item detail is showing on product_detail.html but i don't figure out how to achieve that any idea how to achieve that right now i show all the item list in realated products section but i don't want that here is my codes my views.py class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.filter() return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: quantity = cart.get(item) if quantity: cart[item] = quantity+1 else: cart[item] = 1 else: cart = {} cart[item] = 1 request.session['cart'] = cart return redirect('products:detail', item_id=item_id) my html <div class="product"> <div class="col-11"> <h4 style="color: #025;">Related Products</h4> <div class="scrolling-wrapper"> {% for items in item %} <a href="{% url 'products:detail' item_id=items.id %}"><img class="card col-3" height="300px" width="100%" src="{{ items.first.url }}" alt=""></a> {% endfor %} </div> </div> </div> </div> my models.py class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_categories') name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Item(models.Model): … -
Heroku login fails: Error: unable to get local issuer certificate when trying to deploy django app
I want to deploy my django app to heroku. I am using company PC, windows10. Company is not IT company, it is contruction company. So IT team is not helpfull in some development cases. When I want to login from heroku cli, I got this error: D:\coding\taksi>heroku login heroku: Press any key to open up the browser to login or q to exit: Error: unable to get local issuer certificate What have I tried already: Check/Set Variable SSL_CERT_DIR=YourCetrFolder (I don't have such file, company IT team has no idea about this) I did my deployment via browser, but some tasks are not possible with web interface. for example I want to create super user after deployment, I want to migrate my database after deployment. those tasks are impossible via heroku web.(as far as i know, of course if there is a way to do those via heroku web page, please let me know. as long as it does my job, it is not important whether it is heroku cli or heroku webpage for me) thanks in advance. -
systemctl status gunicorn error when deploying django project on ubuntu 20.04
I want to deploy a django project on ubuntu 20.4 on digital ocean. I'm using gunicorn and nginx. The project structure: ./ e-marketplace/ account/ bin/ env home/ logistics/ stettings.py wsgi.py manage.py requirements.txt staticfiles/ ... The process was going well until I got to the point where I'm to connect my project to gunicorn. I set up the /etc/systemd/system/gunicorn.socket and /etc/systemd/system/gunicorn.service files as shown below: However I keep getting the follow error when I run the command sudo journalctl -u gunicorn.socket as well as sudo systemctl status gunicorn command: I have spent about 3 day trying to solve the problem without any positive outcome I went through digital ocean documentation https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 but I can't figure out what's wrong with my code. I checked the answer to similar question on the internet, including other stack overflow reviews but I still could not find the solution that works for me. -
How to use api in DRF with authentication in python
I want to make an API with token Authentication. Now i can use Postman But in other hand i don't know how can i used it in python. I tried this into python: import requests response = requests.get("http://127.0.0.1:8000/api/v1/get-all-data/ 'Authorization: Token f468db88cb3b4e92ba00f662a4f334d47bd27f38'") print(response.json()) but it gives me an error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
confused with URL parameter in jinja Django
I confused with my URL in jinja: my url.py is: path('<int:listing_id>', views.listing, name='listing') views.py: def listing(request, listing_id): return render(request, 'listings/listing.html') I get an integer in url as an id to specify list(listing_id) but I understand in my html file I must write listing.id instead of listing_id <a href="{% url 'listing' listing.id %}" class="btn btn-primary btn-block">More Info</a> My question is why I must use . instead of _ (listing.id instead of listing_id) -
Django ValueError at /updatestudent/3 Cannot assign "'1'": "Student.class_id" must be a "Class" instance
ValueError at /updatestudent/3 Cannot assign "'1'": "Student.class_id" must be a "Class" instance. This error comes when I am trying to update my student model. when I am updating username also than it doesn't throw any error but if I am not updating username than only this throwing this error Any help is appericiated. models.py user_type_data = ((1,'HOD'),(2,'Staff'),(3,'Student')) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Student(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(default=1, choices=gender_type, max_length=10) profile = models.ImageField(upload_to='student/profile-images/%y/%m/%d/', default='student/profile-images/default.jpg', blank=False, null=False) address = models.TextField() class_id = models.ForeignKey(Class, on_delete=models.CASCADE, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() def full_name(self): return self.admin.first_name+' '+self.admin.last_name def __str__(self): return self.admin.username class Session(models.Model): id = models.AutoField(primary_key=True) session_start= models.IntegerField() session_end = models.IntegerField() objects = models.Manager() def __str__(self): return f'{self.session_start} {self.session_end}' class Course(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): return self.name class Class(models.Model): id = models.AutoField(primary_key=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) branch = models.CharField(default='CSE', choices=branch_data, max_length=40) year = models.CharField(default='First Year', choices=year_data, max_length=15) session = models.ForeignKey(Session, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): return f'{self.course} {self.branch} {self.year} {self.session}' def name(self): return f'{self.course} {self.branch} {self.year} {self.session}' forms.py from django import forms from … -
Allowing a single form to update 2 tables at once
I'm having a trouble where I want to use a form to update 2 different tables. My current form have a few variables. Hostname, ipaddr, mgmt, mgmtip etc. What I want to do now is take hostname, ipaddr and add into one table (This one done) and the other 2, mgmt and mgmtip to another table while under the same id. Like for example, hostname and ipaddr is registered under id of 1 (1st row of table 1) and mgmt and mgmtip to table 2 of the same id = 1. I am currently also able to extract the id for the 1st table. But I just cant seem to update the table2 under the same id. Below is my code: def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_frm = DeviceDetailForm() if device_frm.is_valid(): device_frm.save() ##Part A1 deviceid = Device.objects.aggregate(Max('id')) ##Part A1 - Getting the ID of added device device = Device.objects.all() ##Part A1 if dd_frm.is_valid(): dd_frm.save('id' == deviceid) return render(request, 'interface/device-added.html',{'devices':device}) else: device_frm = DeviceForm() dd_frm = DeviceDetailForm() di_frm = DeviceInterfaceForm() return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_frm}) -
How to use foreignkey with different models in DJango
I'm stack with this problem, and looking for some solution before asking this question here. Lets say I have a one Model that shares same field in different Models how can I achieve this that when I get the objects of those Models I can include that Model foreign key, I did try to achieve this using Generic Relation in DJango yet it didn't solve my issue. here is the sample what I'm trying to achieve using Generic Relation: Model1(models.Model): .. objects_on_this_model .. Model2(models.Model): .. objects_on_this_model ... # Now this is where the model I could save different models with same field shared SameObjectModel(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntengerField() content_object = GenericForeignKey('content_type', 'object_id') .. objects_on_this_model .. # which is the field that has same field to use in different models So when I try to get the objects from Model(n) how can I achieve or get the SameObjectModel? I have this on my mind that I could do this: Model(n).objects.prefetch_related('fk').all() Seems it is not a good idea, since I do not know where I should put the related_name since the foreign key is the content_type which is the model and there is the object_id represent the field primary_key. -
TypeError when loading MariaDB using Django
DB is trying to be used by calling from a web hosting server. However, an error occurs, and the error is also a TypeError, so I don't know how to solve it. DB version is 10.1.13-MariaDB - MariaDB Server. Python version 3.7(64bit) I'm using only DATABASES of 'setting.py' in Django PS C:\Users\wow\source\repos\ann2> python .\manage.py migrate Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", l ine 419, in execute_from_command_line utility.execute() File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", l ine 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrat e.py", line 75, in handle self.check(databases=[database]) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\checks\database.py", line 13, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\mysql\validation.py ", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\mysql\validation.py ", line 13, in _check_sql_mode if not (self.connection.sql_mode & {'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES'}): File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\wow\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\mysql\base.py", lin e 406, in sql_mode return set(sql_mode.split(',') if sql_mode else ()) TypeError: a bytes-like object is … -
How to Count the number of distinct keys in a dictionary in django template
The numbers are serial number and the dictionary belongs to that serial number is data. I want to count the length of dictionary belong to distinct serial number in django template. The name of dictionary is redict. {15: [<videoscomment: Reply...byNavneetKaur>, <videoscomment: Reply...byNavneetKaur>], 20: [<videoscomment: 2nd comment reply...byNavneetKaur>]} I have tried the following methods comments.sno is the number and below gets data belong to that number redict|get_val:comments.sno and i put count in the last to get the length of data. redict|get_val:comments.sno.count And remember we have to do that in django template. -
Django views function called inside a render page views function
My goal is to get the form to appear on the screen. Everything works when the image_upload function is called profile. As what it was called before changing the function name (last Stack overflow question). The reason I changed the name was so I could implement other functions easier in the future and so I could understand Full Stack better. One function to render the page and the other to do a task I wanted. If anyone could help that would I would appreciate it. views.py def profile(request): return render(request, "main/profile.html", {}) def image_upload(request): if request.method == "POST": form = User_Profile_Form(request.POST, request.FILES) if form.is_valid(): form.save() obj = form.instance return render(request, "main/profile.html", {"obj":obj}) else: form = User_Profile_Form() img = User_Profile.objects.all() return render(request,"main/profile.html", {"img":img, "form":form}) urls.py urlpatterns = [ path("", views.home, name = "home"), path("profile", views.profile, name = "profile"), path("image_upload", views.image_upload, name = "image_upload"), path("profile_settings", views.profile_settings, name = "profile_settings"), ] profile.html <div class="container"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-lg btn-success">Upload</button> </form> {% if obj %} <h3>Succesfully uploaded : {{img_obj.caption}}</h3> <img src="{{ obj.image.url}}" alt="image" class="img-thumbnail" > {% endif %} <hr> -
How to convert django form to json in python 3
How to convert django form to json The form I want to convert form = WordForm(instance=word) I have tried all of the methods below. serializers.serialize('json', form) error: 'BoundField' object has no attribute '_meta' json.dumps(list(form)), json.dumps(form) error: Object of type BoundField is not JSON serializable And I found this library (https://github.com/WiserTogether/django-remote-forms) through Googling, but python3 is not compatible. How can I convert a django form to json? -
AUTH_USER_MODEL refers to model 'users.CustomUser' that has not been installed
models.py User = get_user_model() class CustomUser(AbstractUser): sign = models.ImageField(upload_to=image_saving) objects = CustomUserManager() this is my models.py I tried to add just an extra field to django User model. setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django_restful_admin', 'django_jalali', 'm', 'users', ] AUTH_USER_MODEL = 'users.CustomUser' I've added AUTH_USER_MODEL to my setting.py. here is my installed apps. managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) here is my managers.py ... I wanna add a sign culumn to my User models. -
how read specific line from csv file in django
i am trying to read csv file in django but i dont know how to achieve it, i am fresher recently joined organization and working singly, please any one help me from django.shortcuts import render from django.http import HttpResponse import csv from csv import reader def fun(request): with open(r"C:\Users\Sagar\Downloads\ULB_Sp_ThreePhaseUpdate.csv") as file: reader = csv.reader(file) ip = request.GET["id"] flag = False for rec in reader: if rec[1]=="id": return HttpResponse("MID: ",rec[2]) return render(request, "index.html") -
Django breaking after adding extend and load static tags
so I used template inheritance in django. After I used {% extends 'basic.html' %} {% load static %} the html and css doesnt update. What I mean by that if for example when I change the page title then save and refresh [both by ctrl f5 and ctrl r] it doesnt do anything. The extending works fine but when I use load static first of all it doesn't load it second when I update or add any html its like "I dont care" and doesnt update anything. The code {% extends 'basic.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Do</title> </head> <body> <p> Help </p> </body> </html> basic.html <div class="upper"> <p class="blogtitle"> Utsab's Blogs </p> <a href="/" class="homebutton"> Home </a> <a href="blogs" class="blogsbutton"> Blogs </a> <a href="contact" class="contactbutton"> Contact </a> </div> <style> .upper{ background-color: black; height: 40px; position: absolute; top: 0%; left: 0%; right: 0%; } .blogtitle { text-align: center; } .name { text-align: center; font-weight: bolder; font-size: larger; } .text { text-align: center; font-size: large; } .homebutton { font-family: 'Roboto', sans-serif; position: absolute; top: 10px; left: 29%; text-decoration: none; color: azure; } .blogsbutton { position: absolute; left: … -
Best practice of refreshing JWT tokens from mobile and web simultaneously
We are building a customer application. For that, we are using accounting software (ZOHO). Items will be fetched from the accounting software and bills will be generated directly on accounting software using API. API is using JWT for authentication. To generate JWT tokens for each user then is a 'user consent page', which should be manually approved from the web browser. So, for each customer we are not going to register as a user, we are planning to create them as just customers. What we are actually planning to do now, is create one JWT token pair (After manual approval) and use it for all customers for all API calls. My first concern, is that will be a good approach? The second concern, the Token has an expiry of 1 hour. After that, we should use the refresh token to generate the new token. How we can efficiently handle this on the web and mobile (Customers on the web and mobile simultaneously using the same tokens for API calls and the Token change should reflect on all client devices)? Doing this is a good idea? -
Is there any another way to python manage.py crontab run in django server?
i have created a scheduled job in django with django_crontab package. i have added the job. its successfully added but its only get executed whenever i run python manage.py crontab run daeea9e88c171494b1610bdebfasd123 not with runserver command. what might be the issue, this is my view. cron.py file def my_scheduled_job(): file = open('geek.txt','w') now = timezone.now() file.write("This is the write command") file.write("It allows us to write in a particular file") file.write(str(now)) file.close() print(now) return True settings.py CRONTAB_LOCK_JOBS = False CRONTAB_DJANGO_PROJECT_NAME = 'api' CRONTAB_DJANGO_SETTINGS_MODULE = 'api.settings' CRONJOBS = [ ('*/1 * * * *', 'app.cron.my_scheduled_job') ] what i want is its job get executed every minute whenever i run python manage.py runserver. Is there anything missing please help me out.