Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I cannot edit project started on another pc?
I have created a project on one pc and I want to work on it from second pc. I ziped the project from one pc and opened it from another. When I make changes for example in models and want to makemigrations it shows that no changes have been made. What I am doing wrong ? -
Getting error : 'admin' is not a registered namespace, on trying to access the password reset view
I created a password reset view following "https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html " this link. I used the urls for class based views since django uses CBVs in the version 2.1 and above. It seemed to work fine, but today I am getting the above stated error. I have commented the admin url,on uncommenting it the password_reset view works, but through the django registration and uses it's own template regardless of the templates I have created. Why am I getting this problem suddenly when it worked fine earlier? urls.py from django.conf.urls import url,include from django.contrib import admin from NewApp import views from django.conf import settings from django.conf.urls.static import serve from django.urls import path urlpatterns = [ url(r'^$', views.user_login , name='user_login'), url(r'^NewApp/', include('NewApp.urls', namespace="NewApp")), path('', include('django.contrib.auth.urls')), ] NewApp/urls.py from django.conf.urls import url,include from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views app_name = 'NewApp' urlpatterns =[path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Apart from these, I have only used templates which are just copied from the link I have mentioned. -
How to convert Django ORM query to SQL row query?
I have Django ORM query: month = InfraVltgDetail.objects.annotate( month=TruncMonth('create_dt')) .values('month').annotate( name_count=Count('id')) .values('month', 'name_count') I'm using month.query to convert sql row query. #print(by_month.query) output: SELECT django_datetime_trunc('month', "portal_infravltgdetail"."create_dt", 'UTC') AS "month", COUNT("portal_infravltgdetail"."id") AS "name_count" FROM "portal_infravltgdetail" GROUP BY django_datetime_trunc('month', "portal_infravltgdetail"."create_dt", 'UTC') When i'm using output sql row query to execute but getting error. How i'm running sql row query: import psycopg2 conn = psycopg2.connect(database="test", user = "postgres", password = "postgres", host = "localhost", port = "5432") cur = conn.cursor() cur.execute(output_query) cur.fetchall() Could you please help me to convert Django ORM to sql. Thanks in advance. -
Get record's age in second if older than 5 minutes in Django (with PostgreSQL database)
I'm retrieving all records, and I would like to display the record's age for those records that are older than 5 minutes. Here's my current code: Interfaces.objects.all() .annotate( age = (datetime.utcnow() - F('timestamp')), # 0:00:08.535704 age2 = Epoch(datetime.utcnow() - F('timestamp')), # 8.535704 # age3 = int(Epoch(datetime.utcnow() - F('timestamp'))/300), current_time=Value(str(datetime.utcnow()), output_field=null_char_field), ) .order_by('age','ip') age and age2 both work, but the problem is that I want the records that are older than 5 minutes sorted by age, and the rest by ip So I'm trying to set age to 0, if it's less than 5 minutes. Is there a way to do it? -
cant seem to figure out the error: get_queryset() takes 1 positional argument but 2 were given
I have a django rest framework project. I created a viewset and I am setting up the urls for the viewset. I am getting the following error: TypeError at /api/v2/preferences/ get_queryset() takes 1 positional argument but 2 were given I am working with the preferences urls... urlpatterns = [ path('', include(router.urls)), path('dashboards/<int:pk>', dashboard_detail, name='dashboard-detail'), path('dashboards/<str:guid>', dashboard_detail, name='dashboard-detail'), path('users/<int:pk>/stacks/', person_stack, name='user-stacks'), path('preferences/<str:namespace>/<str:path>/<int:pk>/', user_preference_stack, name='preferences-pk'), path('preferences/<str:namespace>/<str:path>/', user_preference_stack, name='preferences-path'), path('preferences/<str:namespace>/', user_preference_stack, name='preferences-namespace'), path('preferences/', user_preference_stack, name='preferences') ] I also wanted to know if it is possible to create 1 url with the namespace and path as optional and not required arguments rather than 4 urls with each variation of the url. here is the viewset: class PreferenceUserViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy' or self.action == 'list' or self.action == 'put': permission_classes = [IsAuthenticated] else: permission_classes = [IsAuthenticated] return [permission() for permission in permission_classes] def get_user(self): return self.request.user def get_queryset(self): namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: queryset = Preference.objects.all().filter(person=self.request.user.id) if namespace and path is None: queryset = Preference.objects.all().filter( person=self.request.user.id, namespace=namespace) if namespace and path: queryset = Preference.objects.all().filter( person=self.request.user.id, namespace=namespace, path=path) return queryset def create(self, … -
Django 1.8 unit tests OperationalError: no such column
I'm trying to upgrade a django1.6 project to 1.8. With this upgrade it seems like south stopped being used. Im trying to update my migrations. I followed the guide which made this seem simple. I deleted all of the old migration files and ran makemigrations to generate new ones. The migrations all run correctly if I run migrate. When I run the unit tests set up I get an error saying: self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x111eb4168> query = 'SELECT "common_basecacheconfig"."id", "common_baseconfig"."contact", "common_baseconfig"."slack_room", "com...config_ptr_id" = "common_baseconfig"."id" ) ORDER BY "app_appconfig"."uniqueentryconfig_ptr_id" ASC' params = () def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) > return Database.Cursor.execute(self, query, params) E django.db.utils.OperationalError: no such column: app_appconfig.name Django-1.8.3-py2.py3-none-any.whl/django/db/backends/sqlite3/base.py:318: OperationalError I edited some of the message to take out company specific stuff. But it's the same message. These are the relevant models I believe name_model = models.CharField(max_length=64, blank=False, db_index=True, validators=[validate_name]) stage_model = models.CharField(max_length=10, choices=STAGE_CHOICES, default=(TEST, TEST)) class UniqueEntryConfig(BaseCacheConfig): name = name_model stage = stage_model class Meta: unique_together = ('name', 'stage') class AppConfig(UniqueEntryConfig): _SERVER_PATH_TEMPLATE = '/service/%s/%s/%s_api' def trimmed_name(self): return self.name.replace('app_', '', 1) def cm_prefix(self): return self.name def delete(self): for config in self.capacity_configs.all(): config.delete() super(AppConfig, self).delete() def server_path(self): return self._SERVER_PATH_TEMPLATE % … -
supervisor starts the celery worker, spawn it and exits with status code (exit status 1; not expected)
WHen I start the supervisor it starts goes to RUNNING state and after few seconds again starting the celery.it continuously doing the scenario. checked the supervisor log, seen that it spawned the worker with pid and goes to success and again goes to exited state. tried wth shutting down the supervisor and started again. Please find the log of supervisor.log 2019-07-16 11:06:48,798 INFO exited: celeryd (exit status 1; not expected) 2019-07-16 11:06:42,539 INFO success: celeryd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) 2019-07-16 11:06:48,798 INFO exited: celeryd (exit status 1; not expected) I expect to run continuously and respond for the command what I give. -
How can I use the Reddit API to render images in my HTML file
I am attempting to use the Python Reddit API Wrapper (Praw) to obtain the title of a subreddit, and then display that image in my HTML, using Django. I am using Django 2.1.5, Python 3.6.3. I have been able to successfully obtain the URL for the images in a separate test python file, which simply prints out the URL to the console. Now I am trying to figure how I would be able to use django so that I can display the images in my HTML. views.py from django.shortcuts import render, praw, requests def subRedditImage(request): reddit = praw.Reddit(client_id='NPZ4FBKzYYELuA', client_secret='vemVHnxnUTn1hrUxeHNDRSXyzqA', user_agent='RedditScroller by XXX') subreddit = reddit.subreddit('FoodPorn') submissions = subreddit.hot(limit = 10) return render(request, 'scrollapp/base.html', submissions) base.html {% block content%} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Reddit</title> <h1>Hot posts</h1> <img src="{{ submissions }}" alt=""> </body> </html> {% endblock content %} I would like to display the images obtained from the reddit api on my html page. I receive an error when attempting to load the page: Traceback: File "C:\Users\J\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\J\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\J\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = … -
NoMatchReverse error ListView to DetailView can't seem to pass url parameters
I have been struggling with this problem for over a day now. I truly don't understand what to look for when it comes to NoReverseMatch errors. Every time I supply an answer to the error, i get a new error that I don't know how to deal with. Would really appreciate some help with understanding how to debug this issue because I am at a loss right now. I am building a website that has two apps. 1. The main website and 2. a Blog. I created the blog app recently and hooked up the urls so that from the home page, you can go to the blog home (a listview) and then all I want is to make it so that users can click on the title of the article that interests them, and it will display the text and other info associated with the article. The problem is I continually keep getting NoReverseMatch errors on either the blog home page or the blog detail view page and I have no idea where to even begin in troubleshooting it. I am new to OOP, Django, and python and so this is all very disorienting. My most recent error I … -
Why am I getting an error when using a django generic view?
i have just started using django, and I keep getting this error now. Also not sure how I can give an additional parameter to the view (url for example). Will appreciate any help In urls.py path('page/<path:url>', TemplateView.as_view(template_name='pages/page.html')) <a class="dropdown-item" href="{% url 'channels:page' post.url %}" target="_blank"> -
How to convert Database records to table using Pandas
I have a django model as below: class WhatsLeft(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE) game_round = models.ForeignKey(GameRound, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) count = models.IntegerField(blank=True, null=True) Ignoring the contest field, I want to convert this into an html table with game_round as the horizontal header, teams as the vertical header and then the counts within the cells. I can do this easily within the template using nested for loops but it is loads of calls to the database. Is there a way to convert this to a table using something like Pandas? -
get_object_or_404 inherited classes
I have a abstract class Type and it have 3 inherited classes Type1 Type2 Type3 70% of these 3 class properties are the same. i want like this; def game_detail(request,tournamentslug,slug,gameslug): tip1=get_object_or_404(Type1, tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,) tip2=get_object_or_404(Type2,tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,) tip3=get_object_or_404(Type3,tournament__slug=tournamentslug,slug=slug,game__slug=gameslug,) How can i do ? tournamentslug,slug,gameslug is base class fields -
pass variable from home flask app to remote flask app python
I have two flask files. One is home.py and the other is remote.py. The remote.py will be on another computer in LAN which acts as a server. The home.py will be in my computer. In the home.py, i pass the url for accessing the remote.py file and if the url gets accessed,the home.py executes the route for adding two numbers and store the result in c variable and sent c to the remote.py file. In remote.py file, I have a route for getting c value from the home system and store it in a get_c variable. Here's the Sample Code i tried: home.py from flask import Flask app = Flask(__name__) @app.route('/sum_value_pass', methods=['POST']) def sum_value_pass(): try: url = '192.168.1.3:5001/sum_value_get' if url accessed: a = 4 b = 4 c = a + b print(c) # send c value to remote system except: print("URL offline") if __name__ == '__main__': app.run(host='0.0.0.0', port=5002) remote.py from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/sum_value_get', methods=['POST']) def sum_value_get(): get_c = [] print(get_c) # get c from home system not yet written if __name__ == '__main__': app.run(host='192.168.1.3', port=5001) This is what i tried. I don't know how to pass variable between two flask app. Help me … -
Reverse generic relations and Generic Relations
in a simple scenario, where i have many measurements table that describe the measurements that comes from a specific protocol and every measurement it's linked to the respective parent device, i was looking for an optimization of my database, putting all the measurements into a table and reference from this table the respective device. Now, keeping in mind that this table it's heavily used in read/write and especially in filtering operations, i was looking for a smarter solution...i've found the Django Generic Relations and Reverse Relations...but this approach it doesn't convince me at all... because, as now, with a simple select with a where the problem it's solved...but using a generic relation, the ORM will generate a lot of inner joins (if i'm not wrong...) and this is an aspect that i want to avoid. So, anyone with smarter idea? My goal is to remove tons of if into my code that at this time are used to decide what table it will be queried based on the protocol type -
Test form which has a choicefield dynamically decided choice items depend on request.user from view
In my form there's a choicefield which has choices depend on the user's condtion. The form get user from request.user from view at the initialization of the form. My question is, how to set user info' in form's unit test? I got error message as below: ERROR: test_form_valid (zmock.tests.test_forms.TestForm) Traceback (most recent call last): File "D:\dp\opc_community\zmock\tests\test_forms.py", line 16, in test_form_valid 'msg': 'mymsg', File "D:\dp\opc_community\zmock\forms.py", line 23, in init self.user = kwargs.pop('user') KeyError: 'user' Below is the test I wrote and related python codes. test_forms.py from django.test import TestCase from ..forms import EntryPostForm class TestForm(TestCase): fixtures = ['myfixture.json', ] def test_form_valid(self): login_result = self.client.login(email='foo@bar.com', password='foobar1234', ) self.assertTrue(login_result) form = EntryPostForm(data={ # 'user': self.request.user, 'title': 'mytitle', 'msg': 'mymsg', }) self.assertTrue(form.is_valid()) forms.py from django import forms from .models import Entry CHOICES_THREE = [ (1, 'PUBLIC'), (2, 'FORUM USER ONLY'), (3, 'PREMIUM USER ONLY'), ] CHOICES_TWO = [ (1, 'PUBLIC'), (2, 'FORUM USER ONLY'), ] class EntryPostForm(forms.ModelForm): postto = forms.ChoiceField(widget=forms.Select, choices=CHOICES_THREE) class Meta: model = Entry fields = ['title', 'msg', 'postto'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(EntryPostForm, self).__init__(*args, **kwargs) if self.user.is_staff or self.user.groups.filter(name='mygroup').exists(): self.fields['postto'].choices = CHOICES_THREE else: self.fields['postto'].choices = CHOICES_TWO views.py from django.views.generic import CreateView from .models import Entry from .forms import … -
How to force logout when Knox created token has expired?
I developed my Django based webapp with token authentication by following this tutorial of Brad Traversy (https://www.youtube.com/watch?v=0d7cIfiydAc) using Knox for authentication and React/Redux for the frontend. Login/logout works fine (here is Brad's code: https://github.com/bradtraversy/lead_manager_react_django/blob/master/leadmanager/frontend/src/actions/auth.js --> logout using a POST request), besides one issue: When the user stays away from the computer for a long time, the token expires in the meanwhile. So when the user returns he is still in the logged in zone of the website, but as soon as he opens a React component with data loading from the DB a 401 error is thrown in the console ("Failed to load resource: the server responded with a status of 401 (Unauthorized)"). Then the user has to go on "logout" and login again. This is not optimal, I would prefer that after the user returns, the system realizes the token expiry and logs the user automatically out. I have thought of the following approaches, but I am not sure how to implement it or which one is best: 1) For every API request: if the answer is 401 --> logout (this might also log the user out in case the token has not expired, but if there is some … -
User custom extend AbstractUser does not appear in 'Authentication' admin panel
I know this problem is common on stack, and I've tried numerous answers Like this one, and more alike. So my goal is to extend User to add some custom fields. In models.py I have added the following class MyUser(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): # __str__ for Python 3, __unicode__ for Python 2 return self.name class Meta: app_label = 'app_name' In admin.py I have added the following: class CustomUserAdmin(UserAdmin): model = MyUser filter_horizontal = ('user_permissions', 'groups',) admin.site.register(MyUser, CustomUserAdmin) In settings.py I have the following: AUTH_USER_MODEL = 'app_name.MyUser' In urls.py: admin.autodiscover() To be noted that I have deleted all my migrations and regenerated them after these changes I have also tried to add in form.py custom Creation and Change form like follows, without success: class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = MyUser fields = '__all__' class CustomUserChangeForm(UserChangeForm): class Meta: model = MyUser fields = '__all__' To be noted that in my database, the user schema is updated with the new field ! But the problem is that it does not appear in the admin pannel section Thank you in advance for your help -
use a web-based image as background with inline style tags, django
im using django2.2 and python3. i only mention that in the event that, somehow, thats apart of why none of this is working. i have a file, search.html. literally the only code in the entire file is as follows: <html> <body style="background:url("https://www.coolpix.com/image123")> some text here </body> </html> the goal here is simply to render the image as the background for the page, yet the only thing that shows up is the text. initially i tried to make this work by using my CSS file, but i couldnt get it to work for some unknown reason. so the next step i took was to just go directly into the html file and make it show up that way. ive tried several different images from several different websites, and nothing seems to work. what could i possibly be doing so wrong? -
I can't filter based on a field in one-to-one field reference to another model
I want the to be able to filter on email in Student. like when I do this: Student.objects.get(email="k@gmail.com") The row where the student has email="k@gmail.com" where be returned. I've tried using the below version and that gave me this error: .... ValueError: invalid literal for int() with base 10: 'kkk@gmail.com' I have also tried to print out type: views.py for l in ll: print(type(l.email.email)). # got <class 'str'> print(type(l.language_to_learn)) print(type(l.email)) # got <class 'users.models.CustomUser'> def profile_list(request): profile=Student.objects.get(email=request.user.email) return render(request,'view_profile.html',{'profile':profile}) models.py class Student(models.Model): email=models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True,) language_to_learn=models.CharField(max_length=20,choices=Language_Choices,default='English',) REQUIRED_FIELDS=['language_to_learn',] class CustomUser(AbstractUser): username = None email = models.EmailField('email address' ,unique=True,blank=False, null=False) USERNAME_FIELD = 'email' fullname=models.CharField('Full name',max_length=50,null=True) REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS objects = UserManager() -
Django default value in model based on data that hasn't been loaded yet
When creating migrations for Django I'm running into an instance where I need to set the default value for a custom user based on another table. # models.py def get_default_item(): return Item.objects.filter(name='XXXX').first().id class CustomUser(AbstractUser): # ... item = models.ForeignKey(Item, on_delete=models.CASCADE, default=get_default_item) # ... I'm running into two issues: I need to ensure that the table for Item is already created. I think I can do this using dependencies. I need to ensure that the Item "XXXX" is created before it is referenced. Unfortunately this can't happen until I migrate the data over because the Item IDs need to be consistent with the old system and (unfortunately) I can't use id 0 with a Django / MySQL combination because that has special meaning. Is there a way to tell the migration "don't worry about this default for now, you'll get it later"? -
How to convert Python datetime object to specific timezone in Django Rest Framework?
I'm working on an existing codebase which implements an api using Django and the django-rest-framework. When you post a datetime like this: 2019-06-21T10:35:46+02:00 it is stored in UTC as 2019-06-21 08:35:46+00 (as expected). This is because I've got USE_TZ = True. When I serve the data, I also want it to be converted to the localised format again (2019-06-21T10:35:46+02:00). So following this tip I implemented it like this: class DateTimeFieldWihTZ(serializers.DateTimeField): """ Class to make output of a DateTime Field timezone aware """ def to_representation(self, value): value = timezone.localtime(value) return super(DateTimeFieldWihTZ, self).to_representation(value) class PeopleMeasurementSerializer(HALSerializer): class Meta: model = PeopleMeasurement fields = [ '_links', 'id', 'timestamp', 'sensor', 'count' ] timestamp = DateTimeFieldWihTZ(format='%Y-%m-%d %H:%M:%S') But this serves it as 2019-06-21 08:35:46. How can I serve it as 2019-06-21T10:35:46+02:00 again? -
How to range items in for loop?
I am fetching data from database by the name field.title and field.img in views.py and I made loop and gave range to it of 2 items but it is fetching every item from database. I use __ in for loop range but whenever I use field in range it gives me AttributeError. Destination is a class in models.py target1 = Destination.objects.all() for field in target1: for __ in range(2): field.img field.title -
Django Unable to import models
Actually am trying to import a models form posts folder and i am getting this following error.. AttributeError: module 'posts' has no attribute 'views' here is urls.py from django.contrib import admin from django.urls import path from . import views from django.conf.urls import include import accounts import posts urlpatterns = [ path('admin/', admin.site.urls), path('',views.home, name = 'home'), path('login/',include('accounts.urls')), path('signup/',accounts.views.signup, name='signup' ), path('logout/',accounts.views.logout, name='logout'), path('posts/',posts.views.myposts) ] here is my posts folder Here is my posts.views from django.shortcuts import render, HttpResponse # Create your views here. def myposts(request): return HttpResponse('all_post.html') -
Django Can't Resolve Style ine fil static
Hello i can't resolve static file (vendor,bootstrap,css,js) i can t see the picture with color just baisc formular need help to resolve this i followed the documentation step by step but this step didnt work this is my code html : <!DOCTYPE html> <html lang="en"> <head> {% load static %} <title>Login V9</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--===============================================================================================--> <link rel="icon" type="image/png" href="{{ static 'AppStage/images/icons/favicon.ico' }}"/> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/bootstrap/css/bootstrap.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/fonts/font-awesome-4.7.0/css/font-awesome.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/fonts/iconic/css/material-design-iconic-font.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/animate/animate.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/css-hamburgers/hamburgers.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/animsition/css/animsition.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/select2/select2.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/vendor/daterangepicker/daterangepicker.css' %} "> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/css/util.css' %} "> <link rel="stylesheet" type="text/css" href="{% static 'AppStage/css/main.css' %} "> <!--===============================================================================================--> </head> <body> <div class="container-login100" style="background-image: url('images/paul.jpg');"> <div class="wrap-login100 p-l-55 p-r-55 p-t-80 p-b-30"> <form class="login100-form validate-form"> <span class="login100-form-title p-b-37"> Sign In </span> <div class="wrap-input100 validate-input m-b-20" data-validate="Enter username or email"> <input class="input100" type="text" name="username" placeholder="matricule"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-25" data-validate = "Enter password"> <input class="input100" type="password" name="pass" placeholder="password"> <span … -
Filtering by variable's value. How does .filter(**{filter_name: filter_value}) work?
So this magic: filter_name = 'some_field_from_model' filter_value = 'some_val' Object.filter(**{filter_name: filter_value}) works. But how does it work? What does ** do? I am fascinated but I don't understand this at all. Can someone explain what is happening here? Thanks a lot. Python newb here.