Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ckeditor Imageresize is not working with django
I am designing my site using Django + CKeditor. My requirement is to reduce the image size before uploading it to the server as my images are sized 3mb ~3000x2500 pixels, I am trying "imageresize" plugin for client side image resize. In the documentation Config are given to set maxWidth, maxHeight to 800. I dont know where to set this configuration. Also want to know if any other plugin that can work better with CKeditor for reducing the image size. Thanks in advance. -
Why it is occuring KeyError: 'main' and how to solve it
I am having keyerror: 'main'. I am searched many sites still can't find any satisfactory answer to solve this error. I would really appreciate if someone can give me solutions. Thanks in advance. I have tried solving this my adding a function on the init.py which is suggested by a site. But it still didn't work. https://forum.inductiveautomation.com/t/error-on-sys-modules/6431/2 code: view.py from django.shortcuts import render import requests from .models import City def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=632cfde42b162b08916956c4360238f0' cities = City.objects.all() # return all the cities in the database city = 'Dhaka' # request the API data and convert the JSON to Python data types city_weather = requests.get(url.format(city)).json() weather_data = [] for city in cities: # request the API data and convert the JSON to Python data types city_weather = requests.get(url.format(city)).json() weather_app = { 'city': city, 'temperature': city_weather['main']['temp'], 'description': city_weather['weather'][0]['description'], 'icon': city_weather['weather'][0]['icon'] } # add the data for the current city into our list weather_data.append(weather_app) #context = {'weather' : weather_app} context = {'weather_data': weather_data} # returns the index.html template return render(request, 'weather_app/index.html') terminal: (env) acer@acer-Aspire-V3-472P:~/DjangoProject/Weather$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 03, 2019 - 06:48:01 Django version 2.2, using settings … -
PermissionError: [Errno 13] Permission denied: '/personal_portfolio'?
I ran python3 manage.py collectstatic then I got "PermissionError: [Errno 13] Permission denied: '/personal_portfolio'" Im running on mac os. Building my site on django. There is no effect on my css so I ran collectstatic and got a permission denied error -
Cannot serialize Django object with JsonResponse instance
This question seems to have been asked multiple times on SO, but none of the answers seem to work. I have this model: class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Post(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) content_url = models.URLField(null=False) and I try to serialize it into JSON here: def create_post(request): post_content = request.body post_content_url = save_post(post_content) # returns a string post = Post.objects.create(user=request.user, content_url=post_content_url) post.save() return JsonResponse({"post": post}) When I do this I get the following error: TypeError: Object of type Post is not JSON serializable What am I doing wrong? The JsonResponse class is supposed to dump the object to json: class JsonResponse(HttpResponse): def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs): if safe and not isinstance(data, dict): raise TypeError( 'In order to allow non-dict objects to be serialized set the ' 'safe parameter to False.' ) if json_dumps_params is None: json_dumps_params = {} kwargs.setdefault('content_type', 'application/json') data = json.dumps(data, cls=encoder, **json_dumps_params) super().__init__(content=data, **kwargs) Please help. According to everything I've read, this should work. -
How to download data from azure-storage using get_blob_to_stream
I have some files in my azure-storage account. i need to download them using get_blob_to_stream.it is returning azure.storage.blob.models.Blob object. so i couldn't download it by using below code. def download(request): file_name=request.POST['tmtype'] fp = open(file_name, 'wb') generator = block_blob_service.list_blobs(container_name) for blob in generator: print(blob.name) if blob.name==file_name: blob=block_blob_service.get_blob_to_stream(container_name, blob.name, fp,max_connections= 2) response = HttpResponse(blob, content_type="image/png") response['Content-Disposition'] = "attachment; filename="+file_name return response -
get URL parameter in function based view
I want add url parameter in function based view how can i do? http://127.0.0.1:8000/xxxxx/4 parameter is 4 i want to aces 4 in view. there is any way to do this? -
Creating custom button in Django admin site
I want to create a custom button in my django admin panel.I have created a directory inside my templates directory and created a file called custom_change_template.html #my_project/my_app/templates/admin/custom_change_template.html {% extends “admin/change_form.html” %} {% load i18n %} {% block submit_buttons_bottom %} {{ block.super }} <div class=”submit-row list-group”> <button type=”button” title=”Cancel” class=”list-group-item active” name=”_cancel” onclick=”location.href=’/admin/order/project/’;”> <span class=”glyphicon step-backward”></span> <span class=”text”>Cancel</span> </button> </div> {% endblock %} But there is still no cancel button in my django admin panel.I have followed this documentation https://medium.com/@CodeRatio/create-custom-button-in-django-admin-change-update-form-4892b25c6653 .Can anyone Please point out what am I doing wrong. -
Django runserver error, new installation, first time user of Django
So I've decided to learn Django, which will be challenging if I cannot get it working. Running Python 3.7.1 (default, Dec 14 2018, 19:28:38) [GCC 7.3.0] :: Anaconda, Inc. on linux (base) runout@runout:~$ python -m django --version 2.2.1 I'm following the tutorial for beginners at djangoproject.com The first line of code was to create a site, which i did... django-admin startproject mysite The second line of code, is where I run into problems. python manage.py runserver My error is as follows: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/runout/anaconda3/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/home/runout/anaconda3/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/runout/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/runout/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/runout/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/home/runout/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/runout/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/runout/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/runout/anaconda3/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/runout/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Get auto-generated field from model in serializer, without returning it
I have a serializer which is used to invite a new user. In the User Model which this serializer used, there is an autogenerated field for an activation key (which gets emailed to the user). What is the best way to cleanly get the activation key in the serializer, without adding it the the User object which will be returned in the response? For obvious reasons, I don't want the activation key being returned to the front end. models.py: class User(AbstractBaseUser): ... activation_key = models.UUIDField(unique=True, default=uuid.uuid4) ... serializers.py: class UserInvitationSerializer(serializers.ModelSerializer): email = serializers.EmailField() class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name') def create(self, validated_data): user = User.objects.create(**validated_data) random_pass = User.objects.make_random_password(length=10) user.set_password(random_pass) user.save() activation_key = ? send_mail('Email Address Verification Request', 'confirm/email/(?P<activation_key>.*)/$', 'info@mydomain',[user.email]) return user -
Django: Cart matching query does not exist
I've a form that creates a Cart with the text "Random" in a character field, if there is not a Cart object created. This is only to get this recently object's id if it is not already created. cart = Cart.objects.get(id=cart_id) I get an error saying that this query generates an error, however I can see the value of cart_id as a cookie so the Query should execute without problem. But it doesn't according to the error message. As you can see in my view, I'm using this: cart_id = self.request.COOKIES.get('cart_id') if not cart_id: cart = Cart.objects.create(cart_id="Random") cart_id = cart.id cart = Cart.objects.get(id=cart_id) To get the cookie cart_id if it does not exist I created a Cart object with the Random text, only to get it's ID. Why I'm getting the error? View.py: class StepOneView(FormView): form_class = StepOneForm template_name = 'shop/medidas-cantidades.html' success_url = 'subir-arte' def get_initial(self): # pre-populate form if someone goes back and forth between forms initial = super(StepOneView, self).get_initial() initial['size'] = self.request.session.get('size', None) initial['quantity'] = self.request.session.get('quantity', None) initial['product'] = Product.objects.get( category__slug=self.kwargs['c_slug'], slug=self.kwargs['product_slug'] ) return initial def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get( category__slug=self.kwargs['c_slug'], slug=self.kwargs['product_slug'] ) return context def form_invalid(self, form): print('Step one: form is NOT valid') … -
Passing django variable in ajax data
I would like ajax to post some variables which have been created in a view. My problem is that it isn't written in the proper way and anything is sent to my post request when I am looking at the chrome inspecter. This is my javascript function : function submitDataTable() { let table = $(document.getElementById('datatable')).DataTable() let advisedPriceColumn = table.column('advised_price:name') let advisedPriceData = advisedPriceColumn.data().toArray() $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' } }) $.ajax({ url: 'submit/', type: 'POST', data: { advisedPrice: advisedPriceData, normal_price: '{{ normal_price|safe }}', }, processData: false, success: res => { alert('Bien ouej mon vieux') location.reload() }, error: xhr => { alert(xhr.responseText.split('\n')[1]) } }) }; These are some of the variables of my view that I would like to pass in my JS function: return render(request,'livedb_model/typeDetail.html',{ 'property':property, 'roomtype':roomtype, 'invdf':invdf, 'price_advised_list':price_advised_list, 'price_list':price_list, 'occupancy_list':occupancy_list, 'c_occupancy_list':c_occupancy_list, 'normal_price_list':normal_price_list[:100], 'normal_price':normal_price, 'week_day_multi':week_day_multi, 'week_end_multi':week_end_multi, 'max_discount':max_discount, 'max_markup':max_markup, 'coccCategory':coccCategory, 'agressiveness':agressiveness }) And this is a screenshot of the chrome inspector, where we can see that only an [object Object] is passing Please can you help me on this? -
how to get abstract user first_name and last_name and how to update it
enter code here models.py class User(AbstractUser): `` id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Employee(models.Model): employee = models.OneToOneField(User, on_delete=models.CASCADE) reporting_manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='reporting_managers', null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) date_of_join = models.DateField(null=True, blank=True) date_of_exit = models.DateField(null=True, blank=True) i want here first_name and last name from Abstract user and that should be also updatable.please help me out this issue views.py class EmployeeUpdateView(UpdateView): """ For updating profile of each employee :update view """ model = Employee fields = ('reporting_manager','date_of_birth','date_of_join','gender','address','photo',\ 'department','employee_code','blood_group','designation','phone_no','personal_email_id','official_email_id',\ 'email_domain','city','allowed_apps') template_name = "registration/update_employee.html" -
Unable to connect to Postgres service using docker and tox
I have a docker application that builds a Postgres database. I am using tox to run my Django tests. When I am running docker-compose run web tox over my docker image in my local machine (I used docker-compose up --build --force-recreate -d to build my docker image) it is showing error as E django.db.utils.OperationalError: could not connect to server: Connection refused E Is the server running on host "127.0.0.1" and accepting E TCP/IP connections on port 5432? But when I am running the only tox command (not on my docker image) it is working fine. I tried to run my Django test without tox that is by using docker-compose run web python manage.py test over my docker image. In this case, it is not showing any errors. I guess I have some problem to run tox over my docker image. Can someone please help me with it? -
How to use Django Filter on a separate page and send the GET data to the original query set page
So let's imagine I have this filterset: class PlayerPageFilter(FilterSet): position = filters.MultipleChoiceFilter(choices=FIELD_POSITION_CHOICES, widget=Select2MultipleWidget) class Meta: model = PlayerDetailPage fields = [] And this view: def get_context(self, request): context = super(PlayerPage, self).get_context(request) context['filter_page'] = PlayerPageFilter(request.GET, queryset=PlayerDetailPage.objects.all()) Then in the PlayerPage template you have something like this: {% for s in filter_page.qs %} {{ s.position }} {% endfor %} How to write a view for the homepage where I can use the same PlayerPageFilter and which sends me to the original template page query set after submitting the form. So not rendering the query set on the homepage but on the original page. -
Django chained or dependent dropdown list
i am new in Django and for my project i need to show a serie of linked DDL in this order “System -> Device -> Component”. I test some examples from web but with no results. My model: class System(models.Model): name = models.CharField(max_length=50) class Device(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=255) system = models.ForeignKey(System, on_delete=models.PROTECT) class Component(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=255) device = models.ForeignKey(Device, on_delete=models.CASCADE) Form: class DeviceForm(forms.ModelForm): class Meta: model = Device System = forms.ModelChoiceField(queryset=System.objects.all()) Device = forms.ModelChoiceField(queryset=Device.objects.all()) Component = forms.ModelChoiceField(queryset=Component.objects.all()) Views: def device_form(request): #form = DeviceForm(request.Device or None, initial={'Affiliazione': initial_value}) form = DeviceForm() return render(request, ‘portal/device_form.html', {'form':form}) Url: path(‘portal/device_form', views.device_form, name=‘device_form’) Last thing i notice, is using Ajax to refresh the next DDL after select and django REST framework I appreciate any help, thanks .Desa -
My default database in my django app is on read-only
On my web app, created with Django, the database 'default' that I am using is on read-only, so I encounter some issue with the admin pages and with the migrate method. The database with the writing access is called with a name because it is not very used compared to the default one. So my question is what is the best solution between changing the name of my databases or modifying the files of the admin and migrate methods? Thank you for your help, -
How to call django-taggit tags using templates tags
I want to filter by multiple Django-taggit tags using Django Haystack and Elasticsearch, I have written a facets function in a custom forms but I can't retrieve the results that match with the selected filter(s) in my templates. So how can I possibly do this? My models.py: class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title My custom forms.py: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs Passing forms in Views.py: class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['ptags'] template_name = 'search_result.html' paginate_by = 6 context_object_name = 'object_list' If needed, the urls: urlpatterns = [ url(r'^$', HomeView.as_view()), url(r'^admin/', admin.site.urls), url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'), url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'), ] + static(MEDIA_URL, document_root=MEDIA_ROOT) And finally, in the templates side … -
How to change the background login error message and view of djang restframework
My question is on the title.Do you need to modify the source code to do this? I've tried to modify the source code to do that, but is there any other way? -
Django Upgrade from 1.11 to 2.2.1 Problem with URLs and Paths
Today I decided to upgrade my project from Django 1.11 to 2.2.1. I've been working through various issues with my project, and I'm fighting through them. However, I spent most of tonight trying to get the URLs to work and they won't cooperate. Long story short, I have multiple app in my project and each app has a URL with it's own namespace. In Django 1.11 this is working fine. However, when I try to port the logic over to Django 2.2.1, I keep getting an error saying that I have a circular import somewhere probably. Here is a snippit of what works just fine in Django 1.11....... My Main Project...In Django 1.11 url(r'^Main/',include('AppA.urls',namespace="AppA")), But when I try to do this in Django 2.2.1..... I realize that URLs were replaced by paths... path('', include('AppA.urls')), But when I try to start my application it says.... your project does not appear to have any patterns in it. If you see valid p atterns in the file then the issue is probably caused by a circular import. I can't seem to figure out how to create the namespace that is working in django 1.11 so that I can properly reference my urls in … -
Django: Filter variable
In my models.py I filter for two cases. I check if there is: a ticket_on_sale ticket_on_sale_soon If 2) is given but 1) not, then the method should give back True. I filter on a variable level (after the database is already hit). I wonder if there is a more solid way. What I did doesn't feel right. Do you have suggestions? @cached_property def only_scheduled_tickets(self): tickets = self.tickets.all() ticket_on_sale = list(filter( lambda ticket: ticket.is_on_sale() and ticket.is_available(), tickets, )) ticket_on_sale_soon = list(filter( lambda ticket: ticket.is_on_sale() and not ticket.is_available(), tickets, )) if ticket_on_sale_soon and not ticket_on_sale: return True -
AttributeError at /search/ 'QuerySet' object has no attribute 'facet'
I'm Getting an AttributeError ( AttributeError at /search/ 'QuerySet' object has no attribute 'facet' ) while setting up custom filters for django-taggit tags with Haystack. The search function is working fine when I enter a query like so: http://localhost:8000/search/?q=las+vegas But the error is showing up when I try to add an other variable for the ptags filter like so: http://localhost:8000/search/?q=las+vegas&ptags=Solo How can I solve this? Full output: System check identified no issues (0 silenced). May 02, 2019 - 20:56:46 Django version 1.10.5, using settings 'uvergo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /search/ Traceback (most recent call last): File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 120, in get form = self.get_form(form_class) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\edit.py", line 45, in get_form return form_class(**self.get_form_kwargs()) File "C:\Users\loicq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\views.py", line 47, in get_form_kwargs kwargs = super().get_form_kwargs() File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 94, in get_form_kwargs kwargs = super(FacetedSearchMixin, self).get_form_kwargs() File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 65, in get_form_kwargs kwargs.update({'searchqueryset': self.get_queryset()}) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", … -
How to "translate" this SQL query to queryset in django
So I've got these Django models (the code is simplified by the way): class Travel(models.Model): #there are many other fields origin_city = CharField() end_city = CharField() class Segment(models.Model): start_time = DateTimeField() origin = CharField() end = CharField() travel = ForeignKey(Travel) price = IntegerField() So a travel has a set of segments, for example if the travel is A->B->C->D->E, then the segments are (A,B) , (B,C) , (C,D) and (D,E). I want to get, given an origin and end, the travels that pass through the given origin and then through the given end. For example, if origin and end are (B,D), the example travel is valid, since it goes through B at some point and then it goes through D later, but it wouldn't be valid for (D,B). I know that in SQL, this could be done like this (assuming travel stores ids and segment has them with foreign key restrictions): SELECT t.* FROM travel as t, segment as s1,segment as s2 WHERE t.id = s1.travel_id AND t.id = s2.travel_id AND s1.origin = (user given origin) AND s2.end = (user given end) AND s1.start_time < s2.start_time -
Django: How to serialize QuerySet into object instead of array?
I want to serialize a QuerySet into a JSON object instead of JSON array. For model Day, the serialized QuerySet should be an object with Day.date keys and serialized Days as values. class DaySerializer(serializers.ModelSerializer): class Meta: model = Day exclude = [] This returns an array of serialized objects: DaySerializer(Day.objects.all(),many=True).data {'15.02.2005':{...}, '16.02.2005':{...}, ... } I'm curious if there is some DRF way to do that. -
Why can my EC2 send email though Gmail butnot from a custom domain?
I'm having an issue with my django mailing, apparently i can send email with an gmail account with no problem, but i can't send any email from my custom domain email. There is a curios thing, locally my SMTP SSL email works, but loaded on the EC2 instance it doesn't send anything. I have tried by changing from SMTPSSL to only SMTP but still not working, also I have tried on a heroku instance but again, the heroku instance doesn't even send from gmail as the EC2 instance. ACCOUNT_EMAIL = os.environ['ACCOUNT_EMAIL'] ACCOUNT_PASSWORD = os.environ['ACCOUNT_PASSWORD'] # EMAIL_PROVIDER = 'smtp.gmail.com' //gmail configurations # EMAIL_SERVER_PORT = 587 EMAIL_PROVIDER = 'krishna.hosting-mexico.net' EMAIL_SERVER_PORT = 465 SECURITY_EMAIL_SENDER = ACCOUNT_EMAIL def send_driver_welcome_email(user_email): from_email_address = EMAIL from_email_address_password = PASSWORD htmly = get_template('driver_welcome_email.html') message = MIMEMultipart('alternative') message['Subject'] = 'Bienvenido a TAXI 2.0' message['From'] = from_email_address message['To'] = user_email html_content = htmly.render(None) part1 = MIMEText(html_content, 'html') message.attach(part1) server = smtplib.SMTP(EMAIL_PROVIDER, EMAIL_SERVER_PORT) #server = smtplib.SMTP_SSL(EMAIL_PROVIDER, EMAIL_SERVER_PORT) //This works locally server.ehlo() server.starttls() server.login(from_email_address, from_email_address_password) server.sendmail(from_email_address, user_email, message.as_string()) server.quit() I don't get why this gets, and google hasn't help much, since a lot of pages suggest to use SES, but i don't have any interest of using it since i want to use … -
AttributeError at /search/ 'FacetedProductSearchForm' object has no attribute 'queryset'
I'm trying to add search filters for my django-taggit tags in my Django project but I keep getting this AttributeError. I'm using Django-Haystack and Elasticsearch for the search functionalities, and this time I'm trying to add the filter with haystack Facets. Full output: Internal Server Error: /search/ Traceback (most recent call last): File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 123, in get return self.form_valid(form) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 76, in form_valid self.queryset = form.search() File "C:\Users\loicq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\forms.py", line 19, in search sqs = self.queryset.filter(ptags__name__in=ptags).distinct() AttributeError: 'FacetedProductSearchForm' object has no attribute 'queryset' [02/May/2019 18:38:34] "GET /search/?q=las+vegas&ptags=Solo HTTP/1.1" 500 86568 My Models: class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title My custom forms.py: from haystack.forms import FacetedSearchForm from django.db.models.query import QuerySet class FacetedProductSearchForm(FacetedSearchForm): …