Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Bootstrap 4 popover dynamically in Django?
I have a simple Django app similar to a quiz app. I have stored all the questions with answers in the database. Then, I retrieve all the questions in a template using Django ListView. Each question has 4 options and one answer field. Initially, I want to hide the answer and use a Bootstrap 4 popover. When a user click on the popover button the answer will display. I have done all but the popover is not showing the answer when I click the button. Below is my code - <div class="col-md-12 card border-0 mb-2 mt-3 ml-1"> <div class="card-body pl-0 pt-3"> {% for topic in topic_list %} <h2 class="mt-0 mb-0">{{ topic.name }}</h2> {% for question in topic.question_set.all %} <h6 class="mb-4">{{ question.serial_no }}. {{ question.name }}</h6> <div class="form-check ml-3"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(A) {{ question.option1 | safe }} </label> </div> <div class="form-check ml-3"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(B) {{ question.option2 | safe }} </label> </div> <div class="form-check ml-3"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(C) {{ question.option3 | safe }} </label> </div> <div class="form-check ml-3 mb-4"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optradio">(D) {{ question.option4 | safe }} </label> </div> <button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="right" data-content="{{ question.answer }}"> … -
Django multiple file upload via modelform and manytomany field outputting file contents instead of uploading
I'm trying to setup a single field in a model that allows multiple file to be uploaded, using a ModelForm. I've been googling this for the last few hours and it seems a manytomany field is the preferred approach. I'm testing it works with some teext files containing just a few characters. The output of form.errors gives something like "b'gggf'" is not a valid value. where one of the files I attempt to upload is b.txt, with gggf being the contents. I would like to know what is causing this and where I am going wrong. The relevant parts of my app are below: models.py: def filename_path(instance, filename): return os.path.join('new_applicant_documents/%s_%s/%s' % (instance.last_name, instance.first_name, filename)) class NewApplicant(models.Model): documents = models.ManyToManyField('NewApplicantDocument') class NewApplicantDocument(models.Model): documents = models.FileField(upload_to=filename_path) forms.py: class NewApplicantForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewApplicantForm, self).__init__(*args, **kwargs) class Meta: model = NewApplicant fields = ['documents'] widgets = {'documents': forms.ClearableFileInput(attrs={'multiple': True}),} views.py: def newapplicant(request): form = NewApplicantForm() if request.method == "POST": form = NewApplicantForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() return render(request, 'newapp/thankyou.html', {}) else: form = NewApplicantForm() return render(request, 'newapp/appform.html', {'form': form}) My form is defined with enctype="multipart/form-data" and works fine when uploading individual files (prior to implement the manytomany field). -
User Login API Does not work! Django the code always show "Email or Password Invalid" message
Where is the error I will show you serializers.py and views.py It is not a syntax error But I think something went wrong in the code! In serializers.py class UserLogin(serializers.ModelSerializer): email=serializers.EmailField(max_length=50, required=True) password=serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ('email','password') def validate(self,data): email=data.get('email') password=data.get('password') if email and password: auth=authenticate(email=email, password=password) if auth: return auth else: raise exceptions.ValidationError('Email or Password Invalid') else: raise exceptions.ValidationError('fill all the fields') In views.py class LoginView(APIView): def post(self, request, format='json'): serializer = UserLogin(data=request.data) serializer.is_valid(raise_exception=True) objectuser = serializer.validated_data token, _ = Token.objects.get_or_create(user=objectuser) return Response(token.key, headers={"Access-Control-Allow-Origin": "*"}) -
Array input in html
Can I use Input of html to access array elements with single input box.[views.py][1] -
It is a python Django project can't able to place order in checkout form
ValueError Incorrect AES key length Request method: post Exception type:value error GetMethod is not intialized -
VScode debugger with docker-compose
Recently i have started using docker for my project running with the following Django Nginx Gunicorn Celery Postgres Redis Earlier it was easy to setup debugger but after using docker-compose i am not able to do that. As soon as i start the debugger it loads for sometime and then automatically stops with no logs or error anywhere. Here are the relevant code. launch.json { "configurations": [ { "name": "Python: Remote Attach", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 443 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ] } ] } docker-compose.yml version: '3' services: db: image: postgres:12 env_file: .env environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} ports: - "5431:5432" volumes: - dbdata:/var/lib/postgresql/data nginx: image: nginx:1.14 ports: - "443:443" - "80:80" volumes: - ./config/nginx/:/etc/nginx/conf.d - ./myapp/static:/var/www/myapp.me/static/ web: restart: always build: ./myapp command: bash -c " python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate && gunicorn --certfile=/etc/certs/localhost.crt --keyfile=/etc/certs/localhost.key myapp.wsgi:application --bind 0.0.0.0:443 --reload" expose: - "443" depends_on: - db - nginx env_file: - .env volumes: - ./myapp:/opt/myapp - ./config/nginx/certs/:/etc/certs - ./myapp/static:/var/www/myapp.me/static/ broker: image: redis:alpine expose: - "6379" celery: build: ./myapp command: celery -A myapp worker -l info env_file: - .env volumes: - ./myapp:/opt/myapp depends_on: … -
How to connect two django model query sets
When a list of strings(representing tags) are sent to a function, it retrieves tags that are in DB and also crates tags that are not found in db. I need to then combine those two into one queryset and return but when I tried to connect the two querysets by using +, it raises error. How can I connect two querysets? # Separate one in DB and not in DB tags_found_in_db = Tag.objects.filter(name__in = tag_strings) name_of_tags_found_in_db = [tag.name for tag in tags_found_in_db] tags_not_in_db = list(set(tag_strings) - set(name_of_tags_found_in_db)) # Bulk Create tags_to_be_created = [] for new_tag_name in tags_not_in_db: tags_to_be_created.append( Tag(name = new_tag_name) ) new_tags = Tag.objects.bulk_create( tags_to_be_created ) # > TypeError: can only concatenate list (not "QuerySet") to list return new_tags + tags_found_in_db -
PostgresSQL full text search query from long text
I am using PostgreSQL full text search in my django+postgresql app. I have a crawler which crawls a bunch of websites and stores the body text of the crawled webpages in a column in the database. User input is a long piece of text and I want to figure out if it is about the same topic/subject as any of the webpages. Can you suggest an optimal way to build the search query from a long piece of text for postgres full text search? -
How to link django custom user model and django allauth package
I have a custom user model in django made using AbstractUser. I am using the django allauth package for my authentication. I have made custom fields in both but am unable to link both of them. models.py from django.db import models from django.conf import settings from django.shortcuts import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser class User(AbstractUser): age = models.CharField(max_length=30, blank=True) phone = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=30,blank=True) gender = models.CharField(max_length=30,blank=True) forms.py from allauth.account.forms import SignupForm from django.contrib.auth import get_user_model from .models import User class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') age = forms.CharField(max_length=30, label='Age') phone = forms.CharField(max_length=30, label='Phone Number') address = forms.CharField(max_length=30, label='Address') gender = forms.CharField(max_length=30,label = 'Gender') print('FN',first_name) print('Age',age) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.age = self.cleaned_data['age'] user.phone = self.cleaned_data['phone'] user.address = self.cleaned_data['address'] user.gender = self.cleaned_data['gender'] user.save() return user I have defined a customUserAdmin admin.py from django.contrib import admin from .models import Medicine,Order,OrderItem,Pharmacy,Address from django.contrib.auth.admin import UserAdmin from .models import User from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model class CustomUserAdmin(UserAdmin): """Define admin model for custom User model with no username field.""" fieldsets = ( (None, … -
Django ORM Model saving
when I'm trying to interact with SQlite model I created I cant save the models using .save it is prompting that <fuction Model.save at (some hex address)> where in tutorial there is no such prompt command can any one help me rectify it -
Getting django.db.utils.IntegrityError: duplicate key value violates unique constraint But value does not exists
I was trying to get some object from DB using Django ORM. Medicine.objects.get(unique_item_id=26775) But while fetching I was caught up with Error -> item_medicine.models.DoesNotExist: Medicine matching query does not exist. Then I tried Inserting the same using Django ORM. Medicine.objects.create(unique_item_id=26775) But again I am getting error psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "item_medicine_medicine_unique_item_id_key" DETAIL: Key (unique_item_id)=(26775) already exists. In my models I have added unique=True for unique_item_id field. I don't know why is this happening. I tried answers given on similar posts But nothing worked. Traceback: Traceback (most recent call last): File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "item_medicine_medicine_unique_item_id_key" DETAIL: Key (unique_item_id)=(26775) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-46fdec6a582b>", line 1, in <module> Medicine.objects.create(unique_item_id=26775) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/home/rohit/Projects/medicine/item_medicine/models.py", line 58, in save super(Medicine, self).save(*args, **kwargs) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/base.py", line 924, in … -
ProgrammingError at /catalog/
So I'm trying to open my Heroku app website. After pushing the files from a git repository to my git heroku repository, I open the website and get this error message. Environment: Request Method: GET Request URL: http://chimpbooks.herokuapp.com/catalog/ Django Version: 3.1.2 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog.apps.CatalogConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "catalog_book" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "catalog_book" ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/catalog/views.py", line 11, in index num_books = Book.objects.all().count() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 411, in count return self.query.get_count(using=self.db) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/query.py", line 515, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/query.py", line 500, in get_aggregation result = compiler.execute_sql(SINGLE) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", … -
Reverse for ' ' with arguments '('',)' not found. 1 pattern(s) tried
I'm getting this error anytime I click on this submit button on my listing page. I've looked through the typical places that this kind of error is triggered by but I can't see what I'm doing wrong here. Error: Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<id>[0-9]+)$'] and further down on the page, on the traceback this line is highlighted as below. For clarity, it is highlighting the 2nd return render in that view. auctions\views.py, line 229, in closeListing return render(request, "auctions/closeListing.html", { I know that in my views and urls I pass the argument of id but then on the template I pass the argument of listing.id but this has been working throughout my project for some reason but just not working here. I actually just tried to change all the arguments in views and urls to listing_id to match the listing.id in the template and this produced the exact same error so I'm really lost. views.py def closeListing(request, id): bids = Bid.objects.filter(bid_item_id=id).order_by('-bid_input') winner = Bid.objects.filter(bid_item_id=id).latest('bid_input').bidder.id winner_name = Bid.objects.filter(bid_item_id=id).latest('bid_input').bidder.username currentHighest = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] if request.method == "POST": if bids == 0: return render(request, "auctions/closeListing.html", { "bids": bids, "error": "No bids have been placed on your listing", … -
What is the best Way to run a CronJob in containerized django application with 2 or more Replicas
I am working on a project which is deployed on docker swarm as a service with 3 replicas. I want to run a simple management command to delete some rows from a table if the date has passed. I have written a django command for it, but want to make the run automated using cron job. I do want to make sure the Job is run only once a day from any of the container which is part of my service. On the internet I found some packages built for running cron jobs for Django application, but none of them considers more than one containers. Some packages have lock based approach but it were file based locks and not a shared lock. I did not want to celery for this simple task. Following is glimpse of my command: class Command(BaseCommand): """Command to clear user subscription if end_date has passed""" def handle(self, *args, **options): try: deleted_count, relative_deleted = MyModel.delete_inactive_instances() except Exception: raise CommandError('Could Not Remove Inactive Subscriptions From DB') else: self.stdout.write(self.style.SUCCESS('Successfully Removed Inactive Subscriptions %s ' % deleted_count)) I am currently running a command each day by docker exec: python manage.py delete_inactive_instances Following is my docker-stack file: services: production_app: image: {id}.dkr.ecr.{region}.amazonaws.com/xxxxxx:latest … -
How to sort table columns using button in Django
I'm building a website in django and I want to add button and drop down menu above the table. In drop down menu, there will be name of the columns and if i select one column and then click the button sort then table will be sort on basis of that columns. def index(request): slist = Stock.objects.all() paginator = Paginator(slist, 20) page = request.GET.get('page') slist = paginator.get_page(page) template = loader.get_template('stocks/screener.html') context = { 'slist': slist, } return HttpResponse(template.render(context, request)) What should i do?? -
Creating project manager system using django
I am creating a project manager system with using Django backend. But I am not sure what is the best approach to build a model for this. For example planning to establish a system structure like: class Organization(models.Model): user = models.ManyToManyField(User) organization_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organization_name = models.CharField(max_length=255) def __str__(self): return self.organization_name Organization Model creates a record when a new user created in Database and bind the user id to itself. class Role(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.name This model take the [read, edit] roles. class Project(models.Model): user = models.ForeignKey(User,on_delete=models.DO_NOTHING) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) project_name = models.CharField(max_length=255) def __str__(self): return self.project_name When a project created. It takes the users' organization. So the project can only seen by the users which participated with same organization. class ProjectParticipant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.user ProjectParticipant controls the which user read or edit the project. I am not sure this is the good approach to build a project manager system. If there are flaws, how can I fix those... -
SVG not rendering
My django project is storing images on AWS. https://race-hub.herokuapp.com/ All png and jpg files are rendering as expected but svg files are not. I've checked various threads on this including content-type to be used for uploading svg images to AWS S3 I've checked the file type is set to "image/svg+xml" on AWS and that the files exist and render fine in AWS. -
Generate PDF file in Django using xhtml2pdf
I tried to generate a PDF file based on the information that comes from client side. I fetched the data using request.POST. @csrf_exempt def create_pdf(request): if request.POST: context = {} data = json.loads(request.POST.get("users")) // I didn't use it. context["title"] = "AMIR" render_to_pdf( template_path="useres/users_template.html", context=context) return HttpResponse(response) and to render pdf file I've wrote the code down below: def render_to_pdf(template_path, context={}): # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response when I call render_to_pdf in create_pdf view It doesn't return pdf file! How do I should return it? -
django_filters, how do I query based on associated model?
My problem is like so, I am using django-tables2 and I want to list some people on my page but these people should go through some queries. These queries will change according to information from other models.if the query is ok, this person will be in my table. # My models class AgeGroup(models.Model): age_group = models.CharField(choices=age_choices, max_length=5) class SolvedExam(models.Model): age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='solved_exam_age_group') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='solved_exam') class Person(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person') age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='person_age_group') * * * class Exam(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person') age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='exam_age_group') * * * # my view class PersonList(SingleTableMixin, FilterView): table_class = PersonTable model = Person queryset = Person.objects.all() paginate_by = 10 template_name = 'person/person-list.html' filterset_class = PersonFilter def get_queryset(self): super(Ogrenciler, self).get_queryset() return Person.objects.filter( **some query** ) raise Http404 I want to list the students if there are exams which is not finished in the person's age group. Thank you very much! -
Pycharm Django Macos Catalina Zsh abort and file tracking disabled
I been moving some PyCharm projects to my new iMac, but with 1 of my project im having issues when I try to run my custom Django commands, witch do work properly in other projects. To give you an overview, this is happening: When I try to run the project in PyCharm (run server): Process finished with exit code 134 (interrupted by signal 6: SIGABRT) When I manual try to run a Django command, it does seem to see the command file but it returns: Process finished with exit code 134 (interrupted by signal 6: SIGABRT) When I copy the command and try to execute it myself: /Users/gerd2020/Documents/Projecten/werkblad/venv/bin/python /Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py testdit /Users/gerd2020/Documents/Projecten/werkblad File tracking disabled zsh: abort /Users/gerd2020/Documents/Projecten/werkblad/venv/bin/python testdit im confused , when I do a collect static that does seem to work. Any ideas where I got to look? -
Django: Why am I getting ValueError when referring to a ForeignKey using a varchar?
My application (called users) includes these two models: class RankingType(models.Model): type_code = models.CharField(max_length=16, unique=True) description = models.CharField(max_length=64) def __str__(self): return f'{self.description}' class RankingProfile(models.Model): user = models.ForeignKey( User, to_field='username', on_delete=models.PROTECT, related_name='ranking_profile_as_user', blank=False ) type_code = models.ForeignKey( RankingType, to_field='type_code', on_delete=models.PROTECT, related_name='ranking_profile_as_type', blank=False, default='btb_buyer' ) profile_name = models.CharField(max_length=64) price_weight = models.IntegerField(default=100) transhipment_weight = models.IntegerField(default=0) earliest_etd_weight = models.IntegerField(default=0) latest_eta_weight = models.IntegerField(default=0) def __str__(self): return f'{self.profile_name}' makemigrations and migrate work fine. I then run some code that loads the users_rankingtype table from a CSV and then users_rankingprofile from another CSV. The users_rankingtype table loads without problem, but when I try to run the code that loads the users_rankingprofile it fails on the first insertion with a ValueError: Cannot assign "'btb_buyer'": "RankingProfile.type_code" must be a "RankingType" instance. Here's the code that loads the table: file_in = path + 'users_rankingprofile.csv' count_rankingprofile = 0 with open(file_in) as csvfile: reader = csv.DictReader(csvfile) for row in reader: r = RankingProfile( profile_name=row['profile_name'], price_weight=row['price_weight'], transhipment_weight=row['transhipment_weight'], earliest_etd_weight=row['earliest_etd_weight'], type_code=row['type_code'], username=row['username'], latest_eta_weight=row['latest_eta_weight'], ) r.save() count_rankingprofile = count_rankingprofile + 1 I use PyCharm, and so I can inspect the RankingType table. The first row of the users_rankingtype table has btb_buyer in the type_code column is in the table. What am I doing wrong? Thanks and regards...Paul -
What is the best way to deploy a django app in 2020?
I have been looking for the best way to deploy my Django app I have been found some solutions and suggestions, but I'm still not sure which one is the best way. Many youtube videos suggest that the serverless solution such as 'Amazon Elastic or Google App Engine' is the best way. I would be very grateful if an experienced Django developer would share with me what is the best way to Deploy a Django application today. -
How to send value to filter in if condition django?
In my html, I want to send this values to my filter but I got this error : ValueError at / invalid literal for int() with base 10: '{{request.user.id}}' My HTML: <span><i{% if post|liked:"{{request.user.id}},{{post.id}}" %} class="fa fa-heart pointer" {% else %} class="fa fa-heart-o pointer" {% endif %} aria-hidden="true"></i> <span class="text-dark">{{ post.likes.count }}</span> My Filter: @register.filter() @stringfilter def liked(value, args): values = args.split(',') user_id, post_id = values user = User.objects.get(id=user_id) post = Post.objects.get(id=post_id) is_liked = post.likes.get(id=user_id) if is_liked != None: return True else: return False Thanks for any answer. -
ai want to separate products based on id stored in postgresql database in django tell me template syntax
i tried this {% for i in object %} {% if i.get(id=1) %} Rs {{i.price}} {% endif %} {% endfor %} but shows error like TemplateSyntaxError Could not parse the remainder: '(id=1)' from 'i.get(id=1)' -
How to test custom authentication backend in django
I wrote a custom authentication backend, I used it in my views to prove that it is working, however I would like to test it so in case it breaks in future for whatever reason, I would know. I think the problem may be because I have no request in the test, so no request is passed into the authenticate method. If this is the problem, then how can I pass a valid request into the authenticate method and test it so the test passes. In other words, can someone please show me a test that passes for the authentication backend below backends.py class EmailBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = User.objects.filter(email=email).first() if user.check_password(password): return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None test_backends.py class TestUserBackend(TestCase): def test_authenticate(self): user = UserFactory() authenticated_user = authenticate(email=user.email, password=user.password) self.assertEqual(authenticated_user, user) UserFactory() is from factory boy. I have also checked that user.password is hashed and the same as user.password which is also hashed. But I keep getting None != the user.email that was generated . Thanks for your help.