Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I customize drf-yasg endpoints's example response?
on my Django project, I'm using DRF and drf-yasg. At some endpoint, the example response body shows the incorrect example. like the following example: But some of them don't show the correct example response body. This endpoint actually returns access_token and refresh_token, doesn't return the email and password. It's wrong information for the front-end devs. Is there any way to change this? -
Django registration & authentication via def
Pls help me with my problem. I need register user with some additional fields (phone, adress). Form without username field. Auth throut email. Prefer using def. I add model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField('phone ', null=True, blank=True) country = models.CharField('country ', max_length=100, null=True, blank=True) city = models.CharField('city ', max_length=100, null=True, blank=True) adress = models.CharField('adress', max_length=300, null=True, blank=True) zip_code = models.IntegerField('zip_code', null=True, blank=True) birth_day = models.DateField('birth_day', null=True, blank=True) avatar = models.ImageField('avatar', upload_to='avatar', null=True, blank=True) agreement = models.BooleanField('agreement', default=True) comment = models.TextField('comment', max_length=3000, null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() def admin_display(self): return self.user.last_name + ' ' + self.user.first_name And add two forms: class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ('comment', 'register_date', 'avatar', 'password', ) widgets = { 'phone': forms.NumberInput(attrs={'placeholder': '9XXXXXXXXX', 'class': 'form-control', 'id': 'phone'}), 'country': forms.TextInput(attrs={'placeholder': 'Россия', 'class': 'form-control', 'id': 'country'}), 'city': forms.TextInput(attrs={'placeholder': 'Москва', 'class': 'form-control', 'id': 'city'}), 'adress': forms.TextInput(attrs={'placeholder': 'Ленина 25', 'class': 'form-control', 'id': 'adress'}), 'zip_code': forms.TextInput(attrs={'placeholder': '101000', 'class': 'form-control', 'id': 'zip_code'}), 'agreement': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexSwitchCheckChecked'}), 'birth_day': DateInput(attrs={'class': 'form-control', 'id': 'birth_day'}), } class UserForm(forms.ModelForm): class Meta: model = User fields = '__all__' widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'Иван', 'class': 'form-control', 'id': … -
Django model validation in clean or in separate validators?
I am pretty new to Django and I was wondering what is the best method to validate your models in Django? Are there any advantages to using clean vs adding validators to your models? By validators I mean when you do declare the field, populating the validator=[] list. I find the models to be easier to read with the validators in another package, and declared in the field list. Also, I try to validate the data before in services, before initializing the models. What do you think / prefer? Thanks a lot. -
Can't render django template to pdf: UnsupportedMediaPathException
I have a Django template rendered by a DetailView, I want to turn that template to PDF using a different view and this library: django-easy-pdf My view: class ServizioPDFView(PDFTemplateView): template_name = 'hub/anteprima.html' base_url = 'file://' + settings.MEDIA_ROOT download_filename = 'anteprima.pdf' def get_context_data(self, **kwargs): ctx = super(ServizioPDFView, self).get_context_data( pagesize='A4', title='Anteprima Offerta', **kwargs ) r = self.request.user.referente ctx['referente'] = r ctx['hub'] = r.hub ctx['servizio'] = Servizio.objects.get(pk=self.kwargs.get('pk')) return ctx My Urls path('servizi_offerti-pdf/<int:pk>', ServizioPDFView.as_view(), name='servizio-detail-pdf'), I get the error: UnsupportedMediaPathException at /servizi_offerti-pdf/7 media urls must start with media_root/ or /static/ I followed the usage tutorial of the library and tinkered with static and media root in my settings.py but without success. Any help is greatly appreciated. -
module 'django.http.request' has no attribute 'session'
I created a class to generate a token when the user logs in. I would like to create a session when the user logs in. Here is the error I am getting: "module 'django.http.request' has no attribute 'session'" Thank you for helping me. Voici l'extrait de mon code. class TokenObtainLifetimeSerializer(TokenObtainPairSerializer): permission_classes = (permissions.AllowAny,) authentication_class = [CsrfExemptSessionAuthentication] def validate(self, attrs): loginInfo = [] # loginInfo[0] -> identifiant ||| loginInfo[1] -> password data = super().validate(attrs) for values in attrs.values(): loginInfo.append(values) if data : user = auth.authenticate(request, identifiant=loginInfo[0], password=loginInfo[1]) auth.login(request, user) refresh = self.get_token(self.user) data['lifetime'] = int(refresh.access_token.lifetime.total_seconds()) return data class CustomTokenObtainPairView(TokenViewBase): serializer_class = TokenObtainLifetimeSerializer -
Duration matching query does not exist
Traceback (most recent call last): File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/ahmed/SavannahX/app/views.py", line 1352, in yearly_subscription_plans duration = Duration.objects.get(name="yearly") File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/``` django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /yearly/subscriptions/ Exception Value: Duration matching query does not exist. -
Dynamic data not getting extended
I making a shopping website and I am using extend tag of html to extend a table into another page. Below is the table in shoppingpage.html enter image description here When I click on any of the categories(blue in color in the image above), only 'Our Products' comes and without the remaining table enter image description here Below are the codes that I have tried shoppingpage.html <body> <h1>Hello, welcome to shopping page!</h1> <ul> <a class="lynessa-menu-item-title" title="Our Products" href="/allproducts">Our Products</a> <div class="submenu megamenu megamenu-shop"> <div class="row"> {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="{% url 'polls:category' result.id %}" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in result.subcategories_set.all %} <ul class="listitem-list"> <li> <a href="{% url 'polls:subcategory' ans.id %}" target="_self">{{ans.sub_categories_name}}</a> </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} </div> </div> </ul> {% block content %}{% endblock %} </body> category.html {% extends "polls/shoppingpage.html" %} <h1>Hello,to categorybase world!</h1> {% block content %} <ul class="row products columns-3" id="appendproducts"> {% for product in products %} <li class="product-item wow fadeInUp product-item rows-space-30 col-bg-4 col-xl-4 col-lg-6 col-md-6 col-sm-6 col-ts-6 style-01 post-24 product type-product status-publish has-post-thumbnail product_cat-chair product_cat-table product_cat-new-arrivals product_tag-light product_tag-hat product_tag-sock first instock featured shipping-taxable purchasable product-type-variable has-default-attributes" data-wow-duration="1s" … -
Django filter data from multidabases
This is my first time using multidabases in django, and I encounter a problem when filtering data from many to many fields. Table1: class table1(models.Model): field1 = = models.ManyToManyField(blank=True, related_name='field',related_query_name='details', to=table2, verbose_name='field1') Table2: class table2(models.Model): multiple_fields = models.BooleanField(default=False) status = = models.ForeignKey(status, on_delete=models.PROTECT) data_type = models.ForeignKey(Type, on_delete=models.PROTECT) Table3: class table3(models.Model): field_rep_id = models.IntegerField() field_id = models.IntegerField() Id field_rep_id field_id 1 3 200 1 3 210 Then this is how I filter, field_details = table1.objects.using('default').get(pk=3) fields = field_details.field1 In table3 I dont have direct access on this so I call like above, the code is working when I use only One database but in Multidatabase I dont know what is the process so I got this error. django.db.utils.ProgrammingError: relation "app1_table3" does not exist LINE 1: ...updated_at" FROM "app2_table2" INNER JOIN "app1_table3... Expected Output: [200,210] -
The number of rows after narrowing-down
This is my serializer. class MixSerializer(serializers.ModelSerializer): pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p") new_order = #I want to get the number order class Meta: model = Mix fields = ('id','pub_date','detail','user','u_key') And I narrowing-down the rows like this below. def get_queryset(self): queryset = Mix.objects.all() u_key = self.request.query_params.get('u_key') if u_key is not None: queryset = queryset.filter(u_key=u_key) return queryset For example, it returns the 30 items from 100 items. so id should be (1,4,5,6,9,11,13...) like this, However I want to get the number new_order (1,2,3,4,5,6,....) I guess I should do some trick in Serializer? or any other way ? Any help appreciated. -
setAttribute also also setting the value for the following element
I'm pretty sure this one is silly but I can't seem to figure it out myself. This is a Django website containing a little bit of Javascript. In my HTML, I have a button that should send a few values to a Javascript function. The javascript function should then find and update some divs in the HTML. The strange thing is that the value assigned to the setAttribute statement is automatically also used for the following innerHTML statement (overruling whatever was configured there). HTML Button: <button class="btn btn-outline-dark" onclick="monthStats( {{simple_total_monthly_sent_volume}}, {{average_monthly_delivery_rate}}, {{average_monthly_unique_open_rate}}, {{total_monthly_unique_open_volume}}, {{average_monthly_unique_click_rate}}, {{average_monthly_rejection_rate}}, )">Month</button> Javascript: function monthStats (sentvolume, deliveryrate, uniqueopenrate, uniqueopenvolume, uniqueclickrate, rejectionrate ) { document.getElementById("sent").innerHTML = (sentvolume).toLocaleString("en-US"); document.getElementById("delivered").innerHTML = deliveryrate+"%"; document.getElementById("uniqueopened").innerHTML = uniqueopenrate+"%"; document.getElementById("uniqueopened").setAttribute("title", uniqueopenvolume.toString()); document.getElementById("uniqueclicked").innerHTML = uniqueclickrate+"%"; document.getElementById("rejected").innerHTML = rejectionrate+"%"; } HTML divs that should get updated: <div class="container"> <div class="row"> <div class="col"> <div id="sent" class="keymetric">{{simple_total_monthly_sent_volume|intcomma}}</div><div class="text-muted keymetricexplanation">sent volume</div> </div> <div class="col"> <div id="delivered" class="keymetric">{{average_monthly_delivery_rate}}%</div><div class="text-muted keymetricexplanation">delivery rate</div> </div> <div class="col"> <div id="uniqueopened" class="keymetric" data-bs-toggle="tooltip" data-bs-placement="top" title="{{total_monthly_unique_open_volume|intcomma}}">{{average_monthly_unique_open_rate}}%</div><div class="text-muted keymetricexplanation">unique open rate</div> </div> <div class="col"> <div id="uniqueclicked" class="keymetric">{{average_monthly_unique_click_rate}}%</div><div class="text-muted keymetricexplanation">unique click rate</div> </div> <div class="col"> <div id="rejected" class="keymetric">{{average_monthly_rejection_rate}}%</div><div class="text-muted keymetricexplanation">rejection rate</div> </div> </div> </div> Clicking on the Month button in the HTML results in the title and … -
safe tag in django template
hi i have a blog and i'm using latest ckeditor . i configed and tested my ckeditor but it does not show correctly! why {{post.body|safe}} not working ??? -
How to create messages if condition is True in django?
I am working on authentication webapp and I want to display message if user input doesn't match some conditions. It should look something like this. For example: if password has length less than 8 characters then display message 'Password should be longer than 8 characters!' My view: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST, 'length_error': False, 'password_match_error': False, 'validate_email_error': False, } global password global password2 global email global username email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') if len(password) < 8: ############custom message context['length_error'] = True if password != password2: ############custom message context['password_match_error'] = True if not validate_email(email): ############custom message context['validate_email_error'] = True if not username: ############custom message context['has_error'] = True if models.CustomUser.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'This email is already registered!') context['has_error'] = True return render(request, 'authentication/signup.html', context, status=409) if context['has_error']: return render(request, 'authentication/signup.html', context) body = render_to_string('authentication/email/email_body.html', { 'username': username, 'token': token, }) send_mail( "Email Confirmation", body, 'tadejtilinger@gmail.com', [email] ) return redirect('email-confirmation') return render(request, 'authentication/signup.html') My signup.html {% include "_base.html" %} {% load static %} {% block title %}Sign Up{% endblock title %} {% block content %} <link rel="stylesheet" href="{% static 'css/authentication/signup.css' %}"> <div class="container"> <form class="signup_form" method="post" action="{% url 'signup' … -
external network for django Webpage
I have a project in Django and it is running on my local machine, I got to make the setting by putting: Allowedhosts = ["*"] and python manage.py runserver 0.0.0.0:8000 This is enough so that I can access the page through another machine on the same network, but I would like to know a way to make access available through an external network, the question is, how do I do it ?? -
How to fetch with multiple query parameters Genereic API view
so I am building an API and i want to fetch based on multiple parameters. Here is the code base. The Url path: path('<str:order_id>/consumers/<int:user_id>/', SingleConsumerTradeAPIView.as_view(), name="single-consumer-trade" ), path('<str:order_id>/producers/<int:user_id>/', SingleProducerTradeAPIView.as_view(), name="single-producer-trade" ), Models.py: from django.db import models from authApi.models import User class Order(models.Model): user = models.ForeignKey(User,related_name='user',null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) class Trade(models.Model): consumer = models.ForeignKey(User,related_name='consumer',on_delete=models.CASCADE) producer = models.ForeignKey(User,related_name='producer',on_delete=models.CASCADE) order = models.ForeignKey(Order, related_name='trades',on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, max_length=255, decimal_places=2) location = models.CharField(max_length=255) energyQuantity = models.DecimalField(max_digits=10, max_length=255, decimal_places=2) startTime = models.DateField(auto_now_add=True) stopTime = models.DateField(auto_now_add=True) Serializers.py: class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ('id', 'order_id', 'startTime', 'stopTime', 'price', 'consumer_id', 'producer_id', 'location', 'energyQuantity', ) class OrderSerializer(serializers.ModelSerializer): trades = TradeSerializer(read_only=True, many= True) class Meta: model = Order fields = ('id', 'trades', 'date', ) What i tried: Views class SingleConsumerTradeAPIView(ListCreateAPIView): serializer_class=TradeSerializer queryset = Trade.objects.all() permission_classes = (permissions.IsAuthenticated,) lookup_fields = ('order_id', 'producer_id') def get_queryset(self): return self.queryset.filter(order_id=self.request.user,producer_id= self.request.user) I want to be able to fetch from the list of trades(via the trade model and serializers) using the order_id and the producer_id. -
Runtime Foreign Key vs Integerfield
I have a problem. I already have two solution for my problem, but i was wondering which of those is the faster solution. I guess that the second solution is not only more convienient- to use but also faster, but i want to be sure, so thats the reason why im asking. My problem is i want to group multiple rows together. The group won't hold any meta data. So im only interested in runtime. On the one hand i can use a Integer field and filter it later on when i need to get all entries that belong to the group. I guess runtime of O(n). The second solution and probably the more practicle way would be to create a foreign key to another model only using the pk there. Then i can use the reverse relation to find all the entries that belong to the group. -
Alert Message Not Rendering In Django
I am trying to create message before submitting the page, but i do not know why the message not rendering , can anyone help me to correct it. form.py class NameForm(forms.ModelForm): translated_names = TranslationField() class Meta: fields = "__all__" model = models.Name admin.py class NameAdmin(MasterDataBaseAdmin): form = forms.NameForm inlines = [AddressInline, RegistrationTypeInline] queryset = models.Name.objects.prefetch_related( "names", "name__id", "registrationstype") views.py class NameViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Name.objects.supported().prefetch_related("names", "registrationstype") serializer_class = serializers.NameSerializer def nametype(request): form = Form(request.POST) if form.is_valid(): return render(request, 'templates\ view2.html', form) view2.html {% extends "admin/base_site.html" %} {% load l10n %} <form action="" method="post">{% csrf_token %} <div> {% for obj in queryset %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" /> {% endfor %} <input type="hidden" name="post" value="yes" /> <input type="hidden" name="action" value="my_action" /> <input type="submit" value="Submit" /> </div> </form> -
Django & Migrate Error: I can't migrate my project
I was trying to run a Django project which I got from someone else. But I can't do the migration. I came from a mobile app development background. So I'm quite new to this backend thing including Django. Please have a look and help with this issue. Thank you Traceback (most recent call last): File "/Users/punreachrany/Desktop/MyProject/manage.py", line 22, in <module> main() File "/Users/punreachrany/Desktop/MyProject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' -
How to define models in django that provides custom values based on pre-selection for a field?
Given the following model that stores the user's wish list for reading books: class ReadingList(models.Model): user_id = models.ForeignKey(UserInfo, on_delete=models.DO_NOTHING, null=False, blank=False, default=None, db_column='user_id') book= models.CharField(max_length=255, blank=False) creation_time = models.DateTimeField(blank=True) class Meta: unique_together = (('user_id', book),) I want to create a model that helps in tracking the time spent in the reading the book on different days which looks something like this: class ReadingTracker(models.Model): user_id = models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='user', blank=False, db_column='user_id') book= models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='book-to-read', blank=False, db_column='book') time = models.DateTimeField(blank=True) time_spent = models.floatfield() On the client-side (corresponding to ReadingTracker) for both the fields user_id and book I see that ReadingList object (1), ReadingList object (2), ... are listed. But, this is not working as expected. What I want to achieve are the following: For user_id field I want to see the something like dummy_uid1, dummy_uid2, ... to be listed. Consider dummy_uid1 wants to read book1 and book2 whereas dummy_uid2 wants to read book1 and book3. When dummy_uid1 is selected as user_id, I want only book1 and book2 to be listed for selection. How do I define the model in django rest framework to achieve this? Any suggestions related to the above would be much appreciated and thank you in advance. -
Did you install mysqlclient? Django
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
Unable to serve django static files via nginx and docker
I am having issue with configuring a nginx server using docker and django. Here is my directory structure -nginx --default.conf --Dockerfile -portfolio_app (django webpapp) --main_app ---settings.py ---wsgi.py --sub_app ---views.py ---static ---media -docker-compose.yml -Dockerfile (django related) -entrypoint.sh (to start django server) Regarding django it working, but i am unable to serve the static files. I think i am not giving the path correctly. Here is Dockerfile related to django FROM python:3.8.13-slim-buster WORKDIR /app RUN pip install --upgrade pip COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY ./portfolio_app ./ COPY ./entrypoint.sh ./ ENTRYPOINT ["sh","/app/entrypoint.sh"] nginx files default.conf upstream django{ server portfolio_app:8000; } server { listen 80; location /{ proxy_pass http://django; } location /static/ { alias sub_app/static/; } } Dockerfile FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf Here is docker-compose.yml file version: '3.3' services: portfolio_app: build: . container_name: portfolio_app volumes: - static_volume:/sub_app/static - media_volume:/sub_app/media ports: - "8000:8000" env_file: - .env nginx: build: ./nginx volumes: - static_volume:/sub_app/static - media_volume:/sub_app/media ports: - "80:80" depends_on: - portfolio_app volumes: media_volume: static_volume: I am not sure about the path of volumes in yml file and settings of default.conf. Here are the logs Successfully built 8459b7bb3baf Successfully tagged docker_nginx:latest Recreating b0f1b634454f_portfolio_app ... done Recreating docker_nginx_1 ... done Attaching to portfolio_app, … -
How to group by in a query for the Django admin serach?
I have a model called Task. The user shall search a specific search in the django admin area. So I implement the method: def get_search_results(self, request, queryset, search_term): in class TaskAdmin(admin.ModelAdmin): I define a queryset in a complicated way. But that works. I now have a wounderful queryset resulting in a nearly perfect SQL statement. There is just one thing missing. I would love to add a GROUP BY at the end. But how? I tried several things: The starting point: [...] queryset = self.model.objects.filter(joinedQ) Django aggregation: .values.aggregate() results normally in a group by, but I can't use .values for this query because django admin does not expect a dict as result. See: Group by day in django admin? using the hidden group_by attribute of the query: queryset.query.group_by = ["product"] queryset = QuerySet(query=queryset.query, model=Task) Does not work. The resulting query has all columns in group by, not only the product column like I specified. So it does not group anything. Query to string and than manually adding the GROUP BY string_query = str(queryset.query) string_query += 'GROUP BY "main_task"."product", "main_task"."version"' queryset = Task.objects.raw(string_query) This results in the correct query what will find the correct results, but I get an exeption: AttributeError: … -
how to insert data to database without forms.py in django
This method works fine for me can some one say how to add file or images like this def insert_students(request); name = request.POST['name'] class = request.POST['class'] student = studentsmodels(name=name, class=class) student.save() return redirect('/') return render(request, "insertpage.html") -
django get latest release QuerySet
class Release(models.Model): version = models.PositiveIntegerField(default=1) class Project(models.Model): project = models.ForeignKey('projects.Project', related_name='releases', on_delete=models.SET_NULL, blank=1, null=1) def getObjects(): releases = [] for project in Project.objects.all(): if project.releases.all(): releases.append(project.releases.all().order_by('-version')[0]) return releases is it possible to get a queryset of latest releases of each project if it has release? sorry I literally have no idea how to write the queryset. -
Django : make a migration run last consistently
I have a migration 0042_db_views.py creating database views that currently depends on the last migration. I want this migration 42 to always be the last one without rewriting its dependencies every time a new migration file is generated, even if we add a new migration say 0043_my_migration.py. I have red the Django docs and a bunch of SO questions, but did not found any solution for it, there is a run_before option but not a run_after... Is there a proper and reliable way to do it ? Something that would make dependencies=* in 0042_db_views.py for example, or an option that I did not found ? My Django version is 4.0.5 # 0042_db_views.py class Migration(migrations.Migration): dependencies = [ ("networks", "0041_migration_41"), ] operations = [ CreateView( name="My_Name", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], options={ "abstract": False, }, ) # 8 other views are created, not detailing them here ] -
Prevent concurrent logins django rest framework jwt authentication
I am using djangorestframework-simplejwt==4.4.0 in my application for User Authentication. But by default it provides multiple logins for a single user i.e. I can generate n number of tokens. What I want is to prevent multiple logins from the same account. How do I do that? Models.py class Company(models.Model): region_coices = (('East', 'East'), ('West', 'West'), ('North', 'North'), ('South', 'South')) category = (('Automotive', 'Automotive'), ('F.M.C.G.', 'F.M.C.G.'), ('Pharmaceuticals', 'Pharmaceuticals'), ('Ecommerce', 'Ecommerce'), ('Others', 'Others')) type = models.ManyToManyField(CompanyTypes) name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=50, default=0) class User(AbstractUser): is_admin = models.BooleanField(default=False) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) @property def full_name(self): return self.first_name + " " + self.last_name class EmployeeTypes(models.Model): emp_choices = (('Pool Operator', 'Pool Operator'), ('Consignor', 'Consignor'), ('Consignee', 'Consignee')) emp_type = models.CharField(max_length=500, default='Pool Operator', choices=emp_choices) class Employee(models.Model): role_choices = (('CRUD', 'CRUD'), ('View', 'View')) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="company") name = models.CharField(max_length=500, default=0) Urls.py path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),