Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Django MultiSelectField values
I have installed Django MultiSelectField through the library django-multiselectfield==0.1.12 and here is my code. models.py: class Job(models.Model): CONTRACT = (("1", _("Indefinido")), ("2", _("Temporal")), ("3", _("Formación o Prácticas")), ("4", _("Autónomo o Freelance"))) contract = MultiSelectField(verbose_name=_("Contract"), max_length=200, choices=CONTRACT, null=True) The Django Admin Form works well, i can select various optionsare saved and show again selected. The database store the list of option ids correctly. But when try to access attribute values on python appears None: print(self.job.contract) None, None Anybody could help me please ? Thanks in advanced. -
How to make a field editable while creating, but read only in existing objects?
I've a django Model, and want to be able to set an id while creating. But once created, the id of existing object shouldn't be editable. class Vehicle: id = models.UUIDField(primary_key=True, default=uuid.uuid4) I see that I need to turn do "editable=True" (which is the default) on the id field, but this would allow editing the id field later on as well. -
Passing POST request by AJAX, Django problem
my view is : def creating_profile(request): if request.is_ajax and request.method == "POST": array = request.POST.get('nums') print(request.POST.get('nums')) else: print('it's not ajax') my js: const RegisterForm = document.forms["RegisterForm"]; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; let nums = [1, 2, 3] RegisterForm.addEventListener('submit', () => { $.ajax({ headers: { 'X-CSRFToken': csrftoken }, url: '/account/creating-profile/', type: 'POST', data: { nums: nums }, success: function (data) { // } }); but it returns None the result of print(request.POST.get('nums')), I would be glad if someone help me about this issue -
django: Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?
Please help with the error I am getting following along a django book.The errors states: "Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?". Attached is the image. Thanks django webpage error {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% if user.is_authenticated %} Hi {{user.username}}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> | <a href="{% url 'signup' %}">Sign Up</a> {% endif %} {% endblock content %} -
KeyError : But the key exists and getting the good result
I have an API that analyse items contained in an image url and return me a dictionnary, everything is OK until I try to count how many occurences of a key, value pair ! The problem is that Python tell me that there is a KeyError on a key that exists and moreover I'm getting the result I want ... To explain, the first for loop is here to access the first dict and then I'm using Counter to group values contained in the 'labelName' key by their key. I'm learning Python just to say. @api_view(['GET']) def send_image_to_url(request, encoded_url): analyzed_image = analyze_url(encoded_url) items_list = [] for response in analyzed_image.values(): aggregated_items = Counter(item["labelName"] for item in response) return Response(aggregated_items) Here is analyzed_image : { "response": [ { "labelId": 8722, "labelName": "Sofa", "score": 0.99225813 }, { "labelId": 8732, "labelName": "Low Table", "score": 0.9896868 }, { "labelId": 8729, "labelName": "Carpet", "score": 0.98912084 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.9777501 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.97317785 }, { "labelId": 8714, "labelName": "Chair-Armchair", "score": 0.9629707 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.91856897 }, { "labelId": 8722, "labelName": "Sofa", "score": 0.88815445 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.6156193 }, { "labelId": … -
How to change `related_name` field of model after migration in Django?
Initially I created a model as shown in image here: MyModel is dummy name Notice, user as a field with ForeignKey relation with related_name as creater which is actually a spelling mistake which I made. Then I ran python manage.py makemigrations and python manage.py migrate commands. After that I realised that I need to correct the spelling and I changed it accordingly as shown in image here: Notice change Now again to incorporate these changes I ran the above two command but when I ran python manage.py makemigrations command I got following error: Error by Django -
Problems with dynamic like and dislike buttons via django templates and JS
I'm trying to dynamically create and use like and unlike buttons for my cs50w project, which should of course allow the user to like or unlike a post and switch a like button to an unlike button and so on. Now, the infuriating thing is, the like and unlike mechanics themselves work, but the buttons are screwing with me. Either I can't get the opposite button to be created after I deleted the original one via Javascript (I tried to use appendChild and CreateElement, to no avail). Or if a post has more than 1 like then more buttons show up with 2/3 of them being duds, etc. I check in a Django view if the current user has liked any posts (the likes are in their own model with 2 Foreign Keys), then if there are any posts then I send them as context to the necessary templates. Inside the templates themselves, I check if a post corresponds to the context if it does I generate an Unlike button, if not I generate a Like button. I've tinkered and googled but the situation is not improving at all... Code: index.html: {% extends "network/layout.html" %} {{ user.username|json_script:"username" }} {% block … -
Querying for GroupBy in Django
class Author(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10, null=True, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): name = models.CharField(max_length=100) author = models.ManyToManyField(Author, related_name='book_author') price = models.SmallIntegerField() def __str__(self): return self.name Hello there! I've been trying to group by the cost of books in the above model according to the author (as there can be multiple authors for a single book). I know it can be done using groupby but I don't know how to query for it in Django ORM, I tried searching the web but didn't get the relevant solution. What I'm trying to do is, for e.g., if a book 'Wonder' has two authors 'A' and 'B' and they have written together with other books as well, like 'Wonder' by 'A' and 'B' and 'New' by 'A' and 'B' So, I want to query for the books with the combination of their authors + a total cost field of all the books written by the authors (many-to-many author combination). If there is a way, please help and sorry for the bad English. -
suit_form_tabs is not working in Django-Admin
I am using django-suit to create my website's admin. I want to create different tabs in a form, for that I am using suit_form_tabs property I added it in my admin but it does not working and not showing in admin form. change_form_template = 'admin/view_order.html' def customer_username(self, obj): return format_html(f'''<a href="/admin/signin/customer/{obj.username.id}/change/">{obj.username.username}</a>''') def generate_invoice(self, obj, request): print("Generating invoice......") return messages.info(request,message="generate invoice") def view_order(self, obj): return f"Order No #{obj.id}" list_display = ['view_order', 'customer_username', 'full_name', 'email','shipping_mobile_number', 'created_at', 'order_status'] suit_form_tabs = (('info', 'Info'), ('address', 'Address'),('products', 'Products'),('tracking','Tracking')) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url='', extra_context=None): if not object_id: self.form = OrderForms2 self.inlines = [orderProduct,OrderTrackingAdminTabular] self.fieldsets = [ ('Info', { 'classes': ('suit-tab', 'suit-tab-info',), 'fields': ['full_name'] }), ('Address', { 'classes': ('suit-tab', 'suit-tab-address',), 'fields': []}), ('Products', { 'classes': ('suit-tab', 'suit-tab-products',), 'fields': []})] self.suit_form_tabs = (('info', 'Info'), ('address', 'Address'),('products', 'Products'),('tracking','Tracking')) extra_context = {} extra_context.update({ 'show_save': True, 'show_save_and_continue': True, 'show_save_and_add_another': False, 'show_delete': False, 'Add_Order': True,}) return admin.ModelAdmin.changeform_view( self, request, object_id=object_id, form_url=form_url, extra_context=extra_context) obj = self.get_object(request, unquote(object_id)) if request.method == 'POST' and 'generate_invoice' in request.POST: self.generate_invoice(obj, request) return redirect(f'/api/v1/order/generate_invoice/{obj.id}/') self.form = OrderForms self.inlines = [] if request.method == 'POST' and 'save_delivery_partner' in request.POST: if not len(request.POST['delivery_partner']): del_partner = None else: del_partner = request.POST['delivery_partner'] obj.delivery_partner = del_partner obj.save() return HttpResponseRedirect(request.get_full_path()) if request.method == … -
Could not determine join condition between parent/child tables on relationship Product.collections
The relationship between Product and Collection is many to many. A product can be in many collections and each collection can have many products. For such case, I want to convert the django models to sqlalchemy in fastapi. Below is a table for product and collection in django models class Product(models.Model): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) name = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) class CollectionProduct(models.Model): collection = models.ForeignKey( "Collection", related_name="collectionproduct", on_delete=models.CASCADE ) product = models.ForeignKey( Product, related_name="collectionproduct", on_delete=models.CASCADE ) class Collection(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) products = models.ManyToManyField( Product, blank=True, related_name="collections", through=CollectionProduct, through_fields=("collection", "product"), ) background_image = VersatileImageField( upload_to="collection-backgrounds", blank=True, null=True ) I tried the below way to migrate django model to sqlalchemy. However, I got following error sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Product.collections - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. sqlalchemy class Product(Base, TimestampMixin): id = Column(Integer, primary_key=True, index=True) title = Column(String(255), nullable=False) slug = Column(String, index=True, unique=True) # referencing the parent product_type_id = Column(Integer, ForeignKey("producttype.id")) product_type = relationship("ProductType", back_populates="products") collections = relationship( "Collection", back_populates="product", ) collectionproduct … -
Django mongoengine rendring pdf file
I am trying to open my pdf file from my search result as i am using mongoengine in django. Recently i shift from sql to mongodb. how to open pdf file from frontend mongoengine django search.html for sql db.below code is for sqldb and i am looking for similar to this in mongoengine django ''' <h1>You searched for {{ searched }} </h1> <br/> {% for i in Document %} <a href="{{ i.file.url }}" class="btn btn-outline-secondary" target="_blank"> {{i.filename}}</a> <br/> ''' This is my search function ''' def search(request): if request.method == "POST": if request.POST.get('searched'): searched = request.POST.get('searched') dbname = my_client['resume'] collection_name = dbname["user_resumes"] collection_name.create_index([("num2","text")]) Document = collection_name.find({"$text": {"$search": str(searched)}},{"score": {"$meta": "textScore"}}).sort([("score",{"$meta":"textScore"})]) return render(request,'search.html'{'searched':searched,'Document':Document}) ''' if you have any reference please share it with me. -
Returning data from task Django+Celery
I'm new to Django and Celery. So what I'm trying to do is return data after it has been queried via the corresponding models object in a task. tasks.py from celery.decorators import task from .models import * from .serializers import * from .views_api_utils import * from rest_framework import status from rest_framework.response import Response @task(name="get_all") def get_all(): dummies = Dummy.objects.all() return dummies views.py @api_view(["GET"]) @authentication_classes([]) @permission_classes([]) def dummy_list_all(request): """ list all dummy objects """ if request.method == "GET": dummies = get_all.delay() serializer = DummySerializer(dummies, many=True) return Response(dummies, status=status.HTTP_200_OK) The issue at hand is that I keep getting this error TypeError: Object of type AsyncResult is not JSON serializable. Advise? -
emotion detection face-api-js models connot load in the django
''' Failed to load resource: the server responded with a status of 404 (Not Found) :8000/models/face_landmark_68_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) :8000/models/face_recognition_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) face-api.min.js:1 Uncaught (in promise) Error: failed to fetch: (404) Not Found, from url: http://127.0.0.1:8000/models/tiny_face_detector_model-weights_manifest.json at face-api.min.js:1 at face-api.min.js:1 at Object.next (face-api.min.js:1) at n (face-api.min.js:1) (anonymous) @ face-api.min.js:1 (anonymous) @ face-api.min.js:1 (anonymous) @ face-api.min.js:1 n @ face-api.min.js:1 :8000/models/face_expression_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found)''' anyone help to solve this error to load models can i give path for inside the js file? means can we used load static in js ? if yes pleas help ''' const video = document.getElementById('video') Promise.all([ faceapi.nets.tinyFaceDetector.loadFromUri({% static '/models' %}), faceapi.nets.faceLandmark68Net.loadFromUri({% static '/models' %}), faceapi.nets.faceRecognitionNet.loadFromUri({% static '/models' %}), faceapi.nets.faceExpressionNet.loadFromUri({% static '/models' %}) ]).then(startVideo) function startVideo() { navigator.getUserMedia( { video: {} }, stream => video.srcObject = stream, err => console.error(err) ) } video.addEventListener('play', () => { const canvas = faceapi.createCanvasFromMedia(video) document.body.append(canvas) const displaySize = { width: video.width, height: video.height } faceapi.matchDimensions(canvas, displaySize) setInterval(async () => { const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions() const … -
Django Help: AttributeError: module 'django.db.models' has no attribute 'BooleanFeild'
I am working on a simple chat application in Django 3.2.5, I faced an issue here when I gave python manage.py makimigrations command, the terminal showed this error File "C:\Python\Python3.9.6\Scripts\ChatApp\chat\models.py", line 8, in Message is_read = models.BooleanFeild(default=False) AttributeError: module 'django.db.models' has no attribute 'BooleanFeild' And the code of the models.py file is from django.contrib.auth.models import User from django.db import models class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=12000) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) Please help me in resolving this error. Your kind response will really be helpfull. -
How <object> or <iframe> does not work with Nginx reverse proxy
My website has a section to display another website by using . It works fine if user access the web server directly. However, that section does not show anything if I put the web behind nginx reverse proxy. I wonder if any nginx configuration shoud be added to support this application. Thank you. HTML <div class="container-fluid"> <div id="terminal" style="height: 800px; width: 100%;"> <div> </div> JS $("#consolebutton").click(function(e) { e.preventDefault(); var device = $('#device option:selected').text(); $.ajax({ type: "POST", url: "{% url 'Generate_Console_Session' %}", headers: { "X-CSRFToken": "{{ csrf_token }}" }, data: { "device": device }, success: function(result) { var instance = JSON.parse(result); var ip_address = instance["ip_address"]; var console_string = '<object type="text/html" data="http://172.18.1.10:8888?hostname=' + ip_address + 'width="1500px" height="800px" style="overflow:auto"></object>'; $("#terminal").html(console_string); }, error: function(result) { alert('Internal Error'); } }); }); Nginx server { listen 8443 ssl; server_name 127.0.0.1 172.18.1.10 managementserver; ssl_certificate /etc/nginx/cert.crt; ssl_certificate_key /etc/nginx/cert.key; ssl_session_cache builtin:1000 shared:SSL:10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4; ssl_prefer_server_ciphers on; access_log /var/log/nginx/app.log; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://console:8000; proxy_read_timeout 90; } } -
How to access user details in all pages in django?
After login I want to access User details when ever I want (Particularly in navigation bar). I did not use user model provided in django. I created my own model like this for authentication. My database is stored in mysql on phpmyadmin(Xampp). AdminUser Modal class adminUser(models.Model): username=models.CharField(max_length=50) firstname=models.CharField(max_length=50) department=models.CharField(max_length=50) name=models.CharField(max_length=50) mail=models.CharField(max_length=50) id=models.IntegerField(primary_key=True) password=models.CharField(max_length=200) class Meta: db_table="admin_users" admin_users.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) print(is_check) if is_check==True: return redirect(reverse('faq_index')) else: return render(request,'AdminUsers/login.html') return render(request,'AdminUsers/login.html') During the login User Details can be only access by login function but I want to access user details in all pages for navigation bar and also want to find out whether user is authenticated or not. As I am not using User Model in django so I can not user user.is_authenticated(). So How do I do this? -
How i can to refactor code model using Built-in class-based generic views in django?
i implements Views with Built-in class-based generic views in django. i using a Listview CreateView UpdateView DeleteView like this. @method_decorator(decorators, name='dispatch') class CustomerListView(ListView) @method_decorator(decorators, name='dispatch') class CustomerCreateView (CreateView ) @method_decorator(decorators, name='dispatch') class CustomerUpdateView(UpdateView ) @method_decorator(decorators, name='dispatch') class CustomerDeleteView(DeleteView ) and this urls.py path('customer/', views.CustomerListView.as_view(), name='customer-list'), path('customer/add', views.CustomerCreateView.as_view(), name='customer-add'), path('customer/update/<id>', views.CustomerUpdateView.as_view(), name='customer-update'), path('customer/delete/<id>', views.CustomerDeleteView.as_view(), name='customer-delete'), this code work normally. but i have implement multiple model with this pattern such as Customer,Employees,Woker, ..... and more. i want to know how to refacetor code like this. in views.py ------------- class Customer(Somthing): # this include Listview CreateView UpdateView DeleteView model = CustomerModel class Employee(Somthing): # this include Listview CreateView UpdateView DeleteView model = EmployeeModel class Woker(Somthing): # this include Listview CreateView UpdateView DeleteView model = WokerModel in urls.py ------------- path('customer/', views.Customer.as_view()), path('employee/', views.Employee.as_view()), path('worker/', views.Worker.as_view()), how the best way to implements?. thank you for expert. -
Why "CSRF verification failed. Request aborted." in CreateModelMixin in django rest framework?
I am new to django rest framework, and trying to write a view to register users but whenever i am running my view by hitting the desired url i get the following error. Error:- Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. View:- class UserRegistration(mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = RegistrationSerializer def post(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) Serializer:- class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True} } def save(self): password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'error': 'p1 and p2 must be same'}) if User.objects.filter(email=self.validated_data['email']).exists(): raise serializers.ValidationError({'error': 'email already exists'}) account = User(email=self.validated_data['email'], username=self.validated_data['username']) account.set_password(password) account.save() return account Note:- I am using postman forAPI testing. I know there are some great way to do the same, but for this instant i would like make this … -
How to use query result in if statement tag in Django template
Is it possible to use query result in if statement template tag category.html (template): {% for ETF in ETFs %} <td>{{ ETF.ticker }}</td> <td>{{ ETF.full_name }} {% if ETF.asset_class == "Inverse" %} <! –– this don't work ––> <span class="alert-warning" > Inverse </span> {% endif %} </td> {% endfor %} views.py def etf_list(request): filtered_results = ETF.objects.all() return render(request, "etf/category.html", { "ETFs": filtered_results, }) It does not work here because ETF.asset_class is not a string object. So it cant equal to another string. Is there other ways to make it work? I have a table of items in the html and want to highlight some items that have some model attributes. -
Django - how can i insert '.json' file to SQLite DB?
my '.json file' like { "users": [ { "userId": 1, "firstName": "AAAAA", "lastName": "as23", "phoneNumber": "123456", "emailAddress": "AAAAA@test.com", "homepage": "https://amogg.tistory.com/1" }, { "userId": 2, "firstName": "BBBB", "lastName": "h5jdd", "phoneNumber": "123456", "homepage": "https://amogg.tistory.com/2" }, { "userId": 3, ... i was search that to google, and try to this problem.. but unresolved. so i use pandas and sqlite3 import sqlite3 as db import pandas as pd df = pd.read_json('test.json') con = db.connect('./test.db') df.to_sql('test', con=con) so DB is created, but .json file data dont save in DB how can solve this problem...? -
Django - Serialize a list of primary keys for ManyToMany attribute?
So I have this test that generates a list of goal categories, which are the primary key then it populates the model described below. When it goes to UserInterestViews if I pass the list of goal_category_list I get an error that they aren't valid PKs, but when I just pass in 1 string it's fine. How do I pass in a list of primary keys to a ManyToManyField in the serializer? test import json from django.urls import reverse from django.test import TestCase from rest_framework import status from cheers.models import GoalCategory from dummy_factory.Factories import UserFactory class UserInterestsTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.goal_category_list = ['health', 'fitness', 'academic', 'spiritual'] for gc in cls.goal_category_list: GoalCategory.objects.create(category=gc, emoji_url='some_url') cls.user = UserFactory() def test_create(self): response = self.client.post(reverse('set_user_interests'), data=json.dumps({'user': str(self.user.uuid), 'categories': self.goal_category_list}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) view.py class UserInterestsView(APIView): """ View for UserInterests object * requires token authentication """ # Create user interests @swagger_auto_schema( request_body=UserInterestsSerializer, operation_description="Create user interests object" ) def post(self, request): serializer = UserInterestsSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() except django.db.utils.InternalError as e: return Response(dict(error=e), status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) model.py class UserInterests(AbstractBaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE) categories = models.ForeignKey(GoalCategory, on_delete=models.CASCADE) -
setting limit to floatfield according to another floatfield
I have these fields in a form. demand = forms.FloatField(label='Demand:', min_value=0) production_rate = forms.FloatField(label='Production rate:', min_value=0) I need producion_rate to be greater than the demand value. It's possible? -
Exist any way of automatic validation in the django serializer for primaryKey (author_slug or phrase_slug)?
I have my CRUDs with models, serializares and views. # models.py from django.db import models class Author(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() class Meta: db_table = 'authors' class Phrase(models.Model): author_slug = models.ForeignKey(Author, db_column='author_slug', on_delete=models.DO_NOTHING) text = models.TextField() class Meta: db_table = 'phrases' # serializers.py from rest_framework import serializers from .models import Author, Phrase class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('slug', 'name', 'description') class PhraseSerializer(serializers.ModelSerializer): author = AuthorSerializer(source='author_slug', read_only=True,) class Meta: model = Phrase fields = ('id', 'text', 'author_slug', 'author') # views.py from rest_framework import viewsets from .models import Author, Phrase from .serializers import AuthorSerializer, PhraseSerializer class AuthorViewSet(viewsets.ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() class PhraseViewSet(viewsets.ModelViewSet): serializer_class = PhraseSerializer queryset = Phrase.objects.all() Now i need to do a new specify endpoint GET /exist-relationship-bwt-author-phrase when this body: { "author_slug": "an-author", "phrase_slug": "a-phrase" } Exist any way of automatic validation in the django serializer for primaryKey (author_slug or phrase_slug)? -
DRF test if JSON list of objects contains a specific object
I'm testing an endpoint from Django DRF, which produces a JSON list of objects. I'm trying to check if a specific object is in the returned list. I've tried assertIn and assertContains, but they produce errors. Test code for the assertIn: def test_list(self): client = APIClient() response = client.get('/api/some_list/', format='json') self.assertEqual( len(response.data), 19 ) self.assertIn( response.data, { "id": 2, "name": "WhatToDo" } ) assertIn produces TypeError: unhashable type: 'ReturnList' Test code for the assertContains: def test_list(self): client = APIClient() response = client.get('/api/some_list/', format='json') self.assertEqual( len(response.data), 19 ) self.assertContains( response, { "id": 2, "name": "WhatToDo" } ) assertContain just failed the test. What is the best approach to test if a specific object exists in the JSON list in response? -
ValueError: The view blog.views.post_search didn't return an HttpResponse object. It returned None instead
I'm implementing "search function" to my django blog, using Solr and Haystack. In "http://127.0.0.1:8000/blog/search/", it says TypeError at /blog/search/ post_detail() missing 3 required positional arguments: 'year', 'month', and 'day' Also in "http://localhost:8000/blog/search", it says ValueError at /blog/search The view blog.views.post_search didn't return an HttpResponse object. It returned None instead. blog/forms.py from django import forms class SearchForm(forms.Form): query = forms.CharField() blog/search_indexes.py from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish') def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().published.all() blog/urls.py from blog.feeds import LatestPostsFeed from django.conf.urls import url from django.urls import include, path from . import views app_name = 'blog' urlpatterns = [ path('search', views.post_search, name='post_search'), ] blog/views.py from .forms import SearchForm from haystack.query import SearchQuerySet def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) blog/templates/blog/post/search.html {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} {% if "query" in request.GET %} <h1>Posts containing "{{ cd.query }}"</h1> <h3>Found {{ total_results }} result{{ total_results|pluralize}}</h3> {% for result in results %} …