Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django API : Variable Filter (is null)
I'm working on my Django project, I have Django running as rest API and I want to filter value null based on a variable column that the user gonna choose. For filtering by equals I did something like that : field = fields[i] value = values[i] queryset = queryset.filter(**{field:value}) but if i leave value empty the query does not work . -
keep getting syntax error running manage.py
Just trying to set up my first django app on pythonanywhere eu region 13:29 ~/OP (master)$ ./manage.py makemigrations OP File "./manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax 13:29 ~/OP (master)$ -
clean() method in form not working (loading it into ListView)
I've tried searching around and reading the docs but I don't quite understand how to get the clean() method to work when dealing with ListView's, get_querysets() and get methods. I've tried adding in a breakpoint() in the clean() method and it doesn't get triggered meaning it's not called at all. My suspicion is because I'm not using post as the method in the form but I need to use get in order to build a filter query to a query set (namely, it's a date picker using from and to). This is my setup (omitting details): Form: class ReportForm(forms.Form): ... def clean(self): super().clean() ... return self.cleaned_data ListView: class ReportView(ListView): form_class = ReportForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = kwargs.get('form', self.form_class()) context['form'] = form return context def get_queryset(self): # Details omitted but I'm essentially taking data from the form # and using it to filter a QuerySet from_date = self.request.GET.get('from_date') to_date = self.request.GET.get('to_date') ....... return QuerySet Template: <form action="" method="get"> {% csrf_token %} {% crispy form %} </form> Does anyone know why my clean method isn't being called? -
Validated data is empty
I use Django REST Frameworke in my application. I want to create like for posts My api view: class LikePostAPIView(CreateAPIView): model = Like permission_classes = [ permissions.IsAuthenticated ] serializer_class = LikeCreateSerializer My LikeCreateSerializer: class LikeCreateSerializer(serializers.ModelSerializer): def create(self, validated_data): print(validated_data) class Meta: model = Like fields = ('post_id', ) I send JSON data: { "post_id": 1 } But i get 500 HTTP status because my validated_data is empty in serializer -
SessionAuthentication; 403 - "detail": "Authentication credentials were not provided."
I'm attempting to test a Rest Framework view for which a User must be authenticated. Upon requesting the API endpoint, Postman is returning a 403: "detail": "Authentication credentials were not provided." The Django test runner shows the User attached to the request and the test passes. However, if I comment out the IsAuthenticated permission in the view and I request the endpoint through Postman, it then returns an Anonymous User. I'm not sure how to resolve this discrepancy between Postman says and what Django says. How can I get the User authenticated via Postman? class TestQuestionDuplicateUpvote(APITestCase): '''Verify that a client is informed that they already voted on a question posted.''' @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('Mock', password="mocksecret") def test_user_upvote_posted_question(self): self.client.login(username="Mock", password="mocksecret") response = self.client.put( reverse("questions_api:vote", kwargs={"id": 1}), data = {'vote': 'upvote'} ) new_vote_tally = self.question.votes.count() self.assertEqual(response.status_code, 400) self.assertEqual(new_vote_tally, self.old_vote_tally) self.assertEqual(response.data['vote'][0], "You have already voted") class UserQuestionVoteView(APIView): renderer_classes = [JSONRenderer, ] parser_classes = [JSONParser, ] permission_classes = [IsAuthenticated, ] authentication_classes = [SessionAuthentication, TokenAuthentication] throttle_classes = [ScopedRateThrottle, ] throttle_scope = "voting" def put(self, request, id): import pdb; pdb.set_trace() account = UserAccount.objects.get(user=request.user) question = Question.objects.get(id=id) vote = request.data['vote'] try: stored_vote = QuestionVote.objects.get( vote=vote, account=account, question=question ) serializer = QuestionVoteSerializer(stored_vote, request.data) except QuestionVote.DoesNotExist: serializer … -
User Profile update with UpdateView with Django
I extended User with a profile. Signup and login works fine, but I have a problem to implement a UserPofile (User + Profile models). Form is rendered, but it's not stored. I'm out of ideas where to look now. What can be wrong? How to debug this? Views: class UserSettings(UpdateView): template_name = 'users/settings.html' context_object_name = 'user' model = UserProfile form_class = ProfileUpdateForm def get_success_url(self): return reverse('users:user-settings', kwargs={'pk': self.get_object().id}) def get_context_data(self, **kwargs): context = super(UserSettings, self).get_context_data(**kwargs) context['user_form'] = UserUpdateForm(instance=self.object.user) return context Model: from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(default='users/default_user.png', upload_to='users', blank=True, null=True) def post_user_created_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(post_user_created_signal, sender=User) Forms: class UserUpdateForm(UserChangeForm): class Meta: model = User fields = ['first_name', 'last_name'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = [ 'picture' ] -
How to get all the Students enrolled to a list of Specific Courses say (1 and 2) in a many to many relationship
I'm trying to get all the Students which are enrolled to a list of specific courses (Say Course 1 and Course 2). class Student(models.Model): name = models.CharField(max_length=50, verbose_name="Student name") courses = models.ManyToManyField(Course, related_name="course_name", blank=True) def __str__(self): return self.name class Course(models.Model): name = models.CharField(max_length=100, verbose_name="Course Name") def __str__(self): return self.name If I do: result = Student.objects.filter(courses__in=[1,2]) I get all the Students who are enrolled with either course 1 or course 2. I'm interested only in students who are enrolled in both courses. The below code works but I think it's not the best way to accomplish this: all_students = Student.objects.all() stud_id = [] for student in all_students: course_list = list(student.courses.values_list('pk', flat=True)) check = all(item in course_list for item in [1,2]) if check: stud_id.append(student.id) studs = Student.objects.filter(id__in=stud_id) The idea is to not loop over every student to find if they're enrolled to the given set of courses. -
FileNotFoundError: [Errno 2] No such file or directory: '/app/static'
I got this error when trying to host my django project on heroku FileNotFoundError: [Errno 2] No such file or directory: '/app/static' here is settings.py: STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' and this is the error : File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/app/static' -
API endpoint returns NoneType
I'm trying to code a read-only API with Django and I've done with Flask Restful too. However, I'm getting an error. The issue is that whenever I reload a page or request an endpoint multiple times, I receive nothing. null So, I thought it was related to Flask and I coded with Django too. However, I came across the same issue with Django Rest Framework. AssertionError at /api/v1/user/regular/users/ Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` And at this point, I think it is related to Firebase. So, is there any rule that I need to change in Firebase? Or a code piece I must add to my Django Rest Framework classes? -
Import data from excel spreadsheet to mysql database using django Rest Framework
Im biginner with django, and I want to send data from an excel file to my database using django Rest framework Views.py class MyFileView(APIView): def export(myfile): xls = pd.ExcelFile(myfile) df1 = pd.read_excel(xls) engine=create_engine("mysql+pymysql://root:@localhost:3307/test") df1.to_sql('table', con=engine, index=False, if_exists='append') parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = MyFileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() response=Response(file_serializer.data, status=status.HTTP_201_CREATED) return response else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Model.py from django.db import models class MyFile(models.Model): file = models.FileField(blank=False, null=False) uploaded_at = models.DateTimeField(auto_now_add=True) I wanna save the file that I receive in a the form of database table using export() function in view.py -
Join data from two models to single dict
I am trying to combine the two models. I want to display in one endpoint a list of cars that are available per user along with the last registered fuel level. Im looking for way to merge two models into single object. My models.py file: class CustomUser(AbstractUser): cars = models.ManyToManyField('Car', related_name='users_cars') class Car(models.Model): brand = models.CharField(max_length=64) model = models.CharField(max_length=64) plate_no = models.CharField(max_length=9) class FuelLevel(models.Model): car = models.ForeignKey('Car', on_delete=models.CASCADE()) level = models.IntegerField() timestamp = models.DateTimeField() views.py: class CarsStatusesList(APIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): token_user_id = self.request.auth.payload['user_id'] user = CustomUser.objects.filter(id=token_user_id).get() # Last levels for user cars levels = FuelLevel.objects\ .filter(car__in=user.cars.all())\ .order_by('car', '-timestamp')\ .distinct('car') cars = user.cars.all() # How to merge cars with lastest fuel level. something like this: result = cars JOIN levels ON " levels.car_id = cars._id " return JsonResponse(list(result.values()), safe=False) I want to get response like this: [{ "car_id": 31, "brand" : "Ford" "model" : "Focus" "plate_no" : "XDS 12342" "level" : "80" "timestamp" : "2021-05-06 12:22" }, "car_id": 4, "brand" : "Ford" "model" : "Mondeo" "plate_no" : "GYR 342" "level" : "20" "timestamp" : "2021-05-06 10:22" } ] -
Can i load static folder on my CSS file in django
In my CSS i need to load an image for the background of my page like this: style.css background: url("media/images/hero-bg.jpg") no-repeat center; But that wont work once i move it server i assume, would i be able to do like in a regular HTML file like this: index.html: {% load static %} <p data-aos="fade-right" data-aos-delay="200"><img class="mr-4" src="{% static 'images/slider1.png' %}" alt="404 not found"> My question is if i use the same syntax would it work fine or do i need to make adaptations to the code. -
Django admin: can't adapt type 'decimal.Decimal'
I'm getting the exception: "can't adapt type 'decimal.Decimal'" in Django Admin when saving the TestType model below I can't replicate the same issue on MacOs, Windows 10 and Linux (in my dev environment), but the issue occurs at the clients'. The problem starts randomly, but once it happens it doesn't stop even after a restart of the client machine I'm using the following setup: Python 3.9.5 Django 3.2.2 psycopg2 Postgres 12.6 Apache for Windows I'm using a simple Django model which used to work perfectly in Django admin. class TestType(SortableMixin): name = models.CharField(max_length=200) data_type = models.IntegerField(null=True, choices=[(datatype.value, datatype.name) for datatype in TestDataType]) min_value = models.DecimalField(decimal_places=2, max_digits=8, blank=True, null=True, default=None) max_value = models.DecimalField(decimal_places=2, max_digits=8, blank=True, null=True, default=None) test_template = models.ManyToManyField(TestTemplate, blank=True, default=None) and in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': db_name, 'USER': 'postgres', 'PASSWORD': db_password, 'HOST': 'localhost', 'PORT': '5432', } } Any clue on what might be the problem? -
If the entries in the model are made on the same date then the fields of this model must be summed up
I have a model class paidparking(models.Model): adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True, verbose_name='Адрес парковки') carnumber = models.CharField(max_length=150,verbose_name='Номер автомобиля') amountoftime = models.IntegerField(verbose_name='Количество времени') price = models.FloatField(verbose_name='Цена') telephone = models.CharField(max_length=20,verbose_name='Номер телефона') email = models.EmailField(verbose_name='Электронный адрес',null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True, verbose_name='Дата и время оплаты') expirationdate = models.DateField(null=True,verbose_name='Дата начала срока действия') expirationtime = models.TimeField(null=True,verbose_name='Время начала срока действия') enddateandtime = models.DateTimeField(null=True,blank=True,verbose_name='Окончание срока действия') There is a function startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y') enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y') paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate', 'price') In JS, I get this data and draw graphs $.ajax({ type: "POST", url: "date", data: { 'startdate': finalDateStrStart, 'enddate': finalDateStrEnd, }, dataType: "json", cache: false, success: function (data) { if (data.result) { var expirationdates = []; var prices = []; for (let i = 0; i < data.result.length; i++) { expirationdates.push(data.result[i].expirationdate); prices.push(data.result[i].price); } if(window.chart instanceof Chart) { window.chart.destroy(); } var ctx = document.getElementById("line").getContext("2d"); var chart = new Chart(ctx, { type: 'line', data: { labels: expirationdates, datasets: [{ label: 'Оплата парковочных пространств', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(144,204,244)', data: prices, }] }, options: { } }); var ctx = document.getElementById("bar").getContext("2d"); var chart = new Chart(ctx, { type: 'bar', data: { labels: expirationdates, datasets: [{ label: 'Оплата парковочных пространств', backgroundColor: 'rgb(144,204,244)', borderColor: 'rgb(255, 99, 132)', data: prices, }] … -
Filtering between two dates but with reverse logic
I am making a search that should be able to filter if a "musician" is free between two dates(start_date, end_date). A musician has a calendar which contains the dates of his shows. So when a user enters the two desired dates in which he wants to book the musician I am supposed to see if the musician does not have a show on at least one of the dates in the range between the two. I was using djagno filter and using .filter() and .exclude() i was able to filter but it excluded musicians that had just one show in the range so obviously it's wrong. I had this piece of code: def _filter_start_date_end_date(self, queryset): queryset = queryset.exclude(shows__performance_date__range=[self.filter_parameters['start_date'], self.filter_parameters['end_date']]) return queryset The queryset contains all the musicians in the database. Show model: class Show(models.Model): id = models.AutoField(primary_key=True) musician = models.ForeignKey(Musician, on_delete=models.CASCADE, related_name='shows') additional_musicians = models.CharField(max_length=200, blank=True, null=True) genres = models.ManyToManyField('Genres', blank=True) performance_date = models.DateField() performance_start = models.TimeField() performance_end = models.TimeField() I hope I asked the question correctly if more information is needed i will provide it. -
New to Django - showing detail object
in my Panel Folder I have the following /Project/Panel/templates/posts/post_detail.html I have created the class based view class PostDetailView(DetailView): model = Post when I go to http://127.0.0.1:8000/panel/posts/1/ I get this error "no such table: panel_post" I have also set the URLS path('panel/posts/', PostListView.as_view(), name='post-list'), path('panel/posts/<int:pk>/', PostDetailView.as_view(), name='post-detail'), what am I doing wrong ? -
Update Text of certain select field in Django-admin
I know there are already several threads on SO on how to customize selects. However still I'm not lucky. I have a Model: Bones class Bone(MPTTModel): section = models.CharField(max_length=255, choices=SECTIONS) name = models.CharField(max_length=255) parent = TreeForeignKey('self', null=True, blank=True, related_name='options', db_index=True, on_delete=models.CASCADE) ... This Model is used by another Model as a many to many field: class BoneChangeBoneProxy(models.Model): anomalies = models.ForeignKey('DiseaseLibrary', on_delete=models.CASCADE, related_name='anomalies') technic = models.ForeignKey('Technic', on_delete=models.CASCADE, related_name='technic_proxy') bone_change = models.ForeignKey('BoneChange', blank=True, null=True, on_delete=models.CASCADE, related_name='bone_change_proxy') # ↧↧↧ here ↧↧↧ bone = TreeManyToManyField('Bone', related_name='bone_proxy') The resulting select field renders each bone as an option with its name. How can I extend the rendered name with the section field in BoneChangeBoneProxy? (changing the __str__ of bones is not an option) This is what I've tried: Forms: from django import forms from .models import Bone class BoneAdminForm(forms.ModelForm): class Meta: model = Bone fields = "__all__" def clean_name(self): return f'{self.cleaned_data["name"]} ({self.cleaned_data["section"]})' admin.py class BoneChangeBoneProxy(admin.TabularInline): model = BoneChangeBoneProxy extra = 1 form = BoneAdminForm autocomplete_fields = ['technic', 'bone_change'] -
How complicated will be to migrate a web server implementation from Tornado to Django framework? [closed]
I am working on a fairly complicated (~ 120k lines of python code ) web server implemented using Tornado framework. As always, the folks who took the decision to use Tornado instead of any other framework, are no longer with the company, so we are now stuck, dealing with a lot of performance issue caused by the limitations coming with this framework, especially on CPU intensive operations. So I was thinking to move from Tornado to Django. Did anyone took this path? I wonder how complicated it can be to do this migration? Any concerns and/or suggestions on doing this ? Thanks -
Django call delete function with a button
I am trying to add a delete function to my project. so I can remove objects from the database without using the admin page. I'm getting this error when I try to render 'exercise_detail.html' Reverse for 'exercise_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['exercise/(?P[^/]+)/delete/$'] models.py from django.db import models class Exercise(models.Model): name = models.CharField(max_length=45, unique=True, primary_key=True) evolution = models.CharField(max_length=8, unique=True) startdate = models.DateTimeField() enddate = models.DateTimeField() logo = models.BinaryField() def __str__(self): return f"Exercise: {self.name}\t Evolution: {self.evolution}" views.py from django.shortcuts import get_object_or_404, render, redirect from django.http import HttpResponse from django.http import Http404 from django.template import loader from django.forms import ModelForm from .models import Exercise, Units from .forms import ExerciseForm def exercise_delete(request, name, *args, **kwargs): ex_del = Exercise.objects.get(Exercise, name=name) if request.method == "POST": ex_name.delete() return redirect('../') context = { 'ex_del': ex_del, } return render(request, 'landing.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.landing), path('newexercise/', views.new_exercise), path('newunit/', views.new_unit), # ex: unit/7th Comm/ path('unit/<str:short_name>/', views.unit_detail), # ex: exercise/Cobra Gold/ path('exercise/<str:name>/', views.exercise_detail), # edit exercise path('exercise/<str:name>/edit/', views.exercise_edit), # ex: delete exercise path('exercise/<str:name>/delete/', views.exercise_delete, name='exercise_delete'), ] exercise_details.html {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <nav class="navbar navbar-expand-lg navbar-light"> <h3>{{ ex_name.name }}</h3> <button class="navbar-toggler" type="button" … -
How to path CSS file in Django?
SETTINGS.PY>INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', 'shop', 'colorfield', ] STATC CODE STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '' MEDIA_ROOT = BASE_DIR HTML {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/base-style.css' %}"> When I access to this static file by just writing path after 'localserver:8000' is works but not working on html file. I am stuck for approximately 3 hours please help.... -
No module named importlib.util while deploying to heroku
I am deploying Django App to Heroku. Everything is working fine BUT when i push my code into heroku master using git push heroku master then it installed all the requirements BUT at the end it shows remote: cwd: /tmp/pip-install-eh43np6w/importlib/ remote: Complete output (11 lines): remote: Traceback (most recent call last): remote: File "", line 1, in remote: File "/app/.heroku/python/lib/python3.9/site-packages/setuptools/init.py", line 5, in remote: import distutils.core remote: File "/app/.heroku/python/lib/python3.9/distutils/core.py", line 16, in remote: from distutils.dist import Distribution remote: File "/app/.heroku/python/lib/python3.9/distutils/dist.py", line 19, in remote: from distutils.util import check_environ, strtobool, rfc822_escape remote: File "/app/.heroku/python/lib/python3.9/distutils/util.py", line 9, in remote: import importlib.util remote: ModuleNotFoundError: No module named 'importlib.util' AND THEN remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku :main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to nytictactoe. remote: To https://git.heroku.com/nytictactoe.git AND ALSO No Python version was specified. Using the buildpack default: python-3.9.5 I have tried many times BUT it keep showing this error. Any help would be Appreciated. Thank You in Advance. -
Django Bootstrap Date Picker default value / todayBtn problem
I created a Date Picker using Django and Bootstrap. When clicking on the calendar field on the right of the input field, however, the calendar jumps to a default of: 06/Fr/yyyy. I tried setting the todayBtn attribute to True but that produced an error. Example can be seen on the following image: My models.py: class TimeInterval(models.Model): time_interval = models.DateField() forms.py: from .models import TimeInterval from bootstrap_datepicker_plus import DatePickerInput class TimeIntervalForm(forms.ModelForm): date = forms.DateField( widget=DatePickerInput( options={ "format": "mm/dd/yyyy", # "todayHighlight": True, # "todayBtn": True, } ) ) class Meta: model = TimeInterval fields = '__all__' views.py: def datepicker_form_view(request): return render(request, "datepicker_form.html", { "time_interval_form": TimeIntervalForm(), }) And my HTML file: {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <form action="." method="POST">{% csrf_token %} {% bootstrap_form time_interval_form %} {{time_interval_form.media }} <input type="submit" value="Submit"> </form> I came across a similar question about the todayHighlight attribute but there the OP used JavaScript/jQuery, hence it was advised that he added that attribute using a jQuery select. I feel that in my case, expanding the HTML code with a <script> section and a jQuery selection just to have that one attribute working is an overkill - there must be a more convenient way to … -
Indexing issue in django-elasticsearch and to_queryset() not working
I am using django-elasticsearch-dsl library a high level client to interact with elasticsearch. This is my Document.py file from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Clothes @registry.register_document class ClothesDocument(Document): class Index: # Name of the Elasticsearch index name = 'clothes' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: # The django model associated with this Document model = Clothes # The fields of the model you want to be indexed in Elasticsearch fields = [ 'Type', 'Pattern', 'Category', 'Title', 'Description',] Here is the model file from django.db import models class Clothes(models.Model): Type = models.TextField(null=True) Pattern = models.TextField(null=True) Type = models.TextField(null=True) Brand = models.TextField() Category = models.TextField() I want to use "term" and "terms" query [Ex. Q("term", Category="Male")] for which I am required to define Category as a KeywordField in Documents.py, How to do that? or Am I missing something? to_queryset() gives ValueError: Field 'id' expected a number but got 'jD4fFHkBKYODK07NgooC'. What I did was: query = Q("match", Category="Male") s = Search(index='abc').query(query)[0:36] qs = s.to_queryset() From docs Last few lines: https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html -
Djan-go run sslserver
I have this code for CMD to run the website with ssl py manage.py runsslserver 127.0.0.1:8384 but today I decided to use waitress-serve, this is the code I use in CMD to run the website without SSL waitress-serve --listen=*:8384 tracker.wsgi:application Now, I don't know how to run the website with SSL using waitress-serve code. Please help. -
Redirect link with token to the correct page
i am implementing email verification on my website, i am sending a link/"token" to the user, how do i make it so that the link redirects to success/failed page, here is how am sending the link (i am using React on the front end if that matters) views.py @api_view(['POST']) def sendmail(request): FRONTEND_URL='http://127.0.0.1:8000' token = get_random_string(length=32) verify_link = FRONTEND_URL + '/email-verify/' + token subject, from_email, to = 'Verify Your Email', 'my@email', request.data['to'] html_content = render_to_string('verify_email.html', {'verify_link':verify_link, 'base_url': FRONTEND_URL}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return JsonResponse({"message": "email sent"},status=HTTP_200_OK)