Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with posting in GeoDjango
I'm trying to create an API that takes coordinates on a chart plane and is able to filter the data according to the width, length and the area of a counter box or wahtever emthod that the help me out. GeoDjango v3.2 looks like a good alternative to achieve this, also the djangorestframework-gis==1.0 package but when I try to use the post methos I get the error: "This field is required" this is the payload: import requests import json url = "http://127.0.0.1:8000/image/" payload = json.dumps({ "thickness": 1, "corners": { "type": "Point", "coordinates": [ 12.492324113849, 41.890307434153 ] } }) headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) print(response.text) this is my model: from django.contrib.gis.db import models as gis_models from django.db import models from django.utils.translation import gettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from hashid_field.field import HashidAutoField class ImageManager(models.Manager): pass class Image(models.Model): thickness = models.IntegerField(_("Thickness in [mm]")) corners = gis_models.PointField(_("Corners coordinates")) objects = ImageManager() class Meta: verbose_name: str = 'Image' THe serializer is: from hashid_field.rest import HashidSerializerCharField from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometryField from images.models import Image class ImageSerializer(GeoFeatureModelSerializer): corners = GeometryField(precision=2, remove_duplicates=True) class Meta(object): model = Image geo_field = 'corners' auto_bbox = True fields = '__all__' -
Django execute couple prefetch_related lookups in a single query
For now a I have not found an ability to execute reverse foreign key joins in Django more efficiently that using a prefetch_related a.k.a. joining in python. This method would generate 1 additional query for each reverse lookup and if I have 4-5 of those they start to decrease the performance and increase execution time. The only thing that is able to achieve that in one query is a full raw sql (not model.objects.raw()) which completely separates query results from the models (python objects) and leads to problems with drf serialization, fields renaming, testing and other stuff you can come up with. Does someone have an idea how to overcome this? Relation example: class Contest(models.Model): ... class Award(models.Model): contest = models.ForeignKey(Contest, related_name="awards") ... Contest.objects.prefetch_related("awards") # would generate 2 queries p.s. thanks in advance :) -
Django. ListView. The image attribute has no file associated with it
I'm new to Django, and I try to show the images of my model via the ListView class but keep getting the error "attribute has no file associated with it". Below is my code. model.py: from django.db import models class AboutModel(models.Model): person_name = models.CharField(max_length=128, null=True) person_position = models.CharField(max_length=128, null=True) person_photo = models.ImageField(upload_to='team_pictures', blank=True) views.py: from django.views import generic from . import models class AboutPage(generic.ListView): context_object_name = 'team_list' model = models.AboutModel app's urls.py: from django.urls import path from . import views app_name = 'app_main' urlpatterns = [ path('products_page/', views.ProductsPage.as_view(), name='products_page'), path('about_page/', views.AboutPage.as_view(), name='about_page'), path('contacts_page/', views.ContactsPage.as_view(), name='contacts_page'), ] project's urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.HomePage.as_view(), name='index'), path("admin/", admin.site.urls), path('details/', include('app_main.urls', namespace='app_main')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: <div class='container team_members'> {% for member in team_list %} <img src={{ member.person_photo.url }}> <br>{{ member.person_name }} - {{ member.person_position }}<br> {% endfor %} </div> Solutions to similar issues on stackoverflow didn't help as custom function views are used there or the problem itself is different. -
Django taggit returns empty list of tags in search view
Explanation I would like to add to SearchView a filter that checks tags in my models and if raw_query contains tag then it displays the list of relevant objects. Each model contains title and tags fields. I am using django taggit with autosugest extension to handle tags in my application. For instance user is inserting tag1 into a search bar and MyModel1 contains a tag like this then it should appear on the page. If not then my SearchView is checking if rank returns anything and return list of relevant objects. Problem tag_query is always returning empty list. I checked database and tags are added correctly. I can display them in Django templates properly but my tag_query return empty list of tags. Question How can I implement tags filter properly so based on users query it will check list of tags and return objects that contain this tag. Code models.py from taggit_autosuggest.managers import TaggableManager class MyModel1(models.Model): title = models.CharField('Title', max_length=70, help_text='max 70 characters', unique=True) tags = TaggableManager() ... views.py class SearchView(LoginRequiredMixin, CategoryMixin, ListView, FormMixin, PostQuestionFormView): model = MyModel1 template_name = 'search/SearchView.html' context_object_name = 'results' form_class = PostQuestionForm def get_queryset(self): models = [MyModel1, MyModel2, MyModel3] vectors = [SearchVector(f'title', weight='A') + SearchVector(f'short_description', … -
Nginx not serving user-uploaded media(Image) files when Debug=False in settings.py
I have set up a django website that would be served by Nginx, everything was working perfectly not until images stopped showing recently. I tried inspecting the possible cause of this strange development using curl and then realized that the Content-Type is not recognized as Content-Type: image/jpeg returns a Content-Type: text/html; charset=utf-8 Below are my files : Variables in Settings.py STATIC_URL = '/home/ubuntu/static/' MEDIA_URL = "/home/ubuntu/media/" STATIC_ROOT = '/home/ubuntu/static' MEDIA_ROOT = '/home/ubuntu/media/' ONNGO_DOMAIN = "https://onngo.co.in" PROFILE_PICTURE_URL = MEDIA_ROOT+"profile_pictures/" STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) Here is my full nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; server_names_hash_bucket_size 512; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; #gzip_vary on; #gzip_proxied any; #gzip_comp_level 6; #gzip_buffers 16 8k; #gzip_http_version 1.1; #gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/core; } #mail { # # See … -
how can I put existing django from my system to my new project
I created new python project and I find it difficult to reused my existing django module into my project I tried to write some cammand to include the django and it denied -
Return a list of options only if they exist in two Django Models
I have two models in my models.py file: Flavour model: class Flavour(models.Model): flavour_choice = models.CharField(null=True, blank=True, max_length=254) def __str__(self): return self.flavour_choice and Product model: class Product(models.Model): category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.SET_NULL ) slug = models.SlugField() sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) brand = models.TextField() has_flavours = models.BooleanField(default=False, null=True, blank=True) flavours = models.ForeignKey( 'Flavour', null=True, blank=True, on_delete=models.SET_NULL ) has_strength = models.BooleanField(default=False, null=True, blank=True) strength = models.ForeignKey( 'Strength', null=True, blank=True, on_delete=models.SET_NULL ) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) display_home = models.BooleanField(blank=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_at',) def __str__(self): return self.name I want to able to add flavours to the flavours table and then choose if they appear for particular products. How would I go about this? I know I could just add the flavours to the product but so many of the products I want to have, have the same flavours. I need to be able to do this database side and not just programmatically so admin users can add flavours and products via a front-end product management page. Any help would be greatly appreciated! -
Works well in Postman but not production
I want to display a variable generated in views.py in my login.html The views.py generates a username(voucher) and I want it auto filled in my login.html In the function the mpesa_body are details from a callback so it neither a GET nor POST. def confirmation(request): print("Start MpesaCallback") global profile, voucher mpesa_body = request.body.decode('utf-8') mpesa_body = json.loads(mpesa_body) print(mpesa_body) print("Mpesa Body") merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"] print('merchant_requestID: ', merchant_requestID) checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"] print('checkout_requestID: ', checkout_requestID) result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"] print('result_code: ', result_code) result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"] print('result_desc: ', result_desc) metadata = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"] for item in metadata: title = item["Name"] if title == "Amount": amount = item["Value"] print('Amount: ', amount) elif title == "MpesaReceiptNumber": mpesa_receipt_number = item["Value"] print('Mpesa Reference No: ', mpesa_receipt_number) elif title == "TransactionDate": transaction_date = item["Value"] print('Transaction date: ', transaction_date) elif title == "PhoneNumber": phone_number = item["Value"] print('Phone Number: ', phone_number) str_transaction_date = str(transaction_date) trans_datetime = datetime.strptime(str_transaction_date, "%Y%m%d%H%M%S") tz_trans_datetime = pytz.utc.localize(trans_datetime) payment = MpesaPayment.objects.create( MerchantRequestID=merchant_requestID, CheckoutRequestID=checkout_requestID, ResultCode=result_code, ResultDesc=result_desc, Amount=amount, MpesaReceiptNumber=mpesa_receipt_number, TransactionDate=tz_trans_datetime, PhoneNumber=phone_number, ) if result_code == 0: payment.save() print("Successfully saved") password_length = 5 voucher = secrets.token_urlsafe(password_length) headers = { 'Content-Type': 'application/json', 'h_api_key': os.getenv("SMS_Token"), 'Accept': 'application/json' } payload = { "mobile": phone_number, "response_type": "json", "sender_name": "23107", "service_id": 0, "message": "Your WiFi Voucher is " + … -
Django get duration between now and DateTimeField
I have a Django model with the following field: date = models.DateTimeField('start date') I want to create a duration function that returns the duration between now and the date in the format "hours:minutes" How can we achieve this? -
400 (Bad Request) from Django Ajax sending Request
How to show simple message in ajax In below code url going to my view in the view else block but giving 400 bad request, when i am approving url is going to view and printing else message in coomand line but again giving 400 bad request function approveEmployeeTimesheet(emp_id) { //$("#approveTimesheet").off("click"); var yearMonth = $("#timesheetYearMonth").val(); bootbox.confirm("Are you sure you want to Approve ?", function (result) { if(result) { $.ajax({ url: "{% url 'user:Check_pending_request_approve_timesheet' %}", data: {"csrfmiddlewaretoken": "{{csrf_token}}", "year_month": yearMonth, "emp_id": emp_id}, dataType: "json", type: "POST", success: function(result) { $.ajax({ url: "{% url 'user:approve_employee_timesheet' %}", data: {"csrfmiddlewaretoken": "{{csrf_token}}", "year_month": yearMonth, "emp_id": emp_id}, dataType: "json", type: "POST", success: function(result) { // hide the edit, approve buttons. $("#approveTimesheet").hide(); $("#sendEditLink").hide(); $("#sendEditLinkApproveDiv").html("<div class='text-success' style='display:table;'><b><i class='fa fa-check'></i> Approved by "+result.timesheetApprovedBy+"</b></div>"); var myToast = Toastify({ text: "Timesheet Approved", duration: 3000, gravity: 'bottom' }); myToast.showToast(); getEmpTimesheets(emp_id) } }); }, error: function(err) { bootbox.alert("Please Approve/Reject the pending requests under tab"); } }); } }); } -
Django, how to cast base model to proxy model
I have a place in my code, where I need to overload model's property. For this matter I'm using proxy model of my base instance. models: class Question(TimeTrack): class Types(models.TextChoices): SINGLE_CHOICE = "SC", _("single_choice") MANY_CHOICE = "MC", _("many_choice") TRUE_FALSE = "TF", _("true_false") CHRONOLOGY = "CHR", _("chronology") MATCHING = "MCH", _("matching") position = models.PositiveIntegerField() text = models.CharField(max_length=512) image_src = models.CharField(max_length=256, blank=True, null=True) time = models.PositiveIntegerField() feedback = models.CharField(max_length=512) type = models.CharField(max_length=30, choices=Types.choices) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) @property def answers(self): return self.answer_set.all() @property def correct_answers(self): return self.answer_set.filter(is_correct=True) def __str__(self): return f"Question #{self.id}" class ShuffledQuestion(Question): class Meta: proxy = True @property def answers(self): _answers = list(super().answers) random.shuffle(_answers) return _answers and the place where I create proxy: _question_data = model_to_dict(question) _question_data["quiz"] = question.quiz _question_data["group"] = question.group newQuestion = ShuffledQuestion(**_question_data) The above works just fine, but I wonder if there is "more elegant" way to accomplish the same. -
Ckeditor Image Properties how to modify this tab
I am trying to customize the Image Properties section of CKEditor, but I don't know where to access the properties to modify it. I refer to this screen here: The changes I seek are: make Upload default tab instead of Image Info Change Theme of this as it doesnt seem to use the skin I applied to actual rich text editor, as long as someone can point me to css behind it I can do the rest. Ability to actually modify width and height as they seem to be locked for some reason and I cant find property that handles it Set max width hard cap on images so they don't go above certain pixel amount. I use Django Python for reference. This is my custom config: CKEDITOR_CONFIGS = { 'default': { 'skin': 'light', 'removeDialogTabs': 'image:Link;image:advanced;', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'defaultstyle', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'TextColor', '-', 'Undo', 'Redo', '-', 'Link', 'Unlink', 'Anchor', '-', 'Image', 'Table', 'HorizontalRule', '-', 'Source', '-', 'Preview' ]}, '/', {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, ], 'toolbar': 'YourCustomToolbarConfig', … -
Django, F object should be passed to my own function
I want to fetch leave requests of all employees where from date should be greater than each employees individual timezone. So i need to get Timezone and convert it to current employee timezone datetime. But im getting error that F object value is not passed as a value in to the function but as a F object. How to pass F object into the function or any solution to get current employee timezone and convert it to timezone current time? Thanks in advance LeaveRequest.objects.filter(from_date__gte=my_own_func(F('request__employee___user__timezone')) -
Django Postgresql dump file import export errors
After exporting database to sql file, it's impossible to import it again to database, it gives many syntax errors and Error in query (7): ERROR: schema "public" already exists I also tried removing all tables in database and it's not worked. How can I solve this issue? What is the best way to export and import database? Versions : Django 4, Postgresql 14.6 -
Testing Django data migrations. Tests pass, when ran solo, fail when ran in batch
Im trying to test data migrations, which include operations on two models: class Category(models.Model): title = models.CharField("Category title", max_length=100) def __str__(self): return self.title class Tag(models.Model): name = models.CharField("Tag", max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f"{self.category}:{self.name}" The migrations: def add_tags_to_category_processes(apps, schema_editor): Category = apps.get_model("surveys", "Category") Tag = apps.get_model("surveys", "Tag") processes_category = Category.objects.get(title="Processes") tags_to_add = ("B2B", "EC", "Security", "Operations") for tag in tags_to_add: Tag.objects.create(name=tag, category=processes_category) class Migration(migrations.Migration): dependencies = [ ("surveys", "0049_change_location_users"), ] operations = [ migrations.RunPython(add_tags_to_category_processes), ] and def add_tag_to_category_external_hr_brand(apps, schema_editor): Category = apps.get_model("surveys", "Category") Tag = apps.get_model("surveys", "Tag") external_hr_brand_category = Category.objects.get(title="External HR Brand") tag_to_add = "External_Events" Tag.objects.create(name=tag_to_add, category=external_hr_brand_category) class Migration(migrations.Migration): dependencies = [ ("surveys", "0050_add_tags_to_category_processes"), ] operations = [ migrations.RunPython(add_tag_to_category_external_hr_brand), ] and finally tests: @pytest.mark.django_db def test_0050_add_tags_to_category_processes(migrator, settings): settings.ALLOWED_MIGRATIONS.append("0050_add_tags_to_category_processes") old_state = migrator.apply_initial_migration( ("surveys", "0049_change_location_users") ) Category = old_state.apps.get_model("surveys", "Category") Category.objects.create(title="Processes") new_state = migrator.apply_tested_migration( ("surveys", "0050_add_tags_to_category_processes") ) Tag = new_state.apps.get_model("surveys", "Tag") Category = new_state.apps.get_model("surveys", "Category") processes_category = Category.objects.get(title="Processes") # assert Tag.objects.filter(category=processes_category).count() == 4 tag_names = ("B2B", "EC", "Security", "Operations") assert ( all(Tag.objects.filter(name=name).exists() for name in tag_names) is True ) migrator.reset() @pytest.mark.django_db def test_0051_add_tag_to_category_external_hr_brand(migrator, settings): settings.ALLOWED_MIGRATIONS.append( "0051_add_tag_to_category_external_hr_brand" ) old_state = migrator.apply_initial_migration( ("surveys", "0050_add_tags_to_category_processes") ) Category = old_state.apps.get_model("surveys", "Category") Category.objects.create(title="External HR Brand") new_state = migrator.apply_tested_migration( ("surveys", "0051_add_tag_to_category_external_hr_brand") ) Tag = new_state.apps.get_model("surveys", … -
Main Container going blank
I am trying to make a home page in my Blog, but the template is messing everything up. The page only displays the navbar and the footer. What is wrong?? This is a screenshot of the home page. This is a link to the code. I have tried removing stuff, and changing it, but it still doesn't work. -
Make DRF EXCEPTION_HANDLER work with ViewSet
I'm using ViewSet for defining views like so: class PatientViews(ViewSet): def list(self, request): """ Returns a Bundle of all available patients, with/without search query """ ... def retrieve(self, request, id): """ Retrieves a particular patient """ ... def create(self, request, format=None): """ Creates a new patient """ ... I've configured the exception handler like so: def api_exception_handler(exc: Exception, context: dict): print("Here") # I want this to print return response Here's the urls.py (not very relevant here I suppose): urlpatterns = [ path("Patient", PatientViews.as_view({"get": "list", "post": "create"})), path("Patient/<id>", PatientViews.as_view({"get": "retrieve"})), ] And used settings.py mods to import it: REST_FRAMEWORK = {"EXCEPTION_HANDLER": "fhir.urls.api_exception_handler"} The api_exception_handler doesn't get called at all when I make an exception at the retrieve method (it's being called through POST method on ViewSet). How can I make this work? -
sent an image displayed on the page to the django server
I have an image which is displayed on the page when the image is clicked a modal opens containing a button. I would like by clicking on the button sent the selected image to the django server. The image tag and the button tag are in different tag structures with others tag so i can't use <form action="" method="post"> ... </form>. <div> <button id="myBtn" type="button"> <img src="path_image" width="200" height="200" alt="description" id="my-image"> </button> </div> <!-- ... --> <!-- button that is in a modal --> <div> <button id="sendBtn" type="button"> upload image </button> </div> How can i get the image and send it ? -
How to do dynamic nested serialization in django rest framework
For an API that serves multiple quizzes, each of which have varying questions, I have the following models:- class Quiz(models.Model): name = models.CharField() class QuizQuestion(models.Model): quiz = models.ForeignKey(related_name="questions", Quiz) question = models.CharField() class QuizCompletion(models.Model): completed_by = models.ForeignKey(User) quiz = models.ForeignKey(Quiz) class QuizAnswer(models.Model): quizquestion = models.ForeignKey(QuizQuestion) quizcompletion = models.ForeignKey(related_name="answers", QuizCompletion) answer = models.CharField() I am trying to write the serializers and views I need in order to allow the QuizCompletion to be created but I'm having some problems with the validation side of things, as the questions each quiz has (and therefore the answers that it needs) are dynamic. So, each quiz has different questions. My serializers look like this:- class QuizQuestionSerializer(serializers.ModelSerializer): class Meta: model = QuizQuestion fields = ["question"] class QuizSerializer(serializers.ModelSerializer): questions = QuizQuestionSerializer(many=True) class Meta: model = Quiz fields = ["name", "questions"] class QuizAnswerSerializer(serializers.ModelSerializer): quizquestion = QuizQuestionSerializer() class Meta: model = QuizAnswer fields = ["quizquestion"] class QuizCompletionSerializer(serializers.ModelSerializer): quiz = QuizSerializer() answers = QuizAnswerSerializer(many=True) class Meta: model = QuizCompletion fields = ["completed_by", "quiz", "answers"] The problem is, how do I validate the request when a user tries to complete a quiz to make sure that they've given an answer to all of that Quiz's questions? My gut feeling is that … -
Need to write custom User model in DJango and return pre stored json file in response
Just started learning Python/Django 5 days back. Need to write an API where it gets 'username', 'password', 'password2' in request and it should store username in some User object. And if the username already exists in User, then just return simple error message: "username is duplicate". I am using User class from django.contrib.auth.models. Which returns a BIG error response , if username is duplicate. Question 1: I want to return simple one line error message in response. from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password class RegisterSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) if attrs['usename']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Question 2: I want to write an API, which on a GET call , returns pre-stored simple json file. This file should be pre-stored in file system. How to do that? -
user models in django
I created the "Account" model but the contents on the admin dashboard and the model I created are not the same I have manually set the fields for admin in the account section, as shown below enter image description here but what appears on the admin dashboard is like the following imageenter image description here Can anyone help me to remove the fields I don't need? -
How to solve djongo.exceptions.SQLDecodeError when i migrate?
i was creating a chatapplication with MongoDB as my storage. everything was fine and i was using JWT to authenticate user. but it all started crashing the moment i turned one Blacklist=True in JWT settings and added 'rest_framework_simplejwt.token_blacklist', in installed apps. & it's showing me this error: PS E:\py\projects\Django\Chat-application\backend\chat_backend> python manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions, token_blacklist Running migrations: Applying token_blacklist.0002_outstandingtoken_jti_hex...This version of djongo does not support "schema validation using NULL" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0003_auto_20171017_2007... OK Applying token_blacklist.0004_auto_20171017_2013...This version of djongo does not support "COLUMN SET NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0005_remove_outstandingtoken_jti...This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0006_auto_20171017_2113... OK Applying token_blacklist.0007_auto_20171017_2214...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 857, … -
django click on pagination links on Detailview not updating detailview content
for django project based on tutorial project https://github.com/mdn/django-locallibrary-tutorial project I want to show first, previous,next, last pagination links . when clicked on next link I want to load bookdetail of next book and when clicked on previous link I want to load previous book details. I made following change in views.py of catalog app class BookListView(generic.ListView): """Generic class-based view for a list of books.""" model = Book paginate_by = 10 # class BookDetailView(generic.DetailView): """Generic class-based detail view for a book.""" # model = Book class BookDetailView(generic.DetailView, MultipleObjectMixin): """Generic class-based detail view for a book.""" model = Book paginate_by = 1 def get_context_data(self, **kwargs): object_list = Book.objects.all() context = super(BookDetailView, self).get_context_data(object_list=object_list, **kwargs) return context It shows booklist with pagination as shown in screenshot It shows pagination link on bookdetail page as shown in screenshot but when next or previous link is clicked bookdetails content is not updated, it remains same. what change is needed so that on each Bookdetail page when next/previous link is clicked next/previous bookdetails is loaded and to show first bookdetail and last bookdetail link on each bookdetail page -
Attribute error on Django REST framework, 'Quiz' object has no attribute 'question'
These are my models class Quiz(models.Model): title = models.CharField(max_length=255) topic = models.CharField(max_length=255) difficulty = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Question(models.Model): text = models.TextField() quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) def __str__(self): return self.text class Choice(models.Model): options = models.TextField() is_correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return self.text class QuizResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField() date_taken = models.DateTimeField(auto_now_add=True) def _str_(self): return f"{self.user.username} - {self.quiz.title} - {self.score}" And here is my serializer.py from rest_framework import serializers from ..models import Quiz, Question, Choice class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = ['options', 'is_correct'] class QuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True) class Meta: model = Question fields = ['text', 'choices'] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(source = 'question',many=True) class Meta: model = Quiz fields = ['title', 'topic', 'difficulty', 'questions', 'created_by'] def create(self, validated_data): questions_data = validated_data.pop('question') quiz = Quiz.objects.create(**validated_data) for question_data in questions_data: choices_data = question_data.pop('choices') question = Question.objects.create(quiz=quiz, **question_data) for choice_data in choices_data: Choice.objects.create(question=question, **choice_data) return quiz When I send a post request to QuizCreateAPIView it shows an error Got AttributeError when attempting to get a value for field questions on serializer QuizSerializer. The serializer field might be … -
Hindi fonts not showing correctly in reportlab generated PDF
I want to generate PDF file in Marathi font, the font is not support properly in reportlab I am trying the code mentioned in the image but it is not working properly I am expecting like this -I marked that the expected result should look like this