Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFound
No matter what I do I can't fix the problem. I'm having trouble deploying. I am getting error 503 Service Unavailable. Current thread 0x00007f6008afd740 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/home/usr/virtualenv/core/3.8' PYTHONPATH = '.:/home/usr/core/' program name = '/home/usr/virtualenv/core/3.9/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/home/usr/virtualenv/core/3.9/bin/python' sys.base_prefix = '/home/usr/virtualenv/core/3.8' sys.base_exec_prefix = '/home/usr/virtualenv/core/3.8' sys.platlibdir = 'lib64' sys.executable = '/home/usr/virtualenv/core/3.9/bin/python' sys.prefix = '/home/usr/virtualenv/core/3.8' sys.exec_prefix = '/home/usr/virtualenv/core/3.8' sys.path = [ '.', '/home/usr/core/', '/home/usr/virtualenv/core/3.8/lib64/python39.zip', '/home/usr/virtualenv/core/3.8/lib64/python3.9', '/home/usr/virtualenv/core/3.8/lib64/python3.9/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fdbc7fe0740 (most recent call first): <no Python frame> I tried almost all the methods I came across with the Google search engine, i tried removing the PYTHONHOME environment variable, which is the most popular solution. I also tried with Linux and Windows. But I never understood the problem. I would be very happy if someone could help me with this. -
Python / Django template : dropdown menu after the third elements
I would like have a list where I can see the first three elements then if there are more elements it will be in a dropdown menu like this : MESSAGE Message 01 Message 02 Message 03 ShowMore (clickable) Message 04 .... Thi is my template : {% if messages %} <div class="collection-item"> <ul> {% for message in messages %} <li{% if message == object %} class="active"{% endif %}> <a href="{{ message.get_absolute_url }}" title="{{ message.customer_product }}" data-turbolinks="false"> <i class="material-icons state-flag {{ message.get_color }}-text">lens</i> <span class="hide-on-collapsed">{{ message }}</span> <span class="show-on-collapsed"><small>{{ message.title }}</small></span> </a> </li> {% endfor %} </ul> </div> {% endif %} -
Store and Retrieve Complex data from django session
Please I created a class in django that contains both variables and functions. import scipy.special from django.db import models class neuralNetwork(models.Model): def __init__(self,no_of_Inodes,no_of_Hnodes,no_of_Onodes,learning_rate): self.inputnodes = no_of_Inodes self.hiddennodes = no_of_Hnodes self.outputnodes = no_of_Onodes self.lr = learning_rate self.w_input_hidden = numpy.random.normal(0.0,pow(self.inputnodes,-0.5),(self.hiddennodes,self.inputnodes)) self.w_hidden_output = numpy.random.normal(0.0,pow(self.hiddennodes,-0.5),(self.outputnodes,self.hiddennodes)) self.activation_function = lambda x: scipy.special.expit(x) pass I initialized it and decided to use it in a different page using 'request.session'. I used django rest framework to serialize it. from rest_framework import serializers from .neuralclass import neuralNetwork class NeuralSerializer(serializers.ModelSerializer): class Meta: model = neuralNetwork fields = '__all__' Then I tried to store it in 'request.session' after training the class (it will contain some values I will use later in a different page). request.session["stored"] = NeuralSerializer(n,many=False).data Then this is what I did to retrieve it in a new page. A page I want to test the network. n = neuralNetwork(request.session["stored"]) But then it always return an empty value for 'n' for me. Please what can I do to allow me to save and retrieve such information from page to page -
Django OneToManyField ProfileUpdate integration with user registration
I m having problems integrating user registration form info with another form used as a profile updater Models.py class Profile(models.Model): skill_choices = (('Beginner', 'BEGINNER'), ('Intermediate', 'INTERMEDIATE'), ('Expert', 'EXPERT')) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) assumed_technical_ski_level = models.CharField(max_length=30, choices=skill_choices) years_of_experience = models.IntegerField(blank=True) money_to_spend = models.IntegerField(blank=True) @receiver(post_save, sender= user) def create_user_profile(self, sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=user) def save_user_profile(self, sender, instance, **kwargs): instance.profile.save() Views.py class ProfileUpdateView(LoginRequiredMixin, TemplateView): profile_form = ProfileForm template_name = 'aplicatie2/profile-update.html' def post(self, request): post_data = request.POST or None profile_form = ProfileForm(post_data, instance = request.user.profile) if profile_form.is_valid(): profile_form.save() return HttpResponseRedirect(reverse_lazy('aplicatie2:lista')) context = self.get_context_data(profile_form = profile_form) return self.render_to_response(context) def get(self, request, *args, **kwargs): return self.post(request) Forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('location', 'assumed_technical_ski_level', 'years_of_experience', 'money_to_spend') The registration is done using the django standard library UserCreationForm I'm getting this error : RelatedObjectDoesNotExist at /companies/questions/ User has no profile. Does someone know a solution to this ? -
How do I get my CreateAPIView to recognize the "validate' seciton of my serializer?
I'm using Django 3.2 and Django rest framework 3.12.2 and have django.contrib.auth installed. I would like to create an endpoint to create users, so I have set this up in my views ... class CreateUserView(CreateAPIView): model = User permission_classes = [ IsAuthenticated ] serializer_class = UserSerializer And I have created this serializer ... class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', 'id', 'first_name', 'last_name') def validate(self, data): errors = {} # required fields required_fields = ['username', 'password', 'email'] for field in required_fields: if not data[field]: errors[field] = 'This field is required.' if errors: raise serializers.ValidationError(errors) return data def create(self, validated_data): user = User.objects.create_user( username=validated_data['username'], password=validated_data['password'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'] ) return user Unfortunately when I submit a request withoutcertain fields (e.g. "email"), read -d '' req << EOF { "first_name": "Test 9999", "last_name": "Dave", "username": "test3@abc.com", "password": "password1" } EOF curl --header "Content-type: application/json" --header "Authorization: Token 6cbf7a80c6dd40e84861c8de143c945aef725676" --data "$req" --request POST "http://localhost:8000/users/" My validator isn't running and instead I get errors in the "create" part of my serializer ... File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/serializers.py", line 453, in validate if not data[field]: KeyError: 'email' How do I structure my view such that the validator in my serializer will be recognized? -
How to translate text in an external javascript file? (Django)
I have a JavaScript file that appends elements to the body according to the user interaction. Right now in my index.html template I'm declaring global variables with the translated text: {% block main %} <script> let TRANSLATION = {% trans "my text" %} </script> {% endblock %} So after Django translates the text in my index template, my JavaScript file can take the translated text and append it using something like: element.innerHTML = TRANSLATION; I know this is a very dirty way of translating the text that JavaScript will use because some users won't need that text and in those cases I'll be wasting resources with variables that I won't be using. So the question is: What is the clean and correct way to translate text for external JavaScript files? -
how do I show the options of a radio button with widget_tweaks?
I'm using widget_tweaks, everything is displayed fine except the radio buttons, when I put this code, it displays the information as a select, and what I want is for it to look like a radio button. Is there any way that the options are show like this? models.py COUNTRIES=( ('EUA', ('EUA')), ('Canada', ('Canada')), ('Other', ('Other')), ) class Profile(models.Model): country = models.CharField(max_length=100, default=0,choices=COUNTRIES) html <label class="form-label d-block mb-3">Country :</label> <div class="custom-radio form-check form-check-inline"> {% render_field form.country class="form-check-input" type="radio" %} <label class="form-check-label" for="customRadioInline1">United States</label> </div> <div class="custom-radio form-check form-check-inline"> {% render_field form.country class="form-check-input" type="radio" %} <label class="form-check-label" for="customRadioInline2">Canada</label> </div> <div class="custom-radio form-check form-check-inline"> {% render_field form.country class="form-check-input" type="radio" %} <label class="form-check-label" for="customRadioInline2">Other</label> </div> -
I can't activate my virtual environment in PowerShell
When i try activate my virtual environment in CMD, doesn't exit any problem but in PowerShell i'm having that error: PS C:\Users\Burak\desktop\my-site\myenv\Scripts> activate.bat activate.bat : The term 'activate.bat' is not recognized as the name of a cmdlet, function, script file, or operable program. Check t he spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + activate.bat + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (activate.bat:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundExceptionenter code here -
How to write script for dropping column from table in django
I want to write this command in script so that i can drop the required column from a table in django. $ python manage.py dbshell $ psql> ALTER TABLE <table_name> DROP column <COLUMN_NAME>; $ python manage.py syncdb need this coomand in a script form. -
What is the proper way to logout the user via class-based view using Django Token Authentication?
I have my login view working perfectly, and I think the logout view should work properly as well, but everytime I click on the button to logout user, it gives error AonymousUser object has not attribute 'auth_token'. My views.py is below: class LoginAPIHTML(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'accounts/login.html' def get(self, request): serializer = LoginSerializer() return Response({'serializer': serializer}) def post(self, request): serializer = LoginSerializer(data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer}) user = authenticate(request, username=request.data['email'], password=request.data['password']) if user: Token.objects.get_or_create(user=user) login(request, user) return redirect('user') else: return redirect('login') class LogoutAPIHTML(APIView): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] def get(self, request): request.user.auth_token.delete() logout(request) return redirect('login') and the template from where I click the logout button is below: <body> <h1>Use Details</h1> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}"> <input type="button" value="Logout"/> </a> {% else %} <h2>{{ message }}</h2> {% endif %} </body> and my CustomEmailBackend is in authentication.py, and defined as below: from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class CustomEmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None Error details are below: AttributeError at /logout 'AnonymousUser' object has no attribute 'auth_token' Traceback Switch to copy-and-paste view … -
Pyrhon and Django AttributeError ".save"
The propelem is I'm getting an error at this line: s_lance.seve() It's an Attribute error Views.py def f(request): if request.method == "POST": titulo = request.POST['titulo'] user = request.user descricao = request.POST['descricao'] s_lance = Produto(titulo = titulo, user = user, descricao = descricao) s_lance.seve() models.py class Produto(models.Model): titulo = models.CharField(max_length=25) descricao = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="lista", default=None) I expected that values would be saved. However, I got this AttributeError -
Tailwind - Div not taking up full height of screen
I am creating a simple login form using tailwind.css. I want the form to take up the full height of the screen, but for some reason, it doesn't and leaves white space at the bottom: I don't understand why this is happening, but I think it has something to do with the second div, which has the lg:w-1/2 property. Here is my HTML code (I'm including all of it, just in case my issue has is being caused by another HTML element): <div class="" id="content"> <section class="relative bg-white overflow-hidden"> <div class=> <nav class="flex justify-between p-6 px-4" data-config-id="toggle-mobile" data-config-target=".navbar-menu" data-config-class="hidden" style="background-color: #2A3342 !important;"> <div class="flex justify-between items-center w-full"> <div class="w-1/2 xl:w-1/3"> <a class="block max-w-max" href="{% url 'home' %}"> <img class="h-8" src="https://i.ibb.co/LRCrLTF/Screenshot-2022-04-03-140946-removebg-preview.png" alt="LOGO" data-config-id="auto-img-1-2" style="transform: scale(2); padding-left: 30px"> </a> </div> <div class="w-1/2 xl:w-1/3"> <ul class="text-slate-400hidden xl:flex xl:justify-center"> <li class="mr-12"><a class="text-slate-400 font-medium hover:text-white transition ease-in-out delay-150" href="#" data-config-id="auto-txt-1-2" style=" font-size: 18px">About</a></li> <li class="mr-12"><a class=" text-slate-400 font-medium hover:text-white transition ease-in-out delay-150" href="{% url 'classes' %}" data-config-id="auto-txt-2-2" style=" font-size: 18px">Classes</a></li> <li class="mr-12"><a class=" hover:text-white font-medium text-slate-400 transition ease-in-out delay-150" href="{% url 'resources' %}" data-config-id="auto-txt-3-2" style=" font-size: 18px">Resources</a> </li> <li><a class=" hover:text-white font-medium text-slate-400 transition ease-in-out delay-150" href="#" data-config-id="auto-txt-4-2" style=" font-size: 18px" id = "responsivehide">Upcoming</a></li> </ul> … -
Django + APP ENGINE (GAE) - No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found
i want to deploy in App Engine a Django app. I created and configurate a SECRET MANAGER in GAE and when i want to get that secret from my SETTINGS.PY, it display the error 'No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found'. If i create the .env locally it works, but i want to get the secret info from the GAE. SETTING.PY env_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(env_file): # Use a local secret file, if provided env.read_env(env_file) # ... elif os.environ.get("GOOGLE_CLOUD_PROJECT", None): # Pull secrets from Secret Manager project_id = os.environ.get("GOOGLE_CLOUD_PROJECT") client = secretmanager.SecretManagerServiceClient() settings_name = os.environ.get("SETTINGS_NAME", "secret-django-phi") name = f"projects/{project_id}/secrets/{settings_name}/versions/latest" payload = client.access_secret_version(name=name).payload.data.decode("UTF-8") env.read_env(io.StringIO(payload)) else: raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.") REQUIREMENTS.txt google-cloud-secret-manager==1.0.0 django-environ==0.4.5 SECRET MANAGER that i upload on GAE like an .env file db_ip=x db_name=x db_user=x db_pass=x SECRET_KEY=*a lot of characters* -
Django REST Framework reverse() not finding match for router's "{basename}-detail"
This question is extremely similar to: How to fix this NoReverseMatch exception in Django rest frameworks routers? but that hasn't been answered/resolved and after a lot of investigating here I am looking for help. I am trying to build an API with test-driven development. As common practice I begin my tests by saving constant variables for the URLS using django.urls.reverse() The problem is reverse('{app}:{basename}-list') works fine, but reverse('{app}:{basename}-detail') throws the exception: django.urls.exceptions.NoReverseMatch: Reverse for 'designer-detail' with no arguments not found. 2 pattern(s) tried: ['api/design/designer/(?P<pk>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/design/designer/(?P<pk>[^/.]+)/$'] My test.py: (notice the list url runs first and throws no exception) from rest_framework.test import APITestCase, APIClient from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import RefreshToken from django.urls import reverse from rest_framework import status from designs.models import Designer from designs.serializers import DesignerSerializer DESIGNER_LIST_URL = reverse('designs:designer-list') DESIGNER_DETAIL_URL = reverse('designs:designer-detail') My app/urls.py: from rest_framework.routers import DefaultRouter from designs.views import DesignerViewset app_name = 'designs' router = DefaultRouter() router.register(r'designer', DesignerViewset, 'designer') urlpatterns = router.urls My project/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/user/', include('user.urls')), path('api/design/', include('designs.urls')) ] My serializers.py: from rest_framework import serializers from designs.models import Designer class DesignerSerializer(serializers.ModelSerializer): """ Model serializer for Designer. """ class Meta: model = Designer fields = … -
Please someone tell how can I run this (https://github.com/kaan0nder/ceng-407-408-2019-2020-Movie-Recommendation-System) project locally on my system
Please someone tell how can I run this (https://github.com/kaan0nde/ceng-407-408-2019-2020-Movie-Recommendation-System) project locally on my system project locally on my system -
Running Django on Google Colab
I was trying to run the Django on Colab, by following the instruction here, however, after the !python manage.py runserver step, I tried to access the server using Google Colab link you printed by running the eval_js method earlier. there is a error msg: This page isn’t working0yztv6fmakbj-496ff2e9c6d22116-8000-colab.googleusercontent.com is currently unable to handle this request. HTTP ERROR 500 then I tried to access the link http://127.0.0.1:8000/, and it appears error msg as follows This page isn’t working127.0.0.1 didn’t send any data. May I ask how to fix this? If this is not the way to run Django in Colab, what should I do? and every time I run !python manage.py runserver, it keeps executing the Performing system checks... Is that normal? Thanks in advanced. -
How to display image here
Hi there, how can i display image here(its example place on the photo but it will be nice if i can put image here) from field Image but not after saving but live(when i paste url then display preview). I dont have any idea how to do that so the last thing is to write a question here. -
What should my nested URLs look like in REST API?
Let's say that I have Books and Authors. I want to be able to get all the Books for a specified Author. What should my URL look like? I have 2 possible ways, which are: localhost:8000/api/books?author=3 localhost:8000/api/authors/3/books I would also need to retrieve specific books, relating to a specific author. So localhost:8000/api/books/5?author=3 and localhost:8000/api/authors/3/books/5 should only work if the Book 5 was written by Author 3. I noticed that old school developers seem to prefer the first one, while new developers (as well as new companies during interviews) seem to favor the 2nd one. My framework is Django and I'm using DRF, but I think my question is not restricted to Django. If you think RESTful restricts things like this too much, I'd still be interested in your answer in a RESTless way of thinking. -
CS50W lecture7 testing,CI/CD--a problem about YAML and GitHub Actions
I am taking CS50’s Web Programming with Python and JavaScript(CS50W) course. I am now having a problem for lecture 7 Testing, CI/CD. When I followed along Brian in the GitHub Actions section(Timestamp at about 1:13:36), the result in my GitHub Actions turned out not to be the same with his. This is the yaml code( I exactly copied from the lecture) : name: Testing on: push jobs: test_project: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run Django unit tests run: pip3 install --user django python manage.py test In his GitHub Actions there was nothing wrong about the "run django unit tests" part. But Mine turned out to have some errors. My result in GitHub Actions showed as this: Run pip3 install --user django python manage.py test pip3 install --user django python manage.py test shell: /usr/bin/bash -e {0} Collecting django Downloading Django-4.0.3-py3-none-any.whl (8.0 MB) ERROR: Could not find a version that satisfies the requirement python (from versions: none) ERROR: No matching distribution found for python Error: Process completed with exit code 1. So I thought there was something wrong for setting up django or python in the GitHub Ubuntu virtual machine, then I tried to get rid of the python … -
Django Tables2 - Format cell based on value from another cell - Blank values causing issues
I'm using Django Tables2. My goal is to highlight a specific table cell based on the value of another field. I've implemented a solution using render_foo methods (similar to the solution for this post). I have a Team_Leader Column and I would like it to be highlighted if New_Team_Leader is True (signifying that the Team_Leader has changed). It's working for the most part, except if the Team_Leader is left blank. When the Team_Leader is blank, the cell accepts the formatting from the previous row. Here is my code: tables.py import django_tables2 as tables Class AuditTable(tables.Table): def render_Team_Leader(self, value, column, record): if record.New_Team_Leader == True: column.attrs={'td': {'class': 'yellow'}} else: column.attrs={'td': {}} return value This image hopefully demonstrates my problem: Highlight rule fails when cell value is None How can I set it up so that the True/False New_Team_Leader formatting rules are applied, even if the Team_Leader is blank? -
Webpage not loading on Apple Devices
I made a webpage on Django + Bootstrap 5. The page works fine and shows everything, and so does on Mobile for android phones. But when it comes to iPhones 6, 7 or older the page wont display the gifs nor pictures that come dynamically from the DjangoDB as an URL. [this is how it looks on iphone, and a MacbookAir][1] [1]: https://i.stack.imgur.com/hvKVK.jpg This is the code segment that's supposed to display the video_list <ul id="first-category" class="items-container"> {% for video in video_list %} <li class="item"> <section class="video-container {{video.source_name}}"> <a href="{% url 'iepheme_app:video_player' pk=video.id %}"> <img class="visual-resource" aria-describedby="{{video.id}}-title" src="{{ video.thumbnail_url }}" alt="{{ video.title }}"> <section class="info"> <label id="{{video.id}}-title" for="{{video.id}}">{{video.title}}</label> </section> </a> </section> </li> {% endfor %} I have tried putting static images instead of gifs, deleting the media queries to check if it wasn't a display problem. A friend of mine tried the site on these devices: MacBook Pro MacOS Monterrey 2.01+ Tablet Ipad Pro 2018 iOS 15.01 + Iphone 11 Pro Max iOS 15.3.1 and all of them display the webpage without a single problem. So the issue is centered specially around IPhone 6, 7 or older. The site in question is https://www.ipeheme.com I appreciate all kinds of help. -
Django form fill all models and dynamic template
I do not find an example for this and I do not know the best way to do it. The goal is to create one form to fill all models. But, I would like to create a dynamic template. The user can choose in a list something in the database and if he does not find it, he could create the new element in the corresponding model. Following a picture with an example. The form contains for each model a selection of possibility or a + to add a new possibility to the Model. In this example, Model1 does not have what the user want, so he selects the + and dynamically, the fields' Model1 appear. And so, the user can add the new element. Thanks for tracks, example of other idea ;) -
django_auth_ldap, проблемы с разграничением доступа
Дамы и господа, помогите. Создал проект django и подключил к нему библиотеку django_auth_ldap, которая позволяет логиниться пользователям из IPA (причём членам только той группы, которую я вписал в настройках в файле settings.py). Всё работает. Но есть задача- разграничить доступ к разным сайтам проекта, чтобы на один сайт могли логиниться пользователи из одной группы на IPA, а на другой сайт - из другой группы. Как это можно реализовать и возможно ли это вообще? Просто я начинающий сисадмин и чуток не хватает знаний. Заранее благодарен за ответ. Дамы и господа, помогите. Создал проект django и подключил к нему библиотеку django_auth_ldap, которая позволяет логиниться пользователям из IPA (причём членам только той группы, которую я вписал в настройках в файле settings.py). Всё работает. Но есть задача- разграничить доступ к разным сайтам проекта, чтобы на один сайт могли логиниться пользователи из одной группы на IPA, а на другой сайт - из другой группы. Как это можно реализовать и возможно ли это вообще? Просто я начинающий сисадмин и чуток не хватает знаний. Заранее благодарен за ответ. -
django-elasticsearch-dsl-drf suggest url gives 404 'Page not found' error
I am using django-elasticsearch-dsl-drf library and have configured my viewset as per the documentation, but it's still throwing me a 404 'Page not found' for some reason. Also I have already used DocumentViewSet instead of BaseDocumentViewSet Document class ItemDocument(Document): Brand = fields.TextField( fields={ 'raw': fields.KeywordField(), 'original': fields.TextField(), 'suggest': fields.CompletionField(), } ) Category = fields.TextField( fields={ 'raw': fields.KeywordField(), 'original': fields.TextField(), 'suggest': fields.CompletionField(), } ) Viewset: class ProductsDocumentView(DocumentViewSet): document = ItemMasterProductsDocument serializer_class = ProductsSerializer fielddata = True filter_backends = [ FilteringFilterBackend, FacetedSearchFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, SuggesterFilterBackend ] faceted_search_fields = { ... } filter_fields = { ... } ordering_fields = ... ordering = ... # Suggester fields suggester_fields = { 'brand_suggest':{ 'field': 'Brand.suggest', 'suggesters': [ SUGGESTER_COMPLETION ], 'options': { 'size': 10, 'skip_duplicates': True } }, 'category_suggest':{ 'field': 'Category.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': 10, 'skip_duplicates': True } }, } My route for viewset: 'api/products/' URL that I tried: http://127.0.0.1:8000/api/products/suggest/?brand_suggest__completion=Jack I am getting "The current path, api/products/suggest/, didn't match any of these." -
Django Test unique violation with auto increment field
There is problem with unique constraint violation in Django models use. My model is like: class Document(models.Model): id = models.BigAutoField(primary_key=True) ...bla bla bla So "id" field must be unique and it is autoincrement. In production environment I'm encounting problem of saving documents with same id. I think it is caused by parallel celery tasking but now it is handled by business logic to respond with 400 Bad request. Now I have to test logic to handle such type of errors in unit test. So I've tried to think in direction of editing Model's Meta values for "id" field inside a unit test but it isn't worked out.