Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset get all data that pass a selected date
I created an object from a model call Project which look like this : [ { "name": "project A" "start_date": 2019-01-01 "end_date": 2019-02-15 }, { "name": "project B" "start_date": 2019-01-15 "end_date": 2019-02-01 }, { "name": "project C" "start_date": 2019-02-27 "end_date": 2019-03-12 }, ] if I have a date range selector and I select the date from 2019-01-07 until 2019-02-10, and my query look like this model_object = Project.objects.all().filter(start_date__gte=(2019-01-07), end_date__lte=(2019-02-10)) The result of model_object queryset will be : { "name": "project B" "start_date": 2019-01-15 "end_date": 2019-02-01 }, What I wanted now is how can I filter the query in such way where I get all the object that is ongoing in between the date 2019-01-07 until 2019-02-10 which mean the result should also include project A because its still ongoing from 2019-01-01 until 2019-02-15 even though it started before 2019-01-07 Any help is much appreciated thanks. -
how to select fields in related tables quickly in django models
I'm trying to get all values in current table, and also get some fields in related tables. class school(models.Model): school_name = models.CharField(max_length=256) school_type = models.CharField(max_length=128) school_address = models.CharField(max_length=256) class hometown(models.Model): hometown_name = models.CharField(max_length=32) class person(models.Model): person_name = models.CharField(max_length=128) person_id = models.CharField(max_length=128) person_school = models.ForeignKey(school, on_delete=models.CASCADE) person_ht = models.ForeignKey(hometown, on_delete=models.CASCADE) how to quick select all info i needed into a dict for rendering. there will be many records in person, i got school_id input, and want to get all person in this school, and also want these person's hometown_name shown. i tried like this, can get the info i wanted. And any other quick way to do it? m=person.objects.filter(person_school_id=1) .values('id', 'person_name', 'person_id', school_name=F('person_school__school_name'), school_address=F('person_school__school_address'), hometown_name=F('person_ht__hometown_name')) person_name, person_id, school_name, school_address, hometown_name if the person have many fields, it will be a hard work for list all values. -
How to create a custom list field when using Django Rest Framework
I have the following model and I would like to add a custom field called choices which will be a list of choices. class HPIQuestionBank(models.Model): label = models.CharField( max_length=200, db_index=True, blank=True, null=True) template = models.ForeignKey( HPIFilter, blank=True, null=True, on_delete=models.CASCADE, default='') I have implemented the following in the serializers. class CheckBoxesListField(serializers.ListField): child = serializers.CharField(allow_null = True, allow_blank=True) class TemplateQuestionBankSerializer(serializers.ModelSerializer): answer_type = serializers.CharField(allow_null = True, allow_blank=True) checkboxes = CheckBoxesListField() hpianswers_set =TemplateAnswerSerializer(many=True) class Meta: model = HPIQuestionBank fields = ['id','label','hpianswers_set','answer_type','checkboxes'] I'm using the serializer on my GET method. When I attempt to make a request I get the following error: AttributeError at /api/clinic2/history/template/6/ Got AttributeError when attempting to get a value for field `checkboxes` on serializer `TemplateQuestionBankSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `HPIQuestionBank` instance. Original exception text was: 'HPIQuestionBank' object has no attribute 'checkboxes'. -
How to use Python iteration to read paragraphs, tables and pictures in word?
So far, I've found a way to read paragraphs and tables in word sequentially and iteratively, but I'm stuck with how to read pictures sequentially. I would like to ask you to help me on the basis of the original code to achieve how the sequence of iteration word pictures? Here is my current code from docx.document import Document as _Document from docx.oxml.text.paragraph import CT_P from docx.oxml.table import CT_Tbl from docx.table import _Cell, Table, _Row from docx.text.paragraph import Paragraph import docx path = './test.docx' doc = docx.Document(path) def iter_block_items(parent): if isinstance(parent, _Document): parent_elm = parent.element.body elif isinstance(parent, _Cell): parent_elm = parent._tc elif isinstance(parent, _Row): parent_elm = parent._tr elif isinstance(parent, InlineShapes): parent_elm = parent.part else: raise ValueError("something's not right") for child in parent_elm.iterchildren(): if isinstance(child, CT_P): yield Paragraph(child, parent) elif isinstance(child, CT_Tbl): yield Table(child, parent) elif isinstance(child, InlineShapes): yield for block in iter_block_items(doc): # 读取段落 if isinstance(block, Paragraph): print(block.text) # 读取表格 elif isinstance(block, Table): print(block.style.name) -
Overriding ModelForm with widgets
A user has a form where he can save sensitive data. I am capable of crypting this data and store it in the database using modelforms. However, if the user wants to modify this data, it appears in the TextInput from the form. I've read this post, and this one. The answer seems to be there, but I can't manage to suceed in the implementation. Here is what I have: Models class CustomUser(AbstractUser): api_key = models.CharField(max_length=256, default='null') Forms class APIForm(forms.ModelForm): class Meta: model = CustomUser fields = ('api_key') widgets = { 'api_key': TextInput(attrs={'size': 10, 'placeholder': 'Your key'}), } Html <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Save changes</button> </form> It seems that the form is not detecting the widget, since if I change the value of the attribute size, the form will not change. Am I missing something? Thanks in advance -
Cannot set MODEL_NAME SpatialProxy (POLYGON) with value of type: <class 'django.contrib.gis.geos.polygon.Polygon'>
When I trying to go on api's url of one my model I face with this: Cannot set Allotment SpatialProxy (POLYGON) with value of type: I check my model definition, and data type in PGadmin. full log Traceback: File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/viewsets.py" in view 103. return self.dispatch(request, *args, **kwargs) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 483. response = self.handle_exception(exc) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception 443. self.raise_uncaught_exception(exc) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 480. response = handler(request, *args, **kwargs) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/mixins.py" in list 42. page = self.paginate_queryset(queryset) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/generics.py" in paginate_queryset 173. return self.paginator.paginate_queryset(queryset, self.request, view=self) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/rest_framework/pagination.py" in paginate_queryset 337. return list(queryset[self.offset:self.offset + self.limit]) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/models/query.py" in __iter__ 272. self._fetch_all() File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all 1179. self._result_cache = list(self._iterable_class(self)) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/models/query.py" in __iter__ 63. obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/models/base.py" in from_db 507. new = cls(*values) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/db/models/base.py" in __init__ 424. _setattr(self, field.attname, val) File "/home/user/MyProjects/forest-venv/lib/python3.5/site-packages/django/contrib/gis/db/models/proxy.py" in __set__ 75. instance.__class__.__name__, gtype, type(value))) Exception Type: TypeError at /api/cutarea-allotment/ Exception Value: Cannot set Allotment SpatialProxy (POLYGON) with value of type: <class 'django.contrib.gis.geos.polygon.Polygon'> There is … -
In-line editing of data in front end
i am trying to develop a web application in which i want inline editing at front end so that user can make changes and the changes gets updated into the database. Models.py from django.db import models from enumfields import EnumField from enumfields import Enum class Choice(Enum): Not_In_Production = 'NP' In_Production = 'IP' On_The_Way = 'OW' In_WareHouse = 'IW' class Choice2(Enum): In_Production = 'IP' On_The_Way = 'OW' In_WareHouse = 'IW' class Item_Table(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=127) description = models.TextField() qty = models.IntegerField() total_sales = models.IntegerField() qty_in_warehouse = models.IntegerField() status = models.BooleanField() Item_Type = models.CharField(max_length=80) ListID = models.CharField(max_length=80) Income_Account = models.CharField(max_length=80) Cogs_Account = models.CharField(max_length=80) Asset_Account = models.CharField(max_length=80) def __unicode__(self): return self class Order_Table(models.Model): id = models.AutoField(primary_key=True) order_number = models.CharField(max_length=63) notes = models.TextField() created_at = models.DateTimeField() status = EnumField(Choice,max_length=2) Total_Amount = models.DecimalField(max_digits=18,decimal_places=2) Customer_ID = models.IntegerField() TXN_ID = models.CharField(max_length=80, null=True,blank=True) Tax_Amount = models.DecimalField(max_digits=18,decimal_places=2) def __unicode__(self): return self View.py from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect from .models import * def item(models.Model): items = Item_Table.objects.all() context = {'items': items, } return render(request, 'home.html',context) def order(models.Model): items = Order_Table.objects.all() context = {'items': items, } return render(request, 'home1.html',context) Html <table id="common-table" class="table table-bordered table-hover display"> <thead> <tr> <th>Item</th> <th>Order Number</th> <th>Total Sales</th> <th>Qty</th> <th>Amount</th> … -
DB not updated on serializer.save()
I am trying to build a api for updating first and last name for my user. The api runs successfully but database is not updated which is the expected behavior I have written the following API and trying to pass the patch request to it. class UserSelfUpdateView(UpdateAPIView): serializer_class = UserUpdateSerializer permission_classes = [UserPermissions, ] def update(self, request: Request, *args, **kwargs): instance = User.objects.filter(id=self.request.user.id) serializer = UserUpdateSerializer(instance, data=request.data,) serializer.is_valid(raise_exception=True) serializer.save() return Response({'success': True}, status=status.HTTP_200_OK) The serializer for the above request is: class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields: ('id', 'first_name', 'last_name') The format in which I am trying to pass my request body is: { "first_name": "A", "last_name": "B" } and this is how my model is defined: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=False) last_name = models.CharField(_('last name'), max_length=30, blank=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return … -
How to calculate the total price of products just by increasing quantity?
I have custorder models in which im taking product and price as foreign key from other models Product and price . I want to calculate the total price of product just by increasing quantity. Im just building a rest api for order creation . Please help me how to do it. Models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) product = ArrayField(models.CharField(max_length=200, blank=True)) def __str__(self): return str(self.product) class Price(models.Model): product = models.ForeignKey('Product',on_delete=models.CASCADE) price_id = models.AutoField(primary_key=True) price = models.DecimalField(max_digits=50, decimal_places = 5, default=0) def __str__(self): return "%s" % self.price class CustOrder(models.Model): Customer_id = models.AutoField(primary_key=True) CustomerName = models.CharField(max_length=200) email = models.EmailField(max_length=70,blank=True, null= True, unique= True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES) phone = PhoneField(null=False, blank=True, unique=True) landmark = models.PointField() #landmark = models.TextField(max_length=400, help_text="Enter the landmark", default='Enter landmark') houseno = models.IntegerField(default=0) #product_name = models.CharField(max_length=200, choices=PRODUCT_CHOICES,default='Boneless chicken') # product_id = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='custorder_productid') product = models.ManyToManyField(Product, blank=True,related_name='pricetag') quantity = models.IntegerField(default=0) # price_id = models.ForeignKey(Price) price = models.ForeignKey(Price, on_delete=models.SET_NULL, null=True,related_name='pricetag') #price = models.DecimalField(max_digits=50, decimal_places=5, default=48.9) pay_method = models.CharField(max_length=200,choices=PAYMENT_CHOICES, default='RAZOR PAY') city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) def str(self): return self.CustomerName -
Google sign-in using android-studio front-end and django back-end
I am totally new to django and android studio. I am developing an app on android studio and as part of it, I added a Google Sign-in mechanism. The sign-in in the front-end - works just fine, and I'm able to hold the user's TokenId. Here is a quick summary of what I'm trying to do - In my application, I want users to have points that will be saved on the server. to do so, I'm using Google sign in. Now, in the server, I want to have a table that connects each user with his score, so It can be updated according to the user's activity. Now, I want to establish a session with my django server. I read in the django book and all I could find is references to django authentication system - which I don't want to use, as I'm using Google's sign-in. My questions are: I read this (link) and I saw that once I pass the TokenId from the front-end to the server, I need to do some verification - and once I'm done, I hold this: userid = idinfo['sub'] Now, I want to create a table that recognizes the users - do … -
how to retrieve first app model data in second app in Django
how to retrieve first app model data in second app in Django. I create a model scheme_details_model in trible app and I have to display field "scheme_title" to the home1.html of the theme. ## this is model in trible app class scheme_details_model(models.Model): scheme_id = models.CharField(max_length=200,blank=False, null=True) scheme_title = models.CharField(max_length=200, default='') publish_on = models.CharField(max_length=200, default='') detail_description = models.CharField(max_length=200, blank=False, null=True) validity_upto = models.CharField(max_length=50, null=True, blank=True) pdf_doc_type = models.FileField(upload_to="driver_file/",validators=[validate_file_extension],null=True) source_url = models.CharField(max_length=100, null=True, blank=True) created_date = models.DateTimeField(default=datetime.now, blank=True) modified_date = models.DateTimeField(auto_now=True) class Meta: db_table = "scheme_details_table" ##view function in theme app from django.contrib.auth.decorators import login_required from django.shortcuts import render from DigitalMine.tribal.models import scheme_details_model @login_required def home(request): book = scheme_details_model.objects.all() data = {} data['object_list'] = book print(data) return render(request, "home1.html") display "scheme_title" field as a link to redirect to another page -
Get selected database inside migration when running manage.py migrate --database=database
I have a data migration which loads entries into my database as shown below: def load_groups(apps, _): Group = apps.get_model('auth', 'Group') Group( name='Admin' ).save() Group( name='Product Manager' ).save() Group( name='Developer' ).save() migrations.RunPython( code=load_groups, ) This code works fine when running manage.py migrate. However if I run manage.py migrate --database=copy the migrations apply to the database with the alias copy but the load_groups section attempts to save to the database alias default. I know I can set where to save to group creation to, but I can't seem to find a way to access the name of the database alias being used. Any ideas would be greatly appreciated. settings.py: DATABASES = { 'default': { 'ENGINE': 'django_prometheus.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'copy': { 'ENGINE': 'django_prometheus.db.backends.mysql', 'NAME': 'dev', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': 3306, 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } -
Celery task worker not updating in production
I have set up a django project on an EC2 instance with SQS as broker for celery, running through Supervisord. The problem started when I updated the parameter arguments for a task. On calling the task, I get an error on Sentry which clearly shows that the task is running the old code. How do I update it? I have tried supervisorctl restart all but still there are issues. The strange thing is that for some arguments, the updated code runs while for some it does not. I checked the logs for the celery worker and it doesn't receive the tasks which give me the error. I am running -P solo so there is only one worker (Ran ps auxww | grep 'celery worker' to check). Then who else is processing those tasks? Any kind of help is appreciated. -
In localhost it runs fine, but when trying to be deployed to aws (eb deploy) gives out the following error:
INFO: Deploying new version to instance(s). ERROR: [Instance: i-0a71c104c0eea1e7c] Command failed on instance. Return code: 1 Output: (TRUNCATED)...on/run/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib64/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named import_export. -
"Expected a list of items but got type \"dict\"."
I am trying to build a api for updating first and last name for my user. I am getting the following error in HTTP Response { "non_field_errors": [ "Expected a list of items but got type \"dict\"." ] } I have written the following API and trying to pass the patch request to it. class UserSelfUpdateView(UpdateAPIView): serializer_class = UserUpdateSerializer permission_classes = [UserPermissions, ] def update(self, request: Request, *args, **kwargs): instance = User.objects.filter(id=self.request.user.id) serializer = UserUpdateSerializer(instance, data=request.data, many=True) serializer.is_valid(raise_exception=True) serializer.save() return Response({'success': True}, status=status.HTTP_200_OK) The serializer for the above request is: class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields: ('id', 'first_name', 'last_name') The format in which I am trying to pass my request body is: { "first_name": "A", "last_name": "B" } The reason for using instance = User.objects.filter(id=self.request.user.id) is because I want the functionality in a way that only logged in user is able to modify his details only. -
My page is not reflecting any css styling changings I make
My page is not loading css correctly. I am learning django framework for building websites. I am trying to style my page with css. I have gone through the tutorial for managing static files in django. I have done every step mentioned. I am trying to display a jumbtron with a purple background and white text. The code is below. Only the text changes to white but background remains the same. I have had this problem for days. I have searched on the internet but didn't find any answer {% block styles %} <style> .jumbotron{ background: purple; color: white; } </style> {% endblock %} {% block content %} <div class="jumbotron"> <h1>Dummy content for testing</h1> </div> {% endblock %} -
Pushing data to firebase using django pycharm
I am new to django. The ide I'm using is Pycharm. I have a signup form in signin2.html. I want to be able to get connected to my database and save the values in users_info table.There are 2 fields in users_info, email and password. I have given the database name as 'users'. I do have one problem with the authentication , I do not want the users who get registered in my site to be able to access the database manually . Only admin email address should have that access . I have provided what I have written so far. Please help me with the connections. I cant seem to push the data to the database. signin2.html <form action="/postsign/" method="post"> {% csrf_token %} <div class = "login-box"> <h1>Welcome</h1> <div class = "textbox" style="float:left"> <input type = "email" placeholder="Email" name = "email" id="email"> </div> <div class = "textbox"> <input type = "password" placeholder="Password" name ="pass" id="password"> </div> <div class="btn"> <input type="submit" placeholder="Login" value="SignIn"> </div> </div> </form> urls.py url(r'^postsign/', views.postsign), views.py config = { 'apiKey': "AIzacccccccccccccccccchskd9vlxvM", 'authDomain': "wccccccca.firebaseapp.com", 'databaseURL': "https://wcccccca.firebaseio.com", 'projectId': "wccccccda", 'storageBucket': "weccccccccccda.appspot.com", 'messagingSenderId': "56444444444834" } firebase=pyrebase.initialize_app(config) def signin2(request): return render(request,"signin2.html") def postsign(request): email = request.POST.get('email') passw = request.POST.get("pass") database = … -
Prevent a ValueError when I don't upload an image in my Djago blog post
I have this model: class News(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) thumb = models.ImageField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('news_detail', args=[str(self.id)]) If I add a blog post and include an image, everything is fine. If I don't include an image and try to view the post in my browser I get this error: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) ValueError: The 'thumb' attribute has no file associated with it. [01/Apr/2019 08:11:48] "GET /news/ HTTP/1.1" 500 178129 I thought blank=True would prevent any errors if I didn't include an image. I also tried thumb = models.ImageField(blank=True, null=True) based on this question but it made no difference. How can I have the option of uploading an image or not uploading an image in my blog post without getting an error? -
How to create a serializer and a view to create a sub-category in django and djangorestframework
I have created three classes 1. Programme - parent - example Bachelor of Arts(BA) 2. Semester - child - first semester- child of programme 3. Course - grand child - Chemistry-1, child of semester Detail: 1) There will be many semester under the programme, link using foreign key 2) There will be many courses under semester. How to implement this behavior in djangorestframework. 1) Create a course under a semester 2) to list all the courses under a programme and semester class Programme(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Semester(models.Model): name = models.CharField(max_length=100) numeric = models.IntegerField() programme = models.ForeignKey(Programme, on_delete=models.CASCADE) def __str__(self): return self.name class Course(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=200) semester = models.ForeignKey(Semester, on_delete=models.CASCADE,related_name='courses') internal = models.IntegerField() external = models.IntegerField() total = models.IntegerField() def __str__(self): return self.name -
Best practice for adding a new item in client
I have a list that the client fetches from the server. The client can add more items, and it's 'auto save' so no need to press a button. My question is how to manage the new item id (can be several). Do I need to immediately go to the server to get a new key? or can I allocate some key Ids (say 0-10) and later in the auto save call the server will know to assign new keys and notify the client? Thank you -
How to point Django .html to S3 media file? AccessDenied
I can upload files to the S3 bucket from my django app using the models admin view. I can also view the video within my django app admin view. But I am not able to view the video via the django .html file. Here is my models.py file from project_4.storage_backends import MediaStorage class video(models.Model): videofile = models.FileField(storage=MediaStorage(), null=True, verbose_name="", unique=True) I created a storage_backends.py under my app project folder from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = settings.AWS_MEDIA_LOCATION default_acl = 'private' # To turn access control list into private use only. Will use it in models.py file_overwrite = False # Not to replace files even they have same name custom_domain = False In my settings.py I added the following import boto3 from botocore.client import Config MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS_ACCESS_KEY_ID = 'x' AWS_SECRET_ACCESS_KEY = 'x' AWS_STORAGE_BUCKET_NAME = 'django-draft-project-1' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = "eu-central-1" AWS_S3_SIGNATURE_VERSION = "s3v4" # AWS S3 Private Media Upload AWS_MEDIA_LOCATION = 'media' PRIVATE_FILE_STORAGE = 'project_4.storage_backends.MediaStorage' AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=94608000', } At this point, I am able to upload and view my video through … -
How to tell to client that Django web application is in healthy state or not (status 200)
I have written a Django web application and also supported REST API to get JSON response. Now I want to write some health endpoint ( some url ) which is when used, my django web application should tell whether or not it is in healthy state. Example, If my Django application is not running ( web server is down ), then if a rest api client tries accessing the health endpoint (URL) and it should get response telling application is not healthy. On the other hand if application is running/up ( web server is up ) then accessing the health endpoint will show message that application is healthy. Is it doable in Django ? Thanks in advance. -
Unable to view django project - development server
on running the the dev server 0.0.0.0:8000 on server , i cannot see the website load on the browser. While going thru some of the reason why this might happen , i have done the following changes: -ALLOWED_HOSTS = ['*'] -Killed all processes on 8000 -firewall turned off Server I am working on is RHEL. System check identified no issues (0 silenced). April 01, 2019 - 04:39:38 Django version 2.1.7, using settings 'gig_bank.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. //Nothing is displayed on browser. -
Convert ratings in stars in Django template
I'm working on a project using Python(3.7) and Django(2.1) in which I want to display an average rating returns from a view inside the Django template. Here's What I have tried so far: From models.py: class Gig(models.Model): CATEGORY_CHOICES = ( ('GD', 'Graphic & Design'), ('DM', 'Digital Marketing'), ('WT', 'Writing & Translation'), ('VA', 'Video & Animation'), ('MA', 'Music & Audio'), ('PT', 'Programming & Tech'), ('FL', 'Fun & Lifestyle'), ) title = models.CharField(max_length=500) category = models.CharField(max_length=255, choices=CATEGORY_CHOICES) description = models.CharField(max_length=1000) price = models.IntegerField(blank=False) photo = models.FileField(upload_to='gigs') status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class GigReview(models.Model): RATING_RANGE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) user = models.ForeignKey(User, on_delete=models.CASCADE) gig = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='rates') order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) rating = models.IntegerField(choices=RATING_RANGE,) content = models.CharField(max_length=500) def __str__(self): return self.content From views.py: def home(request): gigs = Gig.objects.filter(status=True).annotate(avg_review=Avg('rates__rating')) return render(request, 'home.html', {'gigs': gigs}) So, now every gig has an average rating and I want to display stars as the rating inside the template. From home.html: {% for gig in gigs %} <div data-marker-id="59c0c8e33b1527bfe2abaf92" class="col-sm-6 col-xl-4 mb-5"> <div class="card h-100 border-0 shadow"> <div style="background-image: url(/media/{{ gig.photo }}); min-height: 200px;" class="card-img-top overflow-hidden dark-overlay bg-cover"> <a … -
Django 2.1 Site With Two (or more) Language
I am currently researching a solution or approach to the following problem. We need a site that will operate in at least two different languages. The site is Django 2.1-based and uses DjangoCMS. It will have a multi-language blog-like capability in which articles will be published in different languages. Videos will also be posted there. We would like to have an ability to post separate content to different (language) sides of the site. The user will be able to select their language preference in the navigation bar and that version of the site will be served to him from there on. It appears that we would like to have to have two different sets of paths along the lines of www.example.com/lang1/* www.example.com/lang2/* That is, each (or most) pages will be present on both language side and the only difference between the paths will be the language prefix. That said, the slugs would need to be in the native language, if that matters at this point. This is a vision, but it is certainly negotiable. While doing the research, I have found questions like this which have been helpful: Django site with 2 languages However, it appears that I am still …