Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i set up my server with winscp, putty, nginx, ubuntu and gunicorn [closed]
My English is very bad.And I am a beginner in programming I created a backend project with python ,django and rest api.But I don't know how to set up server. Please if someone knows about this , teach me -
django @cache_page decorator not setting a cache
Here's my cache setting: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } And a very basic view with cache_page decorator @api_view(['POST']) @cache_page(60*1) def sawan_ko_jhari(request): data = request.data.get('name') return JsonResponse({"success": True, "data": data}, safe=False) I've been checking cache keys for every request sent.. and I get empty array. Is there something I'm missing here? -
How to incorporate django-tailwind into Dockerized cookiecutter-django project?
Apologies for what is likely a very simple question, I am pretty new to Docker and am struggling to integrate django-tailwind into my docker project, which was created using cookiecutter-django. I have tried altering my Dockerfile and local.yml file to follow the Example dockerfiles on the Example app on the django-tailwind github repo but haven't been able make it work. The instructions beyond the example app are not very detailed. I have quoted my Dockerfile and local.yml file below; would someone be able to advise on what changes I need to make in order to incorporate django-tailwind, or point me in the direction of information that would help me to do it myself? Thanks for any help anyone can offer! Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye # define an alias for the specfic python version used in this file. FROM python:${PYTHON_VERSION} as python # Python build stage FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev # Requirements are installed here to ensure they will be cached. COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir … -
Number of questions Django/Python
Number of questions: Try to create a new game of 20 questions of medium difficulty (MEDIUM) in the Art category. It was acting weird, right? This is definitely not a desirable situation. It follows that Open Trivia DB does not have enough questions from a given category with a given level of difficulty, so it returns us an error. And we do not handle it wisely: try: question = quiz.get_question() quiz.save(request) return render(request, 'game.html', vars(question)) except IndexError as x: return redirect('/finish') because we assume that the end of the questions = the end of the game. What makes sense if the API has the right number of questions ... The response code from the Open Trivia website in this case is 1. Looking at the documentation (https://opentdb.com/api_category.php), we will find out what each code means: Hint We have to think about how to solve this problem. It would be nice if the answer, apart from the error code, would include all possible tasks for a given category and level of difficulty - but unfortunately it is not. We have to adapt to the existing API, changing anything there is beyond our reach. We have three possible solutions: or we will … -
Django excel export, file is not downloading
I am trying to perform excel export functionality in Django with xls. But When I am trying to perform that file is not downloading and there is no error also. Here is my code. def excelExport(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment;filename="InitalRegistaration.xls"' work_book = xlwt.Workbook(encoding='utf-8') uc = u"".join(chr(0x0410 + i) for i in range(32)) # some Cyrillic characters u8 = uc.encode("UTF-8") work_sheet = work_book.add_sheet('Client Registration') work_sheet.write(0,0,"Clients") work_book.save(response) return response I don't know what's wrong with my code but the file is not getting downloaded nor there is the error coming from the code. -
Django: executing UPDATE query always returns rowcount 0
I'm new to programming and I'm not sure, whether the problem is in me or in the Django code. I call link method from my view and update field MatchId on Record model. Database is SQL Server 2017. My view: class RecordViewSet(viewsets.ModelViewSet): """ API for everything that has to do with Records. Additionally we provide an extra `link` action. """ queryset = Record.objects.all().order_by("Id") serializer_class = RecordSerializer permission_classes = [permissions.IsAuthenticated] @action(methods=["post"], detail=False) def link(self, request, *args, **kwargs): idToMatch = request.POST.getlist("Id") recordsToMatch = Record.objects.filter(Id__in=idToMatch) lastMatchId = Record.objects.latest("MatchId").MatchId matchedSuccesfully = recordsToMatch.update(MatchId=lastMatchId + 1) if matchedSuccesfully > 1: return Response(data=matchedSuccesfully, status=status.HTTP_200_OK) else: return Response(data=matchedSuccesfully, status=status.HTTP_404_NOT_FOUND) For some reason matchedSuccessfully always returns zero. Relevant Django code: def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows I rewrote execute_sql as follows: def execute_sql(self, result_type): … -
sending a zip file from hug framework to Django
Background: I am working on a microservice architecture, which has a Django app as a middle communicator. The services are written in hug. Problem: I am uploading a zip file in hug and trying to send it via a post request to Django application, unfortunately the file that I am receiving in hug function is byte string. and post is not able to send it mentioning following error. File "/usr/local/lib/python3.8/cgi.py", line 577, in __bool__ | raise TypeError("Cannot be converted to bool.") my hug function looks like this. def bulkUploadUserPhotos(request, file): apiURL = DJANGO_APP_URL # file is coming from a request. # error coming in below line apiResponse = requests.post( apiURL, files = file ) if apiResponse: return apiResponse.json() else: return { 'msg': 'Failed' } when I try to print file I receive following byte like data. \x8e\t\x8enH9\xa5\xa9\xfe\xa4\x8a\xf2\xeb\'\xb3g\xf7-B\xdd\x03\xbb\xab\x04\xf9\xa9\xfa\r\x0e\x88)){Pc\x94\'\xd2\xb9\xfc^Do\x83$^\x9d/2\xf4\xe7\xeb\xa3\xe1\xfd\xcd\x97\xdbF\x01\xa9=\xd6\xee\xacR\'L^W\xea\xc9\x9a\x82\xd5\xdc%\xd2\r\xeb\xf6\xb3\x93\xee\xf9\x1aJ"\x18\x17R\xe8j\xd9\xbfO\xec|\xe7L\x83V\xff\xc0\xd9\xd9\x19\xf8\xba\x84\xaa%\xf3)\\\t\x93R\x7f\x15\x95R\xa8\x9f\xb5mX<v\x19_\xa6\xeb\xdd\xa7\xbb6\r\x93D\x00\x1c\xd5\n\\\xd0`\xa3 u\xfc\xf53\x1c\x1cZ\xbb\x18\xd0\x1c~\xfc#\xf3\x81\xa5"\x90\xaaIG\x9e\xf4\xa6h\xbf\x96\xe13\xf3\x80e\x94\x9fU*\xc23vXa\xa3\xcb\x89\xa8}\xf4,\xb8Ld\xf8\x91\x1b\x8b\x82:\xa7X$2\xf9\xf2\xf7I\x9f\xb67\xab\x8b>\xe3$\xa1\x08\xb1\x14\xc3\x84\x9c\xcc=^\x8e\xbc\xf5m\x88Pn\xda\xc0\xd2\xc3&)\xabT\x07+\xf8\xf9\x12\x8d\xf0\xa4\xdf>g5R\xce\x89fD\x9d\x80\x11\x99G\xd1\xa9X\xfb\'yX\x04\xb7\x8b\x91\xcc\x99+/\xe7uZ\xff\xd8, -
Getting unique value on the base of Role
I have model name Movie which have many-to-many Relation with Actor Table. Actor Table is further many-to-many relation with Celebrity-Role. My question is i need only unique values on the base of roles Like Actors who's role is Director they show in Movie Table field with Director and only directors should be there and so on. i share my models please have a look. class CelebrityRole(models.Model): CELEBRITY_CHOICES = ( ('Actor', 'Actor'), ('Producer', 'Producer'), ('Writer', 'Writer'), ('Director', 'Director'), ) role = models.CharField(max_length=8, choices=CELEBRITY_CHOICES) def __str__(self): return self.role class Actor(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) name = models.CharField(max_length=200) rank = models.CharField(max_length=5, default=0) gender = models.CharField(max_length=6, choices=GENDER) avatar = models.ImageField(upload_to='CelebrityGallery/', blank=True) description = models.TextField(blank=True) birth_place = models.CharField(max_length=200, blank=True) dob = models.DateField(auto_now=False, auto_now_add=False) height = models.CharField(max_length=20) is_married = models.BooleanField(default=False) movies = models.ManyToManyField( 'movies.Movie', related_name='movies', blank=True) celebrity_role = models.ManyToManyField(CelebrityRole) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here is my Movie Table class Movie(models.Model): title = models.CharField(max_length=200) year = models.CharField(max_length=25, blank=True) description = models.TextField(blank=True) released = models.CharField(max_length=25) runtime = models.CharField(max_length=25) language = models.CharField(max_length=255) country = models.CharField(max_length=100) metascore = models.CharField(max_length=5, blank=True) imdb_id = models.CharField(max_length=10, blank=False, unique=True, default='tt3032400') imdb_rating = models.CharField(max_length=5, blank=True) imdb_votes = models.CharField(max_length=100, blank=True) budget = models.CharField(max_length=25) box_office = models.CharField(max_length=25, … -
Can I get a code for getting id using javascript and ajax
I am new to development and dont have much idea about this please help me, I am unable to get the code for taking id of the absent student using javascript please help me with it. This is my html code where the list of students is displayed, all student by default are present and I if i mark some student as absent all other students should be saved as present and other marked as absent which were selected HTML code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table"> <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {% for student in students %} {% if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year %} <tr> <td style="color:white;"><input type="hidden" name="student_name" value="{{student.id}}" >{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> … -
I want a free alternative. What can I use, is there?
I can't use Rds in my django database I want a free alternative what can I use And is there a way to use Rds without an AWS account -
How to customize/filter django admin panel forms data?
I created models as below; Team model stores different team names, Tournament model is used to create a tournament and add teams into it and finally Game model where I select a tournament, add two teams and create a game. My problem is in Admin panel, while creating a game after selecting a tournament I have to select two teams, in the choice list I am getting all the available teams in the Teams database, instead of just the teams participating in the tournament. class Team(models.Model): name = models.CharField(max_length=30) # Ind, Pak, Aus, Sri, Eng class Tournament(models.Model): name = models.CharField(max_length=50) # Asia Cup: teams = models.ManyToManyField(Team) # Ind, Pak, Sri class Game(models.Model): name = models.CharField(max_length=50) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) # Asia Cup teams = models.ManyToManyField(Team) # Expected: Ind, Pak, Sri My Admin panel customization: class TeamInline(admin.TabularInline): model = Game.teams.through class Game(admin.ModelAdmin): fields = ['name'] inlines = [TeamInline] -
Django CMS - How to add background image in cms
I have been using placeholder to change images and text in html template like this {% block newsimage %} {% placeholder "newsimage" %} {% endblock newsimage %} But in one particular html file the background image have been called from class using css for example- html <div class="container"> In css .container { background: url(../images/sample.jpg); background-size: cover; background-repeat: no-repeat; height: 468px; } So That I cant able to add placeholder for this image how can i add background image for this template in django cms? -
Vs code could not fint models values in django
My models.py: class Service(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) name = models.CharField(max_length=255) price = models.CharField(max_length=255, null=True, blank=True) And my views.py: service = Service.objects.get(id=pk) When I want to show which values have in Service object, Vs code doesnt prompt list of values. For instance, When I tpye id=pk, na, it must prompt value name of models Which extension Have to I install? -
Updating or saving a form field using cleaned_data in Django not working
It is simple, but I don't know why it is not working! I just want to set my TOTAL field from the form with the PRE-TOTAL value. It is updating my FORM_DATA (instance using cleaned_data), but not saving! It is still coming with the default value!!! Would someone tell me why? Here go the codes: MODELS.PY from django.db import models from django.utils import timezone class av_pomades(models.Model): cod_prod = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) price = models.FloatField(default=0) pic = models.ImageField(default='default.jpg', blank=True) def __str__(self): return self.name pomades_to_chose = ( ('Suavecito - water based','Suavecito - water based'), ('Reuzel Blue - water based','Reuzel Blue - water based'), ('Layrite - water based','Layrite - water based'), ('Suavecito - oil based','Suavecito - oil based'), ('Reuzel Pink - Oil Based','Reuzel Pink - Oil Based'), ('Layrite - oil based','Layrite - oil based') ) class order_form(models.Model): pomade = models.CharField(max_length=100, choices=pomades_to_chose) amount = models.PositiveIntegerField() ord_date = models.DateField(default=timezone.now) total = models.FloatField(default=0) def __str__(self): return self.pomade FORMS.PY from dataclasses import fields from tabnanny import verbose from django import forms from . import models class order_forms(forms.ModelForm): class Meta: # model that the fields will come from model = models.order_form # chosing the fields to be displayed fields = ['pomade', 'amount', 'total'] VIEWS.PY from django.shortcuts import … -
"Django-filter" Is it possible to use FilterClass(FilterSet) MultipleChoiceFilter within ViewSet methods? Django 1.11, Python 2.7
I have my class ClassFilter(FilterSet) with some of the Filters fx. MultipleChoiceFilter, ModelMultipleChoiceFilter etc. in it: class ClassFilter(FilterSet): something_severity = MultipleChoiceFilter(choices=Something.SEVERITY_CHOICES, method='something_severity_filter', widget=CSVWidget) def something_severity_filter(self, queryset, name, severities): if severities: queryset = queryset.filter(something_state=Something.STATE_SOMETHING) ... return queryset class Meta: model = Something fields = [] It works perfect when it comes to filtering endpoints. It is assigned to the class like: class ClassViewSet(mixins....., DefaultApiViewSet): filter_class = ClassFilter by having filter_class = ClassFilter. Everything works just fine but now I am in in doubts if I may use the ClassFilter MultipleChoiceFilter within ClassViewSet methods. This means by executing POST method in ClassViewSet, I want to get the MultipleChoiceFilter from FilterClass to filter on my method by getting it as SomethingFilter.get_filters() method @action(detail=False, methods=['post']) def something_update(self, req): ... all_filters = SomethingFilter.get_filters() for serializer_filter in serializer_filters: for filter in all_filters: if(serializer_filter == filter): f = all_filters[filter] Now the f is a filter which I require so that is MultipleChoiceFilter. But when I try to filter with that filter it throws an error. f.filter(queryset, [('LOW')]) #filter the queryset with the filter based on LOW choice Throws: assertionError: Filter 'something_severity' must have a parent FilterSet to find '.something_severity_filter()' In documentation for django-filter it is exactly line: … -
Django custom foreign key representation
If i have two models class Parent(models.Model): attribute_1 = .... attribute_2 = .... class Child(models.Model): parent = models.ForeignKey(Parent) Django by default will do lazy fetching to parent as it will hit the database when i try to access attribute_1 or attribute_2, so how can I make it fetch them by default for this specific use case -
Django templates not picking static files
Following is the my static folder structure: ProjectABC - App1 - App2 - App3 - ProjectABC - resources - static - imgs - css - templates This is how the project structure looks like. This is how the static configuration in settings.py looks like: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) This is how the base.html looks like: <!doctype html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, maximum-scale=1, initial- scale=1, user-scalable=0"> <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"> <link rel="stylesheet" href="https://fonts.googleapis.com/css? family=Open+Sans:400,600,800"> <title>{{SITE_NAME}}</title> <link rel='shortcut icon' href= "{% static 'img/favicon.png' %}"/> <link href="{{STATIC_URL}}css/application.css" media="screen" rel="stylesheet" type="text/css" /> <link href="{{STATIC_URL}}css/style.css" media="screen" rel="stylesheet" type="text/css" /> <script src="{{STATIC_URL}}js/application.js" type="text/javascript"></script> {% block extracss %} {% endblock %} </head> <body> <div class="container"> <h1>Hello</h1> </div> </body> </html> All the static files are being loaded as seen in terminal, but in browser its just loading bare html without any css or img: Please lemme know if i am missing something. Thnk You! -
Problem in deploying Django website on Cyber Panel
I have deployed the Django website on openlite server and cyberpanel. According to the documentation of the cyberpanel, there is no requirement to run the server manually. The default page of cyberpanel will be removed automatically once the Django website will be there. But in my case, that default page is still there. As this is not working, I tried it by executing the following command: python manage.py runserver example.com:8000 After this, the website is working only on port 8000 i.e. "https://example.com:8000", but not on "https://example.com". I have tried configuring all the settings in settings.py like setting the allowed host to ["*"] and also configuring the configurations of vhost in cyberpanel but still it is not working. Can anyone help please ? -
Not able to get current logged in user in django model
I am trying to get current logged in user through my model so that I can only see the current user in my order page dropdown: I have gone through a lot of documents which state that it is not that easy or feasible to get current logged in user in model. I have tried other method like getting AUTH_USER_MODEL but it is returning admin level users as well so not solving the problem. I am also sending the current logged in user from my views file but dont know how to access it inside form class, able to access it in init but dont know how it can be accessed in class. models.py : from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model from django.http import HttpResponse,HttpRequest class Customer(models.Model): name = models.CharField(max_length=200,null=True) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL) #customer = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL) date_ordered = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=20,default= 'PENDING') def __str__(self): return str(self.customer.id) forms.py : class createorderform(ModelForm): def __init__(self,*args,**kwargs): self._instance=kwargs.pop('instance',None) super().__init__(*args,**kwargs) #def __init__(self,instance): # self.user = instance # super().__init__(instance) class Meta: model=Order fields="__all__" exclude=['status'] Views.py def … -
Set the value of a field in a model as the value of a field in another model in django
I have a two model field one which is the user model and one which is the landlord model. I want the first_name and last_name of the user model to be saved also in the landlord model. This is my model view pass class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) nin = models.IntegerField(unique = True , null=True) avatar = models.ImageField(null= True, default="avatar.svg") objects = UserManager() class Landlord(models.Model): user = models.OneToOneField(User, null= True, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.EmailField(unique = True , null=True) bio = models.TextField(null=True) nin = models.IntegerField(unique = True , null=True) avatar = models.ImageField(null= True, default="avatar.svg") USERNAME_FIELD = 'email' REQUIRED_FIELDS= [] objects = User() def __str__(self): return str(self.user)``` -
How to run Django new project in the same VS code folder which already has a project that is running on every runserver Port?
I created two projects baseproject and web_project using django in vs code folder: smcode5 with virtual environment. I used web_project first to create an app and run on server port 8000. Now I want to use baseproject for an app, but only web_project runs. Any suggestions? -
populating foreign key in django
I'm creating a page that lets only admin add some assets. Each asset has a type. I have used a dropdown to select the asset_type. The selected value of asset_type gets passed into views.py but I can't get it written into the newly created asset object. Here is my models.py class assetType(models.Model): title = models.CharField(max_length=150) @property def get_type(self): return asset.objects.filter(asset_type=self.id) def __str__(self): return f"{self.title}" class Meta: verbose_name_plural = 'Asset Types' class asset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False) asset_type = models.ForeignKey('assetType', on_delete=models.CASCADE, null=True) asset_name = models.CharField(max_length=30, null=True) #unique=True location = models.CharField(max_length=30, null=True) brand = models.CharField(max_length=30, null=True) purchase_year = models.PositiveIntegerField(blank=True, null=True) isActive = models.BooleanField(default=True, null=True) currentOwner = models.ForeignKey(User, default='', null=True, on_delete=models.CASCADE) Here is createAssetView from views.py @user_passes_test(lambda u: u.is_superuser) def createAssetView(request): assetTypeList = assetType.objects.all() # use assetType.title assettype = request.POST.get('asset-type') assetname = request.POST.get('asset-name') locationn = request.POST.get('location') brandd = request.POST.get('brand') purchaseyear = request.POST.get('purchase-year') isActivve = request.POST.get('is-active','') == 'on' cuser=request.user context={ "cuser":request.user, "asset_type_list":assetTypeList, "asset_type":assettype, "asset_name":assetname, "location":locationn, "brand":brandd, "purchase_year":purchaseyear, "isActive":isActivve, 'iterator':range(2014,2050) } if request.method == 'POST': new_asset = asset() new_asset.asset_type_title=request.POST.get('asset-type') new_asset.asset_name=assetname new_asset.location=locationn new_asset.brand=brandd new_asset.purchase_year=purchaseyear new_asset.isActive=True if isActivve else False new_asset.currentOwner=cuser print(assettype) # PRINT assettype new_asset.save() return redirect('createAssets') return render(request, 'assets/createAsset.html', context) The PRINT assettype statement prints selected asset type from the form, so the … -
IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id
I'm trying to implement a comment section in my blog that looks as follows: I don't have a user or post name input because it should take as input the request user and the post ID of the post where it's making the comment. My Comment model: class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) approved_comment = models.BooleanField(default=False) class Meta: ordering = ['-created_on'] def __str__(self): max_len = 75 if len(self.body) > max_len: string = self.body[:max_len] + "..." else: string = self.body return string Comment form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) exclude = ['user', 'post', ] View function: def get_post_details(request, post_id): unique_post = Post.objects.get(id=post_id) all_comments = Comment.objects.filter(post=unique_post) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=True) new_comment.post = unique_post new_comment.user = request.user new_comment.save() return get_post_details(request, post_id) else: comment_form = CommentForm() context_dict = { 'post': unique_post, 'comments': all_comments, 'new_comment': new_comment, 'comment_form': comment_form } return render(request, 'blog/post_details.html', context=context_dict) I'm not sure what's missing, but when I try to add a comment I get the below error: IntegrityError at /blog/5 NOT NULL constraint failed: blog_comment.post_id I've searched all over stackoverflow and the issue … -
Does django supports frontend pagination?
In brief sight, to use django's Paginator class, we need to paginate from backend. But most of web pages are doing pagination at frontend. Is it possible doing frontend pagination with django's Paginator? Or should I just give it up and use datatables with giving all data to client? -
How to convert web URL data to JSON format
I am mobile application developer. I want to try to get web URL data in JSON format. I have try to build image aggregator application. https://yandex.com/images/search?rpt=imageview&url=https%3A%2F%2Favatars.mds.yandex.net%2Fget-images-cbir%2F1973508%2FEArWpseFrv-9jTLCuEUwTw5291%2Forig&cbir_id=1973508%2FEArWpseFrv-9jTLCuEUwTw5291 I am trying this URL data in JSON format like our REST API response. Is it possible to convert JSON data of this URL. I have also knowledge of Django framework. If it is not possible from front end using android studio then please share me possibility of Django. Thank you