Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create form fields dynamically from ChoiceField values?
I created a form with a ChoiceField which have multiple integers like that: And I want to add other fields (like CharField, etc) depending on that integer choice. I explain: if you choose 1, one CharField is added. If you choose 2, two CharField are added, etc etc. BUT, on the same page without reload or refresh the page. I don't know how to process, should I use JavaScript ? Or there is a solution to get ChoiceField value and create fields without reloading the page ? I hope I was accurate, I can tell you more information on what I want to do if you need it. Thanks a lot! -
Dango sends emails twice after form submission
I was trying to send emails when a form is submitted in my app, and I managed to do it but for some reason it sends it twice every time. After some search and debugging I think I know where the problem is but I don't know why. So the email sending function of my app takes place in my forms. py and looks like this: class approvalForm(forms.ModelForm): text1 = forms.ModelChoiceField(disabled = True, queryset = Visit.objects.all()) text2 = forms.ChoiceField(disabled = True, choices = poolnumber) def save(self, commit=False): instance = super(approvalForm, self).save(commit=commit) ready = instance.visible if ready is True: self.send_email() instance.save() print('yay sent') else: None return instance def send_email(self): var = self.cleaned_data tomail = self.cleaned_data.get('visit') tomails = tomail.location.users.all() tomaillist = [] for item in tomails: tomaillist.append(item.email) print(tomaillist) msg_html = render_to_string('myapp/3email.html', {'notify': var}) msg = EmailMessage( 'Text here', msg_html, 'myemail@email.com', tomaillist, headers={'Message-ID': 'foo'}, ) msg.content_subtype = "html" print("Email sent") msg.send() class Meta: model = MyModels fields = ('text1','text2', ) The save() function is runnig 2 times. I've tried to move the email sending function to the views.py in the form_valid() function but it's never called so I've tried the form_invalid() but same results. Is there any way to not let the save() … -
How to download a data table in python as pdf while keeping the formatting as desired?
I want to download a python data table as a pdf. I have tried converting it into an HTML table and then download it. The formatting is not maintained that way. This is possible with js but I need python based solution. Format preview should be able to be viewed in my application( Django or dash). And I would like teh option of changing format templates from my app. ex:- Selecting blue will make the header of each column blue in color, etc. Is there any way to converting datatable to pdf without first converting it into HTML. -
Add photos in Django backend with Froala editor
I'm trying to use Froala Editor in Django backend but I cant add photos. In my urls.py in root directory I've added url as follow: urlpatterns = patterns('', url(r'^$', include('main.urls')), url(r'^froala_editor/', include('froala_editor.urls')) ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In setings.py the I have as follows: STATIC_URL = '/assets/' STATIC_ROOT = "/var/www/frontend/website/public/" FRAOLA_EDITOR_THIRD_PARTY = ('image_aviary', 'spell_checker') FROALA_UPLOAD_PATH = "assets/froala_editor/images" In models.py I have field as follow: content = FroalaField(theme='dark') But when I try to add a photo in django admin I get an error as follows: "IMAGE CANNOT BE LOADED FROM THE PASSED LINK" -
Website made with Django for e-commerce site's post-office workers
I am going to create a new website for an e-commerce website in order to give information from e-commerce web'sites api to the new website and display it. This website should have these: Registration, login and logout parts in the top of navbar, Search input to search people in the e-commerce website's api And it should display information of the person who has been searched. So It is easy website. But I can't. Because I am pretty beginner now. Can anyone help me? Thanx in advance. -
How to display remaining Date and Time from DateTimeField in django
Here I have a simple function for sending leave request and accepting by the admin.This code works for now but I want to add some feature here.For example if the leave days was for 2 then after the leave has been accepted by the function below def accept_leave(request,pk): I want to display the remaining days of leave(Example:1 day 12 hours and 30 sec. remaining to complete leave ).After 2 days completed it should display some message like you leave has been completed. I got no idea for starting this .How can I do it ?Any help would be great. Is there any mistake in my approach ? models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateTimeField() end_day = models.DateTimeField() #day = models.IntegerField(default=0) is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) sent_on = models.DateTimeField(auto_now_add=True) views.py def send_leave_request(request): form = MakeLeaveForm() if request.method == 'POST': form = MakeLeaveForm(request.POST) if form.is_valid(): leave_days = form.cleaned_data['day'] org = form.cleaned_data['organization'] start_day = form.cleaned_data['start_day'] end_day = form.cleaned_data['end_day'] diff = end_day - start_day leave_days = diff.days print('org',org) if leave_days > request.user.staff.organization.max_leave_days: messages.error(request,'Sorry can not be sent.Your leave days is greater than {}.'.format(request.user.staff.organization.max_leave_days)) return redirect('organization:view_leaves') else: leave = form.save(commit=False) leave.staff = request.user … -
Pass list of strings into raw sql query (Python/Django)
I need to pass a dynamic list of strings into raw sql query. Here is my code: myList = ['PREFIX\000\000923', 'PREFIX\000\000CS3'] <- strings I have troubles with myList = ['OK1', 'OK2'] <- ok strings myTuple = tuple(myList) query = "SELECT * FROM public.items WHERE name IN {}".format(myTuple) result = cursor.execute(query, myTuple) rows = dict_fetch_all(cursor) for row in rows: print(row) The above piece of code works just fine. However, there is a problem with strings with special characters with backslashes like this: "PREFIX\000\000923". What is the right way to code it? -
How to display a random video from a file in django?
I'm trying to make a video display randomly on my homepage. A user is able to upload a video and it would be saved to a document in media/documents as well as to a dataset. I tried the code below and it keeps giving me an error, {% load media %} {% for doc in document %} <video width='320' height= '240' controls> <source src="{% media 'doc.document' %}" type='video/mp4'> Your browser does not support the video tag. </video> {% endfor %} Exception Type: TemplateSyntaxError at / Exception Value: 'media' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz I removed if settings.DEBUG: from urls.py, however this didn't work. models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.conf import settings ... class Document(models.Model): title = models.CharField(max_length=100, default='NoTitle') description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField("date published")#(auto_now_add=True) creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title urls.py urlpatterns = [ path('admin/', admin.site.urls), path("", views.homepage, name="homepage"), path("myconta/", views.myconta, name="myconta"), path("upload/", views.model_form_upload, name="upload"), path("register/", views.register, name="register"), path('', include("django.contrib.auth.urls")), ] #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def homepage(request): return render(request=request, template_name="main/home.html", context={"sites": Info.objects.all}) return … -
Django Smart Selects Still Showing All Options
I am trying to work with django smart selects for the first time, but I cannot get it to work. I assume I must be doing something wrong in my setup but I cannot identify what it is. I have three models. Customer, BillTo, and Orders. In the Order, the user should select a Customer, and then the BillTo options should be dependent upon the Customer selected. Right now, I am still seeing all BillTo options regardless of Customer. Could someone please help me identify where I am making a mistake or missing something - this is really holding up my project. models.py class Customers(models.Model): ultimate_consignee = models.CharField(max_length=100) def __str__(self): return self.ultimate_consignee class BillTo(models.Model): ultimate_consignee = models.ForeignKey(Customers) c_address = models.CharField(max_length=1000) def __str__(self): return self.c_address class Orders(models.Model): reference = models.CharField(max_length=50, unique=True) #REQUIRED ultimate_consignee = models.ForeignKey(Customers, blank=True) #REQUIRED c_address = ChainedForeignKey(BillTo, chained_field='ultimate_consignee', chained_model_field='ultimate_consignee', show_all=False, blank=True, default=None, null=True) def __str__(self): return self.reference add_order.html {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST" enctype='multipart/form-data'> <br> <h2>Order Information</h2> <br> {% csrf_token %} <div class="column_order"> <label for="form.reference" class="formlabels">Reference ID: </label> {{ form.reference }} <br> <label for="form.ultimate_consignee" class="formlabels">UC: </label><br> {{ form.ultimate_consignee}} <br> <label for="form.c_address" class="formlabels">Ship To: </label> <br> {{ form.c_address}} </form> </div> </div> <script … -
How to save the ManyToManyField to model using POST method.? (Python 3.6, Django 2.2.)
I have 3 models one is Category(Fields = category_name) and another one is SubSategory(Fields = category(ForeignKey to Category),sub_category).and another model is DummyModel. # Model class DummyModel(models.Model): name = models.CharField(max_length=20) email = models.EmailField() category = models.ManyToManyField(Category) sub_category = models.ManyToManyField(SubCategory) This is my form class StartProjectForm(ModelForm): class Meta: model = StartProject fields = ( 'name', 'email', 'category', 'sub_category', ) def __init__(self, *args, **kwargs): super(StartProjectForm, self).__init__(*args, **kwargs) self.fields["category"].widget = CheckboxSelectMultiple() self.fields["category"].queryset = Category.objects.all() self.fields["sub_category"].widget = CheckboxSelectMultiple() self.fields["sub_category"].queryset = SubCategory.objects.all() def save(self, commit=True): clean = self.cleaned_data.get name = clean('name') email = clean('email') category = clean('category') sub_category = clean('sub_category') obj = StartProject() obj.name = name obj.email = email obj.category = category obj.sub_category = sub_category obj.save() When I try to save Error Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. -
Django activity-stream delete verb gives UnicodeEncodeError
in a Django 1.11.24 (python2.7) I'm having problems with a german 'umlaut'. When a resource is deleted I'm creating an acticity stream with following config: action_settings = defaultdict(lambda: dict(actor=getattr(instance, "owner", None), action_object=instance, created_verb=_('created'), deleted_verb=_('deleted'), object_name=getattr(instance, 'name', None), target=None, updated_verb=_('updated'), )) deleted_verb=_('deleted') gives gelöscht. Trying to open this activity in Django-admin ends in UnicodeEncodeError at /de/admin/actstream/action/79/change/ 'ascii' codec can't encode character u'\xf6' in position 9: ordinal not in range(128) I've tried to encode the value to unicode like deleted_verb=_('deleted').encode('utf-8'), or deleted_verb=unicode(_('deleted')), without luck. How can I correctly get rid of the Unicode error? -
How to compare two Django models and display the answer in the third model
I have two completely identical models in structure: class Model_A (models.Model) id_value = models.CharField(primary_key=True, max_length=45) some_value_1 = models.IntegerField(blank=True, null=True) some_value_2 = models.TextField( #and etc. I have many fields class Model_B (models.Model) id_value = models.CharField(primary_key=True, max_length=45) some_value_1 = models.IntegerField(blank=True, null=True) some_value_2 = models.TextField(blank=True, null=True) #and etc. I have many fields First, I try to compare all the field parameters with each other. Second, if the parameters are not the same, and write the answer in the third table(indicating each inequality by its ID and field name) . class Third_Model(models.Model): auto_increment_id = models.AutoField(primary_key=True) id_value = models.CharField(max_length=45, null=False) field_name = models.CharField(blank=True, null=True) value_from_A = models.CharField(blank=True, null=True) value_from_B = models.CharField(blank=True, null=True) How do I perform this action using Python models? Provided that the models have a lot of fields and the models themselves are more than 40 pieces. Here is an example of what I want to do with the sql query example. INSERT INTO `third_table` (`field_name`, `id_value`, `value_from_A`, `value_from_B`) SELECT id_value, manage_objects, param_name, fld_param , ref_param FROM (SELECT id_value, 'Model_name' AS manage_objects, param_name, max(val1) AS fld_param, max(val2) AS ref_param FROM ((SELECT id_value, 'some_value_1' AS param_name, some_value_1 AS val1, Null AS val2 FROM model_a ) UNION ALL (SELECT id_value, 'some_value_2' as param_name, some_value_2 AS … -
how to sum all the consummations for a specific client that is a foreign key in the consummation model?
class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') def get_absolute_url(self): return reverse('clients:consommation_detail', kwargs={'pk': self.pk}) def __str__(self): return 'Consommation numero :' + str(self.id) @staticmethod def get_nom(item, _default=' '): if item: return item.nom return _default @staticmethod def get_price(item, _default=0): if item: return item.price return _default def total_consommation(self): get_price = Consommation.get_price return get_price(self.entree) + get_price(self.food) + get_price(self.dessert) + get_price( self.boisson) + get_price(self.autres) I tried this to get the total of consummation of a client: def total(self): return self.vipcustomer.vip_consommations.annotate(Sum(self.total_consommation())) in the template I have this: {% for consommation in vipcustomer.vip_consommations.all %} <ul> <li> <a href="{% url 'clients:consommation_detail' pk=consommation.pk %}"> </li> </ul> {% endfor %} Total : <strong>{{ vipcustomer.vip_consommations.total}} MRO</strong> ` How to sum the consummations for a vipcustomer that is foreign key to the consummation. Thanks -
How can I fix my modal to work using Javascript?
I decide to make a modal for my homepage using Vanilla JavaScript. I have looked at several examples on how to build a modal from scratch but I'm stuck at getting the display property to change using my JavaScript code. <script type="text/javascript"> var span = document.getElementsByClassName("ex"); var modal = document.getElementsByClassName("vid-modal") function clearModal() { modal.style.display == "none"; } function windowOnClick(event) { if (event.target === span) { clearModal(); } } function fireWhenReady(func) { document.addEventListener('DOMContentLoaded', func) } fireWhenReady(windowOnClick); </script> .vid-modal { position: fixed; background-color: rgba(0, 0, 0, 0.4); width: 1000px; height: 500px; top: 250px; left: 50%; margin: 0 auto; z-index: 1002; transform: translateX(-50%); /* display: initial; */ /* aug 21 still working on modal display */ display: initial; } <div class="vid-modal"> <span class="vexit"><i class="fa fa-window-close ex" aria-hidden="true"></i></span> <div class="vid-box"> <iframe id="front-video" src="https://www.youtube-nocookie.com/embed/Hua4MRTKmy0?rel=0&amp;controls=0&amp;showinfo=0;autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> </div> I expect to set the display property to "none", and apply more advance solutions to this code. -
How to call the correct view method in Django?
I have a project with these files and folders: ... old project new common manage.py ... I access the "old" using http://127.0.0.1:8000/old and there are views, form urls, etc files inside this folder. all works fine. I have similar files inside "new" folder as well. It also runs well: http://127.0.0.1:8000/old However I run into problems when I have a method inside view ("method1") and I declare it inside urls. However it searches for the method1 inside folder "old" not in "new". $.post('{% url "method1" %} inside urls I have path('method/', views.method1, name='method1'), I have no idea why this js searches for method1 inside "old". When I declare method1 inside old folder, it works fine. What am I missing here? -
django all-auth authenticating via twitch
I am trying to authenticate a user from twitch Auth using Django and reactjs. I am able to authorize the user and store its details in the Django admin from backend but not sure how to do it from reactjs. What I tried so far: Following the documents from here: https://django-allauth.readthedocs.io/en/latest/installation.html I configured everything as: settings.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.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.twitch', 'django_extensions', 'users.apps.UsersConfig', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = app-name.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sphinx.wsgi.application' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } I also registered the social application in the Django admin. When I hit: http://localhost:8000/accounts/twitch/login/ It takes me to the twitch authorization page, Which when I click on "Authorize" saves the user details in the Django admin redirects me back to the url: http://localhost:8000/accounts/profile/ The problem is I need to make sure the LOGIN_REDIRECT_URL page '/accounts/profile/' has some authentication so only the logged in user can access it and to display the username of that … -
How can I use dynamic redirect urls in slack oAuth redirect url?
I have a web page that requires a document id. I used slack authentication for the authentication. (because the web page is requesting from the slack channel). Slack requires redirect URL. So how can I put this dynamic redirect URL in slack? The URL is => http://localhost:3000/document/ I tried to put it like this => http://localhost:3000/document/<> but it did not work. -
How to add view permissions in Django 1.9
I am using Django 1.9, and I need to add a permission for a user to only be able to view data in the admin panel. Currently my only options are add, change & delete. Does anyone know how I can go about doing this? I don't really know what to try. -
Create Custom Mixins in Django
I want to create mixins from normal function. from taggit.models import Tag def remove_all_tags_without_objects(): for tag in Tag.objects.all(): if tag.taggit_taggeditem_items.count() == 0: tag.delete() else: pass I want to convert above function into mixin os i can re use it. -
python-django on gcp server not responding
I have deployed the python-Django project on GCP instance. The problem I am facing is that it responds on external IP for a couple of hours then it failed to respond.when I try to open VM-instance it failed to open my ssh instance.in order to start every time I need to stop and start the instance again.Thanks in advance -
Django cron error No module named 'my_app'
I'm trying to send some emails in Django by Django Cronjob but getting an error ModuleNotFoundError: No module named 'my_app' Cron Job Code class MyCronJob(CronJobBase): RUN_EVERY_MINS = 5 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'app.MyCronJob' def do(self): email = EmailMessage('hi', 'message', to=['demo@gmail.com']) email.send() I've tried from .. import my_app but getting an error after adding this import line as well ValueError: attempted relative import beyond top-level package -
How to compare integer field with Datetime in django?
Here I have a simple function for sending leave request and accepting by the admin.This code works for now but I want to add some feature here.For example if the user enter day = 2 which is IntegerField then it get stores into databse then after the leave has been accepted by the function below def accept_leave(request,pk): I want to display the remaining days of leave(Example:1 day 12 hours and 30 sec. remaining to complete leave ).After 2 days completed it should display some message like you leave has been completed. I got no idea for starting this .How can I do it ?Any help would be great. Is there any mistake in my approach ? models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() day = models.IntegerField(default=0) is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) sent_on = models.DateTimeField(auto_now_add=True) views.py def send_leave_request(request): form = MakeLeaveForm() if request.method == 'POST': form = MakeLeaveForm(request.POST) if form.is_valid(): leave_days = form.cleaned_data['day'] org = form.cleaned_data['organization'] leave = form.save(commit=False) leave.staff = request.user leave.organization = org leave.save() return redirect('organization:view_leaves') return render(request,'organization/send_leaves.html',{'form':form}) def accept_leave(request,pk): leave = get_object_or_404(Leave, pk=pk) leave.is_accepted = True leave.is_rejected = False leave.day = ? leave.save() return redirect('organization:leave_detail',leave.pk) -
Django Rest Framework: Retrieving associated items from foreign key relationship in serializer
I'm trying to retrieve associated (FK) rows/values through my serializer. I have an Order model and a Food model, where one or many Food belongs to one Order like so: class Order(models.Model): total_price = models.DecimalField(decimal_places=2, max_digits=4, null=False) status = models.ForeignKey(OrderStatus, related_name='order', on_delete=models.CASCADE, null=False) placed_datetime = models.DateTimeField(null=False) class Food(models.Model): order = models.ForeignKey(Order, related_name='food', on_delete=models.CASCADE) quantity = models.IntegerField(null=False) price = models.DecimalField(decimal_places=2, max_digits=4, null=False) And my serializers: # Order Details serializer class OrderDetailsSerializer(serializers.ModelSerializer): foods = FoodSerializer(many=True, read_only=True) class Meta: model = Order fields = ("id", "status", "total_price", "placed_datetime", "foods") status = serializers.SerializerMethodField("get_status_label") def get_status_label(self, obj): return obj.status.label class FoodSerializer(serializers.ModelSerializer): ingredients = FoodIngredientSerializer(many=True, read_only=True) class Meta: model = Food fields = ("size", "quantity", "price", "ingredients") No luck with the above approach. -
Django-filter displaying all the records, While submitting empty form
Right now i have completed filtering function using django-filters. But while submitting the form empty, its fetching all the records. My code is working fine. I have restricted django-filter from displaying all the records while page startup .Also i don't want to display all the records while submitting empty form. version_filter.html <form action="" method="GET"> <button class="btn btn-primary btn-sm" type="submit">Submit</button> {{filters.form.as_table}} </form> views.py def bfs_version_filter(request): version_obj = bfs_versions.objects.all() filter_obj = version_filter(request.GET, queryset = version_obj) return render(request, 'bfslite/version_filter.html', { 'filters' : filter_obj,}) filter.py class version_filter(django_filters.FilterSet): bfs_version_code = django_filters.CharFilter(lookup_expr = 'icontains', label = "Version") bfs_version_status = django_filters.ChoiceFilter(field_name = "bfs_version_status", choices=TASK_STATUS, lookup_expr='exact', label = "Version Status") bfs_version_end_date = django_filters.DateFilter(widget=forms.widgets.DateInput(attrs={'type':'date'}), label= "End Date") bfs_version_uploaded_on = django_filters.DateRangeFilter(label= "Uploaded on") bfs_task_code__bfs_client_eta = django_filters.DateFilter(widget=forms.widgets.DateInput(attrs={'type':'date'}), label= "Client Date") bfs_shot_code__bfs_shot_code = django_filters.CharFilter(lookup_expr = 'exact', label = "Shot") bfs_task_code__bfs_task_name = django_filters.CharFilter(lookup_expr = 'exact', label = "Task") #payable and paid bfs_version_payable = django_filters.BooleanFilter(field_name='bfs_version_payable', lookup_expr= 'exact', label = "Payable") bfs_version_paid = django_filters.BooleanFilter(field_name='bfs_version_paid', lookup_expr= 'exact', label = "Paid") def __init__(self, *args, **kwargs): super(version_filter, self).__init__(*args, **kwargs) if self.data == {}: self.queryset = self.queryset.none() class Meta: model=bfs_versions fields=[ 'bfs_version_code', 'bfs_version_status', 'bfs_version_end_date', 'bfs_version_uploaded_on', 'bfs_task_code__bfs_client_eta', 'bfs_shot_code__bfs_shot_code', 'bfs_task_code__bfs_task_name', 'bfs_version_payable', 'bfs_version_paid', ] -
How to authenticate user if password set as set_unusable_password()
I want to realize login for user with password which I set in models with help of set_unusable_password. I don't know how to realize authenticate for this user. Can I decode password which is record in db or can I realize my own authenticate function and after that use login(request, user)? Method for creating user with unusable password: @staticmethod def create_user_via_facebook(first_name, last_name, userId): user = User(first_name=first_name, last_name=last_name, email=userId) user.set_unusable_password() user.save() return user