Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bulk create for models with foreign key
I have these two models: class Item(models.Model): item_id = models.CharField(max_length=10, primary_key=True) item_name = models.CharField(max_length=100) description = models.CharField(max_length=500) slug = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.item_name class Image(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) image_url = models.CharField(max_length=200) I have a lot of items, and each Item has some images assigned to it. To add items in the database, I do it through a bulk create: it = (Item( item_id = item['id'], item_name= item['title'], description = item['description'], slug = item['slug'], price = item['price']['amount'] ) for item in items ) while True: batch = list(islice(it, batch_size)) if not batch: break Item.objects.bulk_create(batch, batch_size) This works perfectly fine, ok. But I want to do the same with the images, since I have too many images to do it individually. For now I do it like this: for item in items: for image in item['images']: Item.objects.get(item_id = item['id']).image_set.create(image_url = image['urls']['big']) But this is too slow in uplaoding all the Images (it may take 30 minutes), so I want to upload in bulk like I do it with Item, but since Image model has Item as a foreign key, I cannot do it the same way. How can I upload Images in a more efficient manner? I … -
Where to store media file of Django on production?
So I am learning Django. And I have made some websites with it. Now I am hosting those to Heroku. I am using free Dyno on Heroku. Also, I am using supabase.io database instead of Heroku's because supabase gives more space for the database on the free tier. Now the problem I am facing is with the media files. I can not access them on Heroku since I don't have any place to store them. I have seen some addons on Heroku for the file storage but to use those I need to provide my credit card information, which I do not have. But I have seen an object storage option on supabase.io. It gives 1 GB free storage which is more than enough for me now. But I don't know how can I use it with my Django application. That is why I am looking for help. Also if there are any free alternatives to store my media file without credit card information, please feel free to guide me. Since I do not own any card. -
How to fix "Failed to restart gunicorn.service: Unit gunicorn.socket not found." error?
I'm trying to deploy a django application to a DigitalOcean droplet. I created a systemd service to start gunicorn on boot. Here is my config file: (/etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data Environment="DJANGO_SETTINGS_MODULE=core.settings.production" WorkingDirectory=/home/myproject-api/src ExecStart=/home/myproject-api/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock core.wsgi:application [Install] WantedBy=multi-user.target When I run "ExecStart" line on directly on terminal, it works. But I cant start the gunicorn service. I get this error when I try to start gunicorn: Failed to start gunicorn.service: Unit gunicorn.socket not found. I checked the gunicorn executable, it exists: test -f /home/myproject-api/env/bin/gunicorn && echo "Gunicorn exists." I'm able to run server with gunicorn --bind 0.0.0.0:8000 core.wsgicommand. When I run like this, i can access the server using the server's IP address. Normally, the socket file should been created when I start the server. Also I tried to create the socket file with "touch /run/gunicorn.sock" but it didn't work. I double-checked file and directory names. No mistake. How can I solve this problem? -
how to login a user with email or username in django custom user model
This is my current code can anyone please add the required code to allow a user to login with email or username backends.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend, UserModel class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field: username}) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user -
Cannot switch EMAIL_BACKEND to smtp.EmailBackend
I have a weird problem although my settings.py file specifically says EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" my Django app still uses django.core.mail.backends.console.EmailBackend, how can that be? No matter if I have debug True or False # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" DEFAULT_FROM_EMAIL = "yes@gmail.com" SERVER_EMAIL = "yes@gmail.com" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "yes@gmail.com" EMAIL_HOST_PASSWORD = "yes" EMAIL_USE_TLS = True EMAIL_USE_SSL = False -
ModuleNotFoundError: No module named 'fontawesomefree'
I am getting this error when I try to import fonrawesomefree icons to my django project. I used official django docs requirements.txt file have following # some other requirements fontawesomefree==5.15.4 settings.py have following: INSTALLED_APPS = [ # some other installed apps 'fontawesomefree', ] base.html file have following <head> #some other link & script files <link href="{% static 'fontawesomefree/css/all.min.css' %}" rel="stylesheet" type="text/css"> </head> Project structure [projectname]/ ├── [projectname]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py | |── [App1] |── [static]/ | ├── [css] | ├── [Javascript] | └── [Images] | |── [templates] |── manage.py └── requirements.txt When I try to run server I get following error: ModuleNotFoundError: No module named 'fontawesomefree' Any help is appreciated -
how to use an authentication api in frontend part django
I implemented a login and register API that I want to use in frontend part of the project. I could use some clarifications about the mechanism of using an API for login and register request so I can understand what is wrong. here is my code : user_registration.html {% extends 'core/base.html' %} {% block head_title %}Banking System{% endblock %} {% block content %} <h1 class="font-mono font-bold text-3xl text-center pb-5 pt-10">Register</h1> <hr /> <div class="w-full mt-10"> <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {% csrf_token %} <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> First Name </label> <input name="firstname" type="text" placeholder="Your first Name" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 'rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"> </div> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> Last Name </label> <input name="lastname" type="text" placeholder="Your last Name" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 'rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2"> Email </label> <input name="email" type="text" placeholder="user@example.com" class="appearance-none block w-full bg-gray-200 text-gray-700 border … -
Pass dynamic choice list to form from Views in class based views
I just want to pass a list which will look like this from views to form , FYI i'm using MultipleChoiceField [('ad7d4d7c5fbd4678bafd9f2b93fdd4b5', 'Chandrayaan'), ('b55d7c02c29d4501b8d3f63053fef470', 'MOM'), ('b90a66ea9eb24d019102fadde900fdda', 'Galactica')] i have another issue related to this question as well which i have posted already here -
user sending an input form to another user in the platform - django
in my app I want that if userA selected a userB he can send him an input form that contain fields. those users have a class profile. I don't know what should I do in my views. do someone have any idea or already worked on this before. I really need your help in this -
Postgres: sanitize string before searchin for it
I have a website which uses Postgres as a database. I now want users to be able to search the database for strings and am using pg_trgm for that. I can imagine that it is very dangerous to just search the database for the plain user input, as it could be malicious. So my question is: what security measures do I have to take in order to search for a string in Postgres, which could potentially contain malicious code? Are there for example certain characters which should be escaped? Thanks in advance, Kingrimursel -
Decoupling auth/auth from Django applications
I author a couple of Django applications that I deploy behind an auth/auth system. Currently, my apps' class-based views are hard-coded with my particular auth requirements, by using DRF's authentication_classes and permission_classes and Django's permission_required decorator (and friends). The problem I have is that I can't really figure out any way to configure these on a project level. For example, while testing, I don't want to have to deal with my auth system--creating test users, logging in, etc. I just want to test my app. But even though I have a separate Django environment for production and development, there's no elegant way for me to, in my dev environment's settings.py, say (for example) MYAPP_AUTH_MODEL=None and in my prod environment, say something like MYAPP_AUTH_MODEL=permission_required('myperm_create'). As another example, how could I give consumers of my app complete control over how they secure their deployment, including allowing them to choose not to secure it at all? How does one write a Django app that can be secured with auth/auth, without writing anything into the app that places restrictions on how it's secured in any given deployment? -
Migrating Django from 2.2 to 3.2
I am migrating my application in Django 2.2 to version 3.2 and when passing the tests it gives me the following error that seems native to the framework. The application works perfectly, but the tests stopped working. python manage.py test --keepdb Using existing test database for alias 'default'... Traceback (most recent call last): File "/home/proyecto/src/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/home/proyecto/env/lib/python3.6/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/proyecto/env/lib/python3.6/site-packages/django/test/runner.py", line 645, in setup_databases debug_sql=self.debug_sql, parallel=self.parallel, **kwargs File "/home/proyecto/env/lib/python3.6/site-packages/django/test/utils.py", line 183, in setup_databases serialize=connection.settings_dict['TEST'].get('SERIALIZE', True), File "/home/proyecto/env/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 79, in create_test_db run_syncdb=True, File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 246, in handle fake_initial=fake_initial, File "/home/proyecto/env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/proyecto/env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, … -
How can I insert a checkbox in my django Sign Up form?
This is my forms.py file class SignUpForm(UserCreationForm): email = forms.EmailField(widget= forms.EmailInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' I want to add a boolean checkbox on my signup form, but not quite getting there. Any help would be appreciated. -
django.core.exceptions.FieldError: Unsupported lookup 'exact' when run in apache2
I know, similar problems have been posted and discussed here and in other forums. Nonetheless, I was not able to get around the issue. The follwing code snipped from File "/data/django/jukeoroni/player/jukeoroni/juke_radio.py" works just fine in python manage.py runserver @property def last_played(self): try: return Channel.objects.get(last_played=True) except Channel.DoesNotExist: LOG.info('no last_played channel, returning None.') return None [09-12-2021 15:03:49] [INFO] [Dummy-10|2989487200] [player.jukeoroni.jukeoroni]: Button press detected on pin: 16 button: 0X00 (2), label: Play [09-12-2021 15:03:49] [INFO] [Dummy-10|2989487200] [player.jukeoroni.jukeoroni]: Media inserted: deathmetal (type <class 'player.models.Channel'>) However, the same code results in the titles error when run within apache2: [09-12-2021 15:00:32] [INFO] [Dummy-10|2843735072] [player.jukeoroni.jukeoroni]: Button press detected on pin: 16 button: 0X00 (2), label: Play Traceback (most recent call last): File "/data/django/jukeoroni/player/jukeoroni/jukeoroni.py", line 813, in _handle_button if self.radio.last_played is None: File "/data/django/jukeoroni/player/jukeoroni/juke_radio.py", line 126, in last_played return Channel.objects.get(last_played=True) File "/data/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 424, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 941, in filter return self._filter_or_exclude(False, args, kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/data/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1393, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/data/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1415, in _add_q … -
order_by("-date") not working correctly with paginator
SO i have more than 500 records and want organize them by date, it was pretty simple and it worked but when i used paginator to add pagination it all got messed up, there is no sense in this ordering right now can anyone help me understand what's happening and what i need to do in order to get my order_by() working. Here is a my view: if request.method == "GET": if request.session["store_year"] == "" and request.session["store_month"] == "": request.session["store_year"] = "" request.session["store_month"] = "" timelineData = Timeline_english.objects.all().order_by("-date") timeline_list = [] timeline_date_list = set() for val in timelineData: obj = { "id": val.id, "image": val.image, "text": val.text, "url": val.url.replace(" ", "-").lower(), "date": val.date } timeline_list.append(obj) timeline_date_list.add(str(val.date)[:4]) page = request.GET.get('page', 1) print("page", page) paginator = Paginator(timeline_list, 9) try: timeline_list = paginator.page(page) except PageNotAnInteger: timeline_list = paginator.page(1) except EmptyPage: timeline_list = paginator.page(paginator.num_pages) print(timeline_list) try: page_count = math.ceil(timelineData.count()/9) page_limit = 3 page_count_arr = [] if page_count > page_limit: new_pagecount = int(page)+page_limit else: new_pagecount = page_count last_page_number = { "mode": "yes" if page_count == int(page) else "no", "index": page_count } if page_count > int(page): for i in range(int(page), new_pagecount+1): page_count_arr.append({ "mode": "yes" if i == int(page) else "no", "index": i }) data.update({"quotes_list_pages": page_count_arr}) else: … -
Django Leaflet Ajax
How to list and map located data: At one point In an interval In a rectangle In a circle of rayoun R thank you so much -
Translating django tables2 template column header
Hi i'm working with django-tables2 and I have a table where I need to translate the headers of each column. class ModelTable(tables.Table): name = tables.columns.Column() edit = tables.TemplateColumn('<a href='{% url "edit_my_model_instance" record.id %}'>Edit</a>', verbose_name=u'Edit', ) delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=u'Delete', ) class Meta: model = models.Model The above code without translations work fine, but when I add the gettext for translate like this : delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=_(u'Delete'), ) Where I added gettext as _ : verbose_name=_(u'Delete') I receive the following error TypeError: 'TemplateColumn' object is not callable The thing is if I use tables.Column it works fine with translation, so the problem is only when I user TemplateColumn. If you can guide me through this I'd appreciate it, thanks. -
Django Rest Framework Swagger API expand_all fields not working
I have a REST API described with Swagger. When I try to expand some fields, I get a valid JSON response (Response 200). However, when I try to expand all fields, I get no response (Response 500) I compared the logs when I expanded some fields vs when I expanded all fields. Below are some excerpts of logs from generics.py In generics.py,in function paginate_queryset, self.paginator= <rest_framework.pagination.PageNumberPagination object at 0x7fa32f2d01d0> In generics.py,in function paginate_queryset, self.paginator is NOT None In generics.py,in function paginator, self.pagination_class = <class 'rest_framework.pagination.PageNumberPagination'> . self._paginator= <rest_framework.pagination.PageNumberPagination object at 0x7fa32f2d01d0> In generics.py,in function paginator, self._paginator.django_paginator_class= <class 'django.core.paginator.Paginator'> . page_size = 10 . page_query_param = page . page_size_query_param= None . max_page_size= None . template = rest_framework/pagination/numbers.html, *************BELOW LINES ARE DISPLAYED ONLY WHEN I EXPAND SOME FIELDS & ARE NOT DISPLAYED WHEN I EXPAND ALL***************** In generics.py,in function paginate_queryset, self.request= <rest_framework.request.Request object at 0x7fa32f2d0b70> .return = [<Exon: Exon object (1)>, <Exon: Exon object (2)>, <Exon: Exon object (3)>, <Exon: Exon object (4)>, <Exon: Exon object (5)>, <Exon: Exon object (7)>, <Exon: Exon object (8)>, <Exon: Exon object (9)>, <Exon: Exon object (10)>, <Exon: Exon object (11)>], What could be the issue that prevents the paginate_queryset from being called, when I expand … -
getting null value when posting data to django using ajax
Am trynig to post data from an input to my django view to do some processing on this data ,which is a text, and am using AJAX but I get the input NULL in my view $(document).on('submit', '#post-form',function(e){ $.ajax({ type:'POST', url:'{% url "index" %}', data:{ inp:$('#qst').val() csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, dataType: 'json', success:function(json){ document.getElementById("post-form").reset(); $(".messages_area").append('<div class="messages__item messages__item--visitor">'+json.inp+'</div>') $(".messages_area").append('<div class="messages__item messages__item--operator">'+json.answer+'</div>') }, error : function(xhr,errmsg,err) { console.log(xhr.status + ":" + xhr.responseText); // provide a bit more info about the error to the console } }); }); And this is my view def chat(request): context={} inp="" response_data = {} if request.method == 'POST' and request.is_ajax: inp = request.POST.get('inp') answer=respond(inp) response_data['answer'] = answer response_data['inp'] = inp return JsonResponse(response_data) return render(request, 'templates/rhchatbot/index.html',context ) But when I print the inp value I get : {'inp':null} -
Why doesn't my 'home' page recognize 'object_list' in views?The specific template of CBV only does
I have a navbar template and I want to make it dynamic. When I want to do this in the template, nothing happens: {% for platform in object_list %} <li><a href="#">{{platform.title}}</a></li> {% endfor %} This code only works in the platform.html file but I want to show the navbar in all of my html files It is in platform.html(platform URL) and it should be like this And this one is in home url but it is an empty subnav this is my models from django.db import models # Create your models here. class Platform(models.Model): PLATFORM_CHOICES = ( ('PC', 'PC'), ('PS', 'playstation'), ('XBOX', 'Xbox'), ('NS', 'nintendo switch'), ) title = models.CharField(max_length=4, choices=PLATFORM_CHOICES, verbose_name= "platform") slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name = "platform" verbose_name_plural = "platforms" def __str__(self): return self.title class Game(models.Model): title = models.CharField(max_length=50) description = models.TextField() slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to="images") platform = models.ManyToManyField(Platform) class Meta: verbose_name = "game" verbose_name_plural = "games" def __str__(self): return self.title this is my views: from .models import Game, Platform from django.shortcuts import get_object_or_404, render from django.views.generic import ListView, DetailView, TemplateView # Create your views here. def home(request): return render(request, 'blog/home.html') class GameList(ListView): template_name = "blog/game.html" model = Game games = Game.objects.all() … -
Cookie is not setting from django app deployed on Heroku
I am building an app using React and Django. The backend is deployed on Heroku. When a user logs in, a JWT token is generated and a cookie is set on the client-side with the value of JWT token. When I run the django server on local machine, it works fine and the cookie is getting set. But when I use the server on Heroku, the cookie is not setting in the browser. What should be done to make the cookie work? Login View in views.py @api_view(['GET', 'POST']) def login(req): email = req.data.get('email') password = req.data.get('password') print(email, password) user = User.objects.filter(email=email).first() if user is None: #raise AuthenticationFailed('User not found') return Response({'message': 'Not Found'}) if not user.check_password(password): #raise AuthenticationFailed('Incorrect password') return Response({'message': 'Incorrect'}) payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') res = Response() res.set_cookie(key='jwt', value=token, httponly=True) res.data = { 'message': 'Logged In' } return res Settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' … -
Django KeyError: 'parent'
What i am trying to do is i try to check if the user has parent or not,then to authorize the serialization operation.But i get an error that says: value = self.validate(value) File "/root/server/accounts/serializers.py", line 715, in validate if (attrs['parent'] == None) and (attrs['id'] == self.context['request'].user.pk): KeyError: 'parent' Models.py class MyModel(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name =models.CharField(max_length=40,unique=True,default='name') parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) Serializers.py class ModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('id','name','password','parent') def validate(self, attrs): attrs = super().validate(attrs) if (attrs['parent'] == None) and (attrs['id'] == self.context['request'].user.pk): return attrs elif (attrs['parent'].id != self.context['request'].user.pk) and (attrs['parent'] != None): raise ValidationError('Unauthorized Request') return attrs Does anybody know the issue of the problem? -
Results from dynamic search bar not showing up on my page?
So, I'm making a dynamic search bar and everything works as it's supposed to (getting the results from Django, converting it to JSON, JS receives the JSON, etc.), except the conversion of the results to HTML on the page. I'm not sure what I'm supposed to do to have the results actually show on the web page and not just on the console anymore? Code: <form class="d-flex" method="POST"> {% csrf_token %} <input class="form-control me-2" type="search" id='search' placeholder="Search for books via their titles" aria-label="Search" > <div id="results" style="display: none;"> </div> </form> document.addEventListener("DOMContentLoaded", () => { // TODO: Implement Search Mechanic const search = document.querySelector("#search"); if (search !== null) { search.onkeyup = () => { console.log(search.value); get_results(search.value); }; } }); function get_results(query) { //TODO Create API to get results if (query === null) { return [] } if (query !== "") { fetch(`/results/${query}`) .then(response => response.json()) .then(result => { console.log(result); const display_div = document.querySelector("#results"); display_div.style.display = "block"; result.forEach(query => { console.log(query); const par = document.createElement("par"); const a = document.createElement("a"); a.classList.add = "links"; a.textContent = query.name; a.href = "#"; par.appendChild(a); display_div.appendChild(par); }); }); } } @login_required def results(request, query): if request.method == "GET": if query is not None: results = Search(query).get_results() print(results) JsonResponse({"message": … -
How to resend verification email django restframework?
I can send a verification email upon registering the user so that the account can be activated. But how would one go about resending another verification email on an API? Here, I am making an activation link with a token in it and when the user opens the link it takes the token and verifies the user. But how would resending the verification email work? class RegisterUser(APIView): serialzer_class = RegisterSerialzer def post(self, request): user = request.data serializer = self.serialzer_class(data = user) serializer.is_valid(raise_exception = True) serializer.save() user_data = serializer.data # user = User.objects.get(username=serializer.data['username']) # print(user.id) # token = Token.objects.create(user=user) user = User.objects.get(email = user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+ user.username + 'user the link below to verify your email \n' + absurl data = {'email_body':email_body,'to_email':user.email, 'email_subject':'Verify your email'} Util.send_email(data) class VerifyEmail(APIView): def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) user.is_verified = True # user.is_authenticated = True user.is_active = True # if not user.is_verified: user.save() return Response({'email':'successfuly activated'}, status=status.HTTP_200_OK) # except jwt.ExpiredSignatureError as identifier: except jwt.ExpiredSignatureError: return Response({'error':'Activation Expired expired'}, status=status.HTTP_400_BAD_REQUEST) # except jwt.exceptions.DecodeError as identifier: except jwt.exceptions.DecodeError: return Response({'error':'invalid token'}, status=status.HTTP_400_BAD_REQUEST) -
I can't figure out what to write in HTML?
Help write html code to display video posts on the site I am new to Django I don't know what to write in HTML to display the post I added in django-admin Tried adding a form and this way to add the post didn't work I would be glad to get any help