Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make a django bootstrap breadcrumbs
how do I create dynamically a django bootstrap breadcrumb like that : home > category > product > product_detail ? I've tried using documentation but can't implement it . this is my_project urls : from django.contrib import admin from django.urls import path , include urlpatterns = [ path('accounts/' , include('accounts.urls') ), path('' , include('products.urls' ) ), this is my_app urls : from django.urls import path from . import views urlpatterns = [ path('' , views.index , name='index' ), ] urlpatterns += [ path('category_1' , views.category_1, name='category_1' ), path('category_2' , views.category_2, name='category_2' ), path('category_3' , views.category_3, name='category_3' ), path('product_detail /<str:product_title>/' , views.product_detail , name='product_detail '), ] this my views : from django.shortcuts import render , get_object_or_404 from .models import category , product def index(requset): category = category .objects.all() category_1= product.objects.filter(category=category[0]) category_2= product.objects.filter(category=category[1]) category_3= product.objects.filter(category=category[2]) context = { 'category_1':category_1, 'category_2':category_2, 'category_3':category_3, } return render(requset, "products/index.html", context) def product_detail (requset ,product_title): all_products = product.objects.filter(product_title = product_title) context ={ 'all_products':all_products , } return render( requset,'products/product_detail .html',context) -
How can I hide fields in auto-generated schemas, or define schemas explicitly?
I am using drf-yasg (Django REST Framework - Yet Another Swagger Generator) to generate docs for my RESTful API, but it's not doing exactly what I want. I thought that setting read_only and write_only attributes to True would hide fields from the documentation as they are omitted from request and response bodies, but this is not the case. I don't see any examples of defining schemas within a decorator, or even just hiding a field, but if I can learn how to do one of those things, I'll be in good shape. Let's go with a basic example: user login. # serializers.py class TokensSerializer(serializers.Serializer): """ Serializes access and refresh tokens for responses to a logged-in user. """ username = serializers.CharField(max_length=64, write_only=True) access = serializers.CharField(max_length=4096, read_only=True) refresh = serializers.CharField(max_length=4096, read_only=True) # ... class LoginSerializer(serializers.ModelSerializer): """ Serializes username, email, password, and tokens to allow for logging in. """ class Meta(): model = User fields = ['username', 'email', 'password', 'tokens'] username = serializers.CharField(max_length=64) email = serializers.CharField(max_length=254, read_only=True) password = serializers.CharField( min_length=8, max_length=64, write_only=True) tokens = TokensSerializer(read_only=True) # ... These serializers generate Tokens and Login models respectively, which are defined in the following .json and .yaml formats: { "definitions": { "Tokens": { "required": ["username"], … -
Expecting value: line 1 column 1 (char 0) (django)
hello I am getting this error and I don't know how to solve it please help this is my traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cart/update/ Django Version: 3.1.6 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'billing', 'accounts', 'products', 'orders', 'search', 'tags', 'carts', 'addresses'] Installed 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'] Traceback (most recent call last): File "c:\python36\lib\json\decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\daghe\Dev\ecommerce - Backup\src\carts\views.py", line 28, in updateItem data = json.loads(request.body) File "c:\python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "c:\python36\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\python36\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /cart/update/ Exception Value: Expecting value: line 1 column 1 (char 0) and this is my view def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'carts/home.html', context) def updateItem(request): data = json.loads(request.body) … -
WebRTC Peer to Server instead of Peer To Peer
WebRTC Peer to Server instead of Peer To Peer I want to build a WebRTC Video and Voice Calling App. However, I do not want a user to be able to connect directly to another user, as this brings unwanted security risks. So I think it makes more sense to implement the whole thing in such a way that all users (2 in this case) connect to a server, which then distributes the data and the users do not distribute it among themselves, so that, for example, the IP is publicly visible. I don't want that: So even I think this is the normal way you could do it I don't want to, because, how I said there are a lot of security risks that this kind of connection brings with it. I want that: I've heard that Discord, for example, does exactly what I show in the graphic (at least similarly). Can this be implemented? And if so, how? By the way, I used Python Django in the backend. I was wondering whether this could also be done with Python Django Channels. So is there an implementation in Django Channels that I can set up a WebRTC server? Many … -
Django filefield.open() accesses local storage instead of remote storage during data migration. Why?
Using Django 2.2 and python 3.7, deployed on Heroku I have a model with a filefield with a flexible storage location, depending on app environment (local filesystem in dev, S3 in production). We need the file upload model to do more stuff, and we're approaching it by create the new model use a data migration to copy data from the old model to the new one delete the old model The data migration works great in local (with local filesystem storage), but fails on a Heroku test server (where the files are stored in an S3 bucket). I get an error message like so: FileNotFoundError: [Errno 2] No such file or directory: '/app/private/recalls/user_74/PDIR_BBUY__9e8c995f-512f-446a-9e99-e95f0de1a4ff.pdf' Relevant code is below Existing "old" model: from django.db import models from myapp.storage_backends import storages_location, upload_file_rename class OldUpload(models.Model): recall_file = models.FileField( validators=[FileExtensionValidator(allowed_extensions=['pdf'], message=RECALL_FILE_EXTENSION_MESSAGE)], storage=storages_location(), upload_to=recall_file_rename ) myapp.storage_backends (based on Local filesystem as a remote storage in Django): import os import uuid from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings from django.core.files.storage import FileSystemStorage, get_storage_class class PrivateS3MediaStorage(S3Boto3Storage): location = settings.PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = True custom_domain = False bucket_name = settings.AWS_MEDIA_BUCKET_NAME class PrivateFileSystemStorage(FileSystemStorage): location = os.path.join(settings.MEDIA_ROOT, settings.PRIVATE_MEDIA_LOCATION) def storages_location(): media_storage = None if settings.SITE_NAME == 'LOCAL': base_url … -
How to exclude a worker from the pool available to the beat scheduler?
I have a Django app running on Heroku, with several production instances (different versions of the app, run with different env variables). I am using Celery with Redis and CloudAMQP. The contents of my Procfile: release: python manage.py migrate web: gunicorn {appname}.wsgi worker: celery -A {appname} --concurrency=3 worker beat: celery -A {appname} beat The beat is only used in app A. Only app B is currently using a worker (those dynos are only used in those particular apps). What I'm trying to do is start an app C. It needs a worker to run tasks invoked in the code, but that worker cannot be used to run scheduled tasks - they should all be run from app A. As I understand it, beat uses any free worker from the available pool. Is there a way to exclude a worker provided in app C from those used by beat? -
How to connect Pandas Table with Django Paginator
I created a table that extracts data from two files that are submitted via form. I take this file and display the table. I wanted to add pagination too, but I have a problem with the request that I can't identify. My problem is that when the request on /? Page = 2, it returns to the screen of submitting the file. Is there any other way to do this? This is the function in views.py def czech_margin (request): lines_for_page = None paginator = None data = none if request.method == 'POST' and request.FILES ['myfile']: myfile = order.FILES ['myfile'] myfile2 = request.FILES ['myfile2'] df = treatData (myfile, myfile2) json_records = df.reset_index (). to_json (orient = 'records') print (json_records) date = [] data = json.loads (json_records) #Paginator get data! = None: paginator = Paginator (date, 20) page = request.GET.get ('page') if request.GET.get ('page') is Not None else 1 lines_for_page = paginator.get_page (page) #data = data.to_html () return render (request, 'checa_margem.html', { 'table': lines_for_page }) -
Proper project structuring
I've recently started as the sole developer on a Django project. I'm currently working on updating an endpoint to including validation for incoming PDF documents. The simple validation function follows: def is_valid_certification(stream: BytesIO) -> bool: pdf = PdfFileReader(stream) page: PageObject for page in pdf.pages: if page.extractText().find("<search string>") != -1: return True return False My question is, where is the most pythonic place to store this bit of code? Keeping all the logic within the POST handler seems messy and it's not generic enough to be considered a utility. -
Why command "python manage.py migrate" after success work lock console?
I try to solve following task. I have Django app and I want to start it using Docker. As 'db' I add a container with PostgreSQL or MySQL. In my case I need run "python manage.py migrate" before "python manage.py runserver", so I wrote in docker-compose.yml file in fiels "command" folloving string:sh -c "sleep 20 && python manage.py migrate --noinput && python manage.py runserver 0.0.0.0:8000 --noreload". But after applying all migrations command "python manage.py migrate" doesn't stop and doesn't give to run "python manage.py runserver". some lines.... web_1 | Applying datapage.0001_initial... OK web_1 | Applying datapage.0002_auto_20190709_1955... OK web_1 | Applying datapage.0003_auto_20190713_1358... OK web_1 | Applying datapage.0004_auto_20190720_1107... OK web_1 | Applying sessions.0001_initial... OK If I use: docker-compose exec web python manage.py migrate we have same result: some lines.... web_1 | Applying datapage.0001_initial... OK web_1 | Applying datapage.0002_auto_20190709_1955... OK web_1 | Applying datapage.0003_auto_20190713_1358... OK web_1 | Applying datapage.0004_auto_20190720_1107... OK web_1 | Applying sessions.0001_initial... OK After pressing Ctrl + C, we get the following error: ^CException ignored in: <module 'threading' from '/usr/local/lib/python3.7/threading.py'> Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 1307, in _shutdown lock.acquire() KeyboardInterrupt Settings of docker-compose.yml: version: "3.7" services: db: image: postgres restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres … -
How to get the Expense id and passing it to Django view function
I'm struggling with finding the correct way to pass {{expense.id}} to a view function inside Django so that based on the id, I can update the expense detail. Expenses are coming from a model which relates by 'ForeignKey' to the Projects coming from another Model. I need the expense ID before submitting another form which take cares of updating that transaction. view.py def updateTransaction(request, project_slug): id: ? form.py class ExpenseForm(forms.Form): title = forms.CharField() deposit = forms.IntegerField() witdraw = forms.IntegerField() model.py class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='expenses') title = models.CharField(max_length=100) deposit = models.IntegerField(default = 0, null = True) witdraw = models.IntegerField(default = 0, null = True) created_at = jmodels.jDateField(auto_now_add = True, null = True) -
Django & PostgreSQL MemoryError + script not working correctly
I'll start by explaining the architecture of the project. There is a bot on aiogram, through which orders are created. Orders consist of lines (item), price, and order affiliation IDs. Task: The script will process all unpaid orders, and if the order has not been paid for more than N minutes, the product rows are returned to the product table, and the order is deleted. My implementation: while True: users = MyUser.objects.all().exclude(bot_username='null') now = timezone.now() for admin_user_obj in users: for order in User_purchase.objects.raw('SELECT id, time_created, chat_id, balance_to_return FROM user_purchases WHERE is_paid=FALSE and belongs=%s LIMIT 5', [admin_user_obj.id]): if order.time_created + timezone.timedelta(minutes=admin_user_obj.booking_time) < now: try: bot_user = Bot_user.objects.get(belongs=admin_user_obj.id, chat_id=order.chat_id) if order.balance_to_return: bot_user.balance += order.balance_to_return bot_user.active_orders -= 1 bot_user.save() send_order_canceled(order, admin_user_obj) for z in User_purchase.objects.raw('SELECT id, strings, item FROM user_purchases WHERE id=%s', [order.id]): add_strings(z.item, z.strings) except: pass order.delete() SQL queries because MemoryError is thrown otherwise. After launching and monitoring the logs, the script starts spamming me with the product line: enter image description here And the client told me that his 1 line of goods turned into 23 million, and several lines in the reservation turned into 7 million lines. To say that it surprised me is to say nothing. models.py class User_purchase(models.Model): … -
Passing in context variables to form
I want to pass in the parent_username variable in the below view function to the LevelTestModelForm, so that I could fill in one of the form inputs as that variable automatically. Here is the view: def LevelTestView(request, pk): parent_username = User.objects.get(pk=pk).username form = LevelTestModelForm() if request.method == "POST": form = LevelTestModelForm(request.POST) if form.is_valid(): form.save() return reverse("profile-page") context = { "form": form } return render(request, "leads/leveltest.html", context) I hope you guys could help. Thanks a lot. -
How to Optimize queries inside for loop in Django
I have a legacy code of application on which I am working. I installed Django debug toolbar and noticed nearly 1600 queries being executed on a single page of the application on a single request. After observing the trace of Django debug toolbar I noticed that the view function has nested queries inside for loop which calls model method. And further model method has another for loop inside first for loop calling another model method. Now after reading about django query optimization on the internet I learnt that this is very bad practice. But after spending 2 days on it I am not able to figure out how to optimize it. I am not able to figure out any alternate method with which I can replace that for loop with a query which brings all the data in one query. Below I am posting the Models, respective model methods and views which are being called. views.py def course_modules(request, course_id, msg=None): user = request.user course = Course.objects.get(id=course_id) learning_modules = course.get_learning_modules() context = {"course": course, "user": user, "msg": msg} course_status = CourseStatus.objects.filter( course=course, user=user ) context['course_percentage'] = course_status.first().percent_completed context['modules'] = [ (module, module.get_module_complete_percent(course, user)) for module in learning_modules ] if course_status: course_status … -
change django_migrations schema
Is there any way to change the schema for the django_migrations table? I want to move all Django related tables to another schema named django, I already used Database routers class DjangoAppRouter: route_app_labels = {'auth', 'contenttypes', 'admin'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'django' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'django' return None def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'django' return None class PrimaryRouter: def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ENV('DB_NAME'), 'USER': ENV('DB_USER'), 'PASSWORD': ENV('DB_PASS'), 'HOST': ENV('DB_HOST'), 'PORT': ENV.int('DB_PORT'), }, 'django': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=django' }, 'NAME': ENV('DB_NAME'), 'USER': ENV('DB_USER'), 'PASSWORD': ENV('DB_PASS'), 'HOST': ENV('DB_HOST'), 'PORT': ENV.int('DB_PORT'), } } DATABASE_ROUTERS = ['bilikStudio.db-router.DjangoAppRouter', 'bilikStudio.db-router.PrimaryRouter'] but this is not working for django_migrations. any suggestions? -
Settting up templates directory error (Django)
Whenever I run python manage.py runserver I get: Below are the relevant parts of my Settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) --------- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], '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 = 'mysite.wsgi.application' I would appreciate it if someone could help as I am confused as to why such simple things are not working for me! -
Django Form. View form with models of logged user
I'm doing simple to do app in django. I wan't user to have possibility to add borads and task (task is specified for board). When user is adding task (form created with ModelForm ) there is posibility to choose from diferent boards but the form is showing all boards - for all users. I want it to show only boards of currently logged user. How can I do this? Would appreciate some help. models.py: class Board(models.Model): board_name = models.CharField(max_length=50) day = models.DateTimeField(default=timezone.now) board_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.board_name class Task(models.Model): task_name = models.CharField(max_length=100) done = models.BooleanField(default=False) not_done = models.BooleanField(default=False) task_board = models.ForeignKey(Board, on_delete=models.CASCADE) def __str__(self): return self.task_name forms.py: class TaskForm(forms.ModelForm): class Meta: model = Task user = User.objects.get(username='admin') fields = ['task_name', 'task_board'] views.py def add_task(request): if Board.objects.filter(board_user=request.user).exists(): form = TaskForm(request.POST) # problem nadal nierozwiązany if request.method == "POST": form.instance.task_board.user = request.user if form.is_valid: form.save() return redirect('tasks-view') else: return redirect('tasks-view') return render(request, 'todo/task_form.html', {'form': form}) -
Django - Use annotation in query - Related Field got invalid lookup
In my manager, I've overriden get_queryset to annotate sqft_annotated value. class RealestateManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( sqft_annotated=Coalesce('sqft_a', 'sqft_b', 'sqft_c') I use this value frequently but now, in this query, it raises error (probably because it isn't annotated): _a = Q(realestates__home_type__in=[constants.HOME_TYPES.HOME_TYPE__SINGLE_FAMILY, constants.HOME_TYPES.HOME_TYPE__FARM], realestates__sqft_annotated__gte=1100, ...) _b = Q(<QUERY>) _c = Q(<QUERY>) leads_query = Q(Q(_a | _b) | ~_c) Category.objects.annotate(lead_count=Count('realestates', filter=leads_query)).annotate( lead_perc=Case(When(lead_count=0, then=0), default=(Count( 'realestates', filter=leads_query) / float(total)) * 100)) ERROR Related Field got invalid lookup: sqft_annotated Can I somehow use the sqft_annotated in such query? PS: Tried to set base_manager_name in class Meta - didn't help. -
how to show djago validation error message in html template?
I set max_length limit for my every form filed. I want when any user exceed max length limit then contact-form will not be submitted and showing an error message. such as if any user forget to fill name filed then it will show name is required or if it exceed max length limit then it will show "maximum 300 character allowed". here is my code: #forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=300) email = forms.EmailField(max_length=300) subject = forms.CharField(max_length=1000) message = forms.CharField(max_length=3000) #models.py from django.db import models from django.utils import timezone # Create your models here. class Contact(models.Model): current_time = models.DateTimeField(blank=True, null=True,default=timezone.now) name =models.CharField(max_length=300) subject =models.CharField(max_length=1000, default="") email =models.EmailField(max_length=300) message = models.TextField(max_length=3000) views.py @csrf_exempt def home_view(request,*args,**kwargs): if request.method == "POST": contacts = ContactForm(request.POST) if contacts.is_valid(): name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] post = Contact(name=name,email=email,subject=subject,message=message) post.save() context= {'message_name':name} return render(request, 'index.html',context) else: print('not submittd') fm = ContactForm() context= {'form':fm} return render(request, 'index.html',context) here is html code of my contact from: <section class="contact section" id="contact"> <h2 class="section-title">Contact</h2> {% if message_name %} <div class="centerTest"> <h1> Thanks {{ message_name }} for your message. We will get back to you very soon</h1> </div> {% else %} <div … -
How do i raise a validation error on django parent form with child formsets?
I have a Django form with 6 formsets. I want to check if a condition exists and if it does then raise a validation error for the overall form. I know how to raise errors for each of those 6 formsets but I can't figure out how to do it for the master/parent form. The master/parent form contains no fields. Any pointers in the right direction would be much appreciated. -
Heroku: properly set up procfile to run scraper on a daily basis
I just deployed my first app Django app and have it set up on a Hobby dyno via Heroku. One main part of the app is that it runs a webscraper via a management command on a (semi)daily basis which scrapes roughly 160K records and puts them into a Heroku database. Once the data is scraped the app is pretty static, but I am still noticing some instances where it loads quite slowly. My question is, since I am quite new to Heroku or hosting any live app, what is the best way to set this job up to be sure I am using worker dynos to execute it? I tried to read Heroku docs on background jobs etc but it didn't really help me too much. I am honestly not even sure if my Procfile is set up properly to use worker dynos to run my scraper, or it's being run on the web one? The basic structure of my app is as follows; all of the code set up to run the scraper via a management command is held in the scraper app. Project - scraperapp - homepage - otherapps - settings - VENV - Procfile - requirements.txt … -
How to build filter class using django-filter that allows to query by multiple values of one model field
I have to build endpoint that must allow to filter by multiple values. It must looks like this: http://example.com/page?field=1&field=2&filed=3 and allow to execute such or similiar query + validate the list MyModel.objects.filter(field__in=[1,2,3]) django-filter(https://django-filter.readthedocs.io/en/stable/) library looks promising but in the documentation I have not found an easy way to do something so simple. How can I achieve this? -
Django Multiple Image Upload Using form
This can upload single image. But i want to upload multiple image like insta do. In instagram multiple images are stored in a slider. I don't understand files = request.FILES.getlist('image') how can i iterate this this list Views.py file @login_required def index(request): images = Image.objects.all() users = User.objects.filter(is_superuser=False) prof = Profile.objects.get(user=request.user) actions = Action.objects.exclude(user=request.user) following_ids = request.user.following.values_list('id', flat=True) if request.method == "POST": form = ImageCreateForm(request.POST, request.FILES) files = request.FILES.getlist('image') if form.is_valid(): description = form.cleaned_data["description"] image = form.cleaned_data["image"] new_item = form.save(commit=False) new_item.user = request.user new_item.save() create_action(request.user, 'Uploaded Image', new_item) messages.success(request, "Image Added Successfully") return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) if following_ids: # If user is following others, retrieve only their actions actions = actions.filter(user_id__in=following_ids) actions = actions.select_related('user', 'user__profile').prefetch_related('target')[:10] return render(request, "account/index.html", { 'section': 'index', 'images': images, 'prof': prof, 'actions': actions, 'users': users, 'form': form, }) forms.py file from django import forms from urllib import request from django.core.files.base import ContentFile from django.utils.text import slugify from .models import Image class ImageCreateForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Image fields = ('description',) def clean_url(self): image = self.cleaned_data['image'] valid_extensions = ['jpg', 'jpeg'] extension = image.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('The Given URL does not match valid image extensions.') return image … -
Django - adding another check to my login
I'm creating a single page application that uses Django's session authentication on the backend. Django is using django-allauth for everything authentication-related. I would like to add an additional step to my login where the user inputs a code and Django must verify that code too, other than password and username. How can i do that? Note that i'm using Django as an API, so i don't need to edit the form and add another field, i only need to add another check to the authentication backend, so something very easy: if the code is right, than proceed to check username and password too, else return an error. The problem is that i don't know where to add this check. I think i need to work on the authentication backend, but i'm stuck here. Here is an example of the login data that django receives: {'login': 'test', 'password': 'testPass12', 'testToken': '123abc'} So basically, other than checking login and password like it already does now, it should check if testToken is equal to a specific value. Here is the allauth authentication backend: class AuthenticationBackend(ModelBackend): def authenticate(self, request, **credentials): ret = None if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: ret = self._authenticate_by_email(**credentials) elif app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.USERNAME_EMAIL: … -
Django database data not showing in Templete
I have a class HardBook that inherits from Book: class Book(models.Model): title = models.CharField('Book Title', max_length=200) image = models.ImageField('Book Cover', upload_to='covers') description = models.CharField('Description', max_length= 350) class HardBook(Book): quantity = models.IntegerField('Quantity') I want to display the field data in a table, I want to show title, image and quantity. Everthing is displayed except quantity. {% for hardbook in hardbooks %} <tr> <td> <div class="cover-image" style="background-image:url({{hardbook.image.url}});"></div> </td> <td>{{hardbook.title}}</td> <td>{{hardbook.quantity}}</td> </tr> {% endfor %} -
dynamic form fields repeate the value of index[0]
'i have two table on different servers, both the table has same fields, i need to to compare the table in order to ensure that the data is synced and both the server has same data. in case of, mismatch will prepare a new table where i will endorsed the missing data. to clarify it further table1: emp_name , roll_no, (table on main server) table2: emp_name , roll_no. (table on standby server) i need output of the rcords that are in table1 but not in table2. and i will store the missing records in table3 like. missing_record_list: emp_name , roll_no. i will have almost 2 lakh records. i am writing this program in django. please reply with suitable solution. thanks