Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cropper.js is rotating the elongated portrait images in mobile view
Hi I have been following this tutorial for making cropper.js worked in my Django app. The issue is, that whenever I try to upload an image in mobile view the canvas rotates the image. Like this: Can anyone please point out what the issue is and how can I prevent this? -
How to Upgrade Amazon Elastic Beanstalk Linux 1 to Linux 2 for Django Application
I am trying to upgrade a Django application from AWS Elastic Beans Python 3.6 running on 64bit Amazon Linux/2.9.20 to Python 3.8 running on 64bit Amazon Linux 2/3.2.0. It runs locally. When I try and deploy to Elastic Beanstalk I'm getting the following error: Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/current/src/core/wsgi.py", line 14, in <module> Apr 6 10:30:48 ip-172-31-43-9 web: application = get_wsgi_application() Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application Apr 6 10:30:48 ip-172-31-43-9 web: django.setup(set_prefix=False) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/__init__.py", line 19, in setup Apr 6 10:30:48 ip-172-31-43-9 web: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ Apr 6 10:30:48 ip-172-31-43-9 web: self._setup(name) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup Apr 6 10:30:48 ip-172-31-43-9 web: self._wrapped = Settings(settings_module) Apr 6 10:30:48 ip-172-31-43-9 web: File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ Apr 6 10:30:48 ip-172-31-43-9 web: mod = importlib.import_module(self.SETTINGS_MODULE) Apr 6 10:30:48 ip-172-31-43-9 web: File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module Apr 6 10:30:48 ip-172-31-43-9 web: return _bootstrap._gcd_import(name[level:], package, level) Apr 6 10:30:48 ip-172-31-43-9 web: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Apr 6 10:30:48 ip-172-31-43-9 web: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Apr 6 10:30:48 … -
DRF OPTIONS request - include initial/default choices
I'm using options to populate select inputs in my project. Is there a way to include also information about default values? For this field: DELIVERY_METHOD__SHIPPING_ONLY = 'shipping_only' DELIVERY_METHOD__LOCAL_PICKUP_ONLY = 'local_pickup_only' DELIVERY_METHOD__SHIPPING_AND_LOCAL_PICKUP = 'shipping_and_local_pickup' DELIVERY_METHOD_CHOICES = ( (DELIVERY_METHOD__SHIPPING_ONLY, 'Shipping only'), (DELIVERY_METHOD__LOCAL_PICKUP_ONLY, 'Local pickup only'), (DELIVERY_METHOD__SHIPPING_AND_LOCAL_PICKUP, 'Shipping & local pickup'), ) delivery_method = models.CharField(max_length=32, choices=DELIVERY_METHOD_CHOICES, default=DELIVERY_METHOD__SHIPPING_ONLY) The OPTIONS actions.POST.delivery_method is this: "delivery_method": { "type": "choice", "required": false, "read_only": false, "label": "Delivery method", "choices": [ { "value": "shipping_only", "display_name": "Shipping only" }, { "value": "local_pickup_only", "display_name": "Local pickup only" }, { "value": "shipping_and_local_pickup", "display_name": "Shipping & local pickup" } ] }, But it should also say that Shipping only is the default one so I can prepopulate the input with this value. Is there a built-in way to do that? -
How to run a project in single docker container and run the installed dependencies of project in docker filesystem instead of using docker images?
I am new to docker I am noob and I have a full running application in docker consist of multiple containers responsible to run the project. I want to make the container image and gave it to the client but when I pushed my project to docker-hub it can only contain one container in the repository at a time. So, now I want to work with single container instead of using the multiple containers running MySQL and Redis as the dependencies of project. So, I installed redis and MySQL inside the docker file-system using bash of my container. But my project is not working without running my project I cannot start the redis and MySQL installed inside the container which is running on Debian Linux and when I run my project I can access the bash of my container and start the services but still my django app in the container is giving errors relevant to SQL. Can anyone tell me how to tackle this situation? -
Send Django-form to other server for data-handling
I have a Django app which is hosted on Google App Engine. One of the models consist of three fields class product_prices(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,null=True) start_price = models.FloatField(default=0) last_price = models.FloatField(default=0) data = models.TextField(max_length=512) I want to do some database calls, based on the information entered, and then alter the data-field, the last-price based on the data returned from the database, e.g in my (pseudo) view below, I call MyDatabaseFunctionCall(form) to do those calculations. What I would prefer is, to have that calculation being on another server with some more CPU/RAM such that I don't slow down GAE hosting my application. #Current views.py on GAE def add_link_to_track(request): user = request.user instance = MyModel(user=user) if request.method == "POST": form = MyForm(request.POST,instance = instance) if form.is_valid(): #Create the dummy-model form.save() #Do the calculation in the back-ground thr = threading.Thread(target=MyDatabaseFunctionCall,args=(form,),daemon=True) #Alters the data thr.start() return redirect("my_site") else: form = MyForm() return render(request, "my_site/my_template.html",context=context) Can a form-instance e.g be pickled and thus send back-n-forth between servers in some way? Or is it better having a "temp-database" that I push the form information to uppon creation and then having the compute-server monitoring that database such that it can pull new forms, alter … -
AWS resend invite link after expiration
from the boto3 documentation i came to know we need to set the MessageAction="RESEND" to resend the invitation message to a user that already exists and reset the expiration limit on the user's account. def get_set_cognito(sender, instance, *args, **kwargs): self = instance if self.pk is None: client = boto3.client('cognito-idp', region_name=settings.AWS_DEFAULT_REGION) # try: # # Check if the user exists in Cognito # existing_user = client.admin_get_user(Username=self.user.email, # UserPoolId=settings.COGNITO_USER_POOL_ID) # except client.exceptions.UserNotFoundException: # pass try: # if not existing_user: response = client.admin_create_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email, ForceAliasCreation=True|False, MessageAction='RESEND', DesiredDeliveryMediums=['EMAIL'], UserAttributes=[ { 'Name': 'custom:backend_url', 'Value': settings.BACKEND_API_URL }, { 'Name': 'custom:backend_id', 'Value': settings.BACKEND_ID }, { 'Name': 'email_verified', 'Value': 'true' }, { 'Name': 'email', 'Value': self.user.email }, { 'Name': 'family_name', 'Value': self.last_name if self.last_name else ' ' }, { 'Name': 'given_name', 'Value': self.first_name if self.first_name else ' ' }, { 'Name': 'phone_number', 'Value': self.phone if self.phone else ' ' } ], ) self.user.username = response['User']['Username'] if(len(response['User']['Username']) < 3): logger.error("empty response from cognito for email - " + self.user.email) logger.error(response) self.user.delete() else: self.user.save() # else: # self.user.username = existing_user['Username'] # self.user.save() except client.exceptions.UsernameExistsException: # existing_user = client.admin_get_user(Username=self.user.email,UserPoolId=settings.COGNITO_USER_POOL_ID) existing_user = client.admin_get_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email ) self.user.username = existing_user['Username'] self.user.save() except Exception as e: logger.error( "there was an error trying to … -
is there way to add style to username field - django forms
is there way to add style to username field - django forms , i tried use self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'}) but it's not work why class UserForm(forms.ModelForm): password = forms.CharField(required=True,label=' pass',widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':' pass ','style': 'font-size:24px;text-align: center;'})) first_name = forms.CharField(required=True,label=' first name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' first name ','style': 'font-size:24px;text-align: center;'}) ) last_name= forms.CharField(required=True,label=' 2nd name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' 2nd name ','style': 'font-size:24px;text-align: center;'}) ) email= forms.EmailField(required=True,label=' email ',widget=forms.EmailInput(attrs={'class': 'form-control','placeholder':' email ... youremail@email.com','style': 'font-size:24px;text-align: center;'}) ) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('username','first_name','last_name','email','password') def __init__(self, *args, **kwargs): super(UserForm,self).__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'}) -
What If I compile the py manage.py collectstatics?
What If I compile the py manage.py collectstatics? I am on my localhost. I have configured all the s3 url accourding to given url. We can see on last paragraph then it's telling run python manage.py collectstatic . My question is why we are doing this? Do we need to run this on every static or media changes? I tried to run this but it asking do you want to override this? Can I simply do yes? If I give yes then what will happen? I am not much aware in this topic collectstatics -
Getting wrong value when reading an xlsx file using openpyxl
i'm trying to read values from an xlsx file containing formulas using openpyxl, i noticed that for some cells i'm getting a wrong value. here's the XLSX exemple. the result i get. and the code: wb = openpyxl.load_workbook(excel_file, data_only=True) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["Feuil1"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: #cell.number_format='0.0########' print(cell.number_format) row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) -
How do i share my django models with a child process using python multiprocessing?
I am trying to pass my django models to another child process, for that i am using the following code from multiprocessing import Process from multiprocessing.managers import BaseManager from role.models import Role from group.models import Group from kafka import KafkaConsumer class KafkaProcessManager(BaseManager): pass def consume_events(kafka_ip_port, events_topic, Role, Group): # To consume latest messages and auto-commit offsets consumer = KafkaConsumer(events_topic, bootstrap_servers=[kafka_ip_port]) for message in consumer: print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition, message.offset, message.key, message.value)) #if (message["MODEL"] == "UserFeature" and message["TYPE"] == "DEACTIVATED"): group = Group.objects.get(id=1) group.description = "UPDATED AFTER CONSUMING EVENT THROUGH CHILD PROCESS" group.save() kafka_manager = KafkaProcessManager() kafka_manager.register('Role', Role) kafka_manager.register('Group', Group) kafka_manager.start() Role = kafka_manager.Role() consumer = Process(target=consume_events, args=(kafka_ip_port, events_topic, Role, Group, )) consumer.start() consumer.join() The intention is to do some processing/updating when a certain message (event) is receieved. But i am getting an error on line Role = kafka_manager.Role() AttributeError: Manager isn't accessible via Role instances. Can anyone guide me how to pass the model instances to the child process. Thanks is advance. -
Django REST framework POST without insert
I'm building a Django REST API which has access to our existing database with existing users. The purpose of this API is allowing the upcoming mobile application to make requests. I'm sending a post request to a view with custom authenticator to verify the sent account details. My existing model: class LogonAccount(models.Model): id = models.BigIntegerField(primary_key=True) email = models.TextField() two_step_enabled = models.BooleanField() password = models.TextField(blank=True, null=True) username = models.TextField(unique=True, blank=True, null=True) My View and Serializer class LogonAccountViewSet(viewsets.ModelViewSet): queryset = LogonAccount.objects.all().order_by('username') serializer_class = LogonAccountSerializer class LogonAccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = LogonAccount fields = ('username', 'email') Sending a post request to this endpoint with username and password in its body keeps returning me a bad request (400) with: { "username": [ "logon account with this username already exists." ], "email": [ "This field is required." ] } Making the fields not required in the serializer just changes the error to database constraints (null value in column id) class LogonAccountSerializer(serializers.HyperlinkedModelSerializer): username = serializers.CharField(required=False) email = serializers.CharField(required=False) class Meta: model = LogonAccount fields = ('username', 'email') I'm not trying to insert data, just trying to validate it. What am I doing wrong or how do I stop it from trying to insert data? -
Converting djangos object.values dict into native datatype?
I'm trying to get specific fields from my database using the object.values() attribute, as such: stocks = Stock.objects.values("ticker", "stock", "exchange__exchange_code", "earnings_yield", "roic") The reason I'm not using Stock.objects.filter()... is because I only need a subset of the fields, and as far as I know, values() is the way to go. stocks[0] returns this: { 'ticker': 'ATRLJ-B', 'stock': 'Atrium Ljungberg AB (publ)', 'exchange__exchange_code': 'ST', 'earnings_yield': Decimal('0.0250'), 'roic': Decimal('0.0200') } How do I get earnings_yield and roic as regular floats? E.g, proper JSON formatted I tried clean = json.dumps(list(stocks), cls=DjangoJSONEncoder) stocks = json.loads(clean) But that returns the decimals as strings, not decimals -
How to call manager & helper classes that are used multiple times in Django/Python?
Say I have a manager class SomeManager that a view uses multiple times in multiple methods, what's the pythonic way to call the manager? In other languages, I would use a method in the view's parent class that in python would look something like ParentView(): some_manager_instance = None def some_manager(self): if not self.some_manager_instance: self.some_manager_instance = SomeManager() return self.some_manager_instance ChildView(ParentView): def do_something(self): self.some_manager().do_something() which any view's methods could then call, without having to recreate the manager so many times. Or, is it more pythonic to just set some_manager = SomeManger() on the views that actually need the manager? -
Alter Django 3+ database schema for SQL Server
By default Django creates database tables with schema [dbo] during migration. These links (Django database tables being created under incorrect schema & https://stackoverflow.com/a/47535618/3960991) present solutions to modifying the schema name in Django 2. These solutions produce errors during migration in Django 3. I have not been able to find any discussion of this issue since Django 3 was released in December 2017. -
TypeError: create_user() missing 2 required positional arguments: 'email' and 'password' in Django Rest Framework
I am trying to create a superuser with email and password only but I am getting the above error. After running py manage.py createsuperuser , it asks for admin and password only and I provide respective fields but after bypassing password validation with yes, it gives above error. class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, first_name, last_name, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None #email = models.EmailField(_('email address'), unique=True) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email -
Django signals not called when app is registered using package name but works with app config class
I was experiencing a problem where my signals were not getting called. I have an app called users and in it I have a model for Profile that extends the django User model and when a user object is saved, I need to create a corresponding profile for it for that I added a signals.py module in the users app, here's my signals file from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): instance.profile.save() And inside my settings.py INSTALLED_APPS I added my app like this INSTALLED_APPS = [ # other apps 'users', ] And my users/apps.py looks like this from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals After registration, the user object was getting created but no corresponding profile. I even put some debug statements in the signal receivers just to confirm my receivers were not getting called and yes the receivers were never getting called. I couldn't find a solution to this as all answers I found on SO showed similar configurations that worked. Out of curiosity I decided to … -
nginx gives 502 Bad Gateway with Django, Docker, gunicorn
I know that this type of question has already been asked numerous times, but the fact that everybody's config is different makes asking it again justified. I'm trying to make nginx work with Django and gunicorn, using Docker to containerize everything. Here's the Dockerfile: FROM python:3.7 COPY requirements.txt /app/requirements.txt WORKDIR /app RUN pip install -r requirements.txt COPY . /app/ RUN chmod -R 777 . EXPOSE 8000 CMD [ "gunicorn", "-b", "0.0.0.0:8000", "computer_vision.wsgi" ] Here's nginx's default.conf: upstream django { server computer-vision:8000; } server { location /static { try_files $uri $uri/ @proxy_to_app; } location @proxy_to_app { proxy_pass http://django; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } Here's docker_compose.yml: version: "3.7" services: computer-vision: build: . image: cv:cv ports: - 8000:8000 nginx: image: nginx ports: - 8080:80 volumes: - ./computer_vision/computer_vision_api/static:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf gunicorn runs successfully, but nginx gives a 502. Here's the console display: nginx_1 [error] 30#30: *4 connect() failed (111: Connection refused) while connecting to upstream, client: ip_address, server: , request: "GET / HTTP/1.1", upstream: "http://ip_address:8000/", host: "localhost:8080" The Dockerfile, default.conf and docker-compose.yml are all in the same directory. Questions: Is server inside upstream in default.conf … -
How to handle media files in production for django
somehow I have handled the media files by keeping the media_root under the static and then by collectstatic command it works in production if I set debug to True else it doesn't work. But neither I want to set debug to True nor I want to put media_root under the static directory. So, what's the solution now apart from AWS s3 because it sucks a lot when it comes to sign up even for free tier. -
object-level validation in django serializers does not recognize function
class serializer_blahblah(serializers.ModelSerializer): """Serializer for ProfileUsefulRecommendations.""" profile_id = serializers.UUIDField() recommendation_id = serializers.UUIDField() class Meta: """Meta class.""" fields = ( "id", "profile_id", ... everything works perfectly with this serializer, however I decided to add object-level validation Here is what happens: def validate(self, data): recommendation_id = str(data["recommendation_id"]) print("recommendation: ", recommendation_id) validate_recommendation_id(recommendation_id=recommendation_id) print(validate_recommendation_id(recommendation_id=recommendation_id)) return data Print out: recommendation: 3a232d0d-0705-4775-8bae-0e2f3d69c96c It does not even recognize the function.... However, if I use exactly same function in individual field serializer, it goes well. But shortly speaking I need it as a object-level -
how to return foreign key related data before submitting the form
i have created a project and the project includes invoices and items , sometimes during creating the invoice the admin dont remember the price of the item , so i have decided to show the price when the admin select an item (ForeignKey) ! is it possible please ? my models.py class Item(models.Model): items = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=3) def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice_no = models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=3) i have to display the price of the selected Item before submitting the form , in order to the admin know how much its the price !? is it possible please i have tried alot , and i know it can be done with ajax , but i'm not good at ajax and this is my template <form method="POST">{% csrf_token %} {{items.management_form}} <div class="p-1 pr-2 pb-1 text-xs border border-black rounded-lg flex flex-wrap" style="direction: rtl;"> <div class="flex w-8/12 lg:w-9/12"> <div class=""> customer name : </div> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.customer | add_class:'bg-transparent w-full text-center focus:outline-none customer' }} {% if form.customer.errors %} <div class="redCOLOR pb-1 my-0 text-center rounded-lg w-full md:w-6/12 mx-auto">{{form.customer.errors}}</div> {% … -
Can I call a web service from javascript?
I'm working on a site to learn English the user must order the words to make the correct question or sentence. I put the questions and sentences in the database the problem is how to make javascript to call a function that returns a new record from the database to view on the page should I use the Jsp service or what I'm actually stuck:( I've read about python Django can I use it here what should I read to do that. thanks var question=["Does","he","like","chess","?"]; // How to get the question from Database var randquestion=shuffle(question); let correctAns="Does he like chess ?"; var temp=""; for(var i=0;i<question.length;i++) { temp+="<button class='btn btn-warning btn-border' id="+'animate'+i+"type=button draggable='true' ondragstart='drag(event)'>"+randquestion[i]+"</button>"; } document.getElementById("div2").innerHTML=temp; function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); let tmp1=document.getElementById(data).innerText; let tmp2=document.getElementById("answer").innerText; ev.target.appendChild(document.getElementById(data)); let tmp3=tmp2.concat(" ",tmp1); document.getElementById("answer").innerText=tmp3; } function drop2(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); let tmp1=document.getElementById(data).innerText; let tmp2=document.getElementById("answer").innerText; ev.target.appendChild(document.getElementById(data)); let tmp3=tmp2.replace(tmp1,""); document.getElementById("answer").innerText=tmp3; } function checkAnswer() { let tmp=document.getElementById("answer").innerText; if(correctAns==tmp) { document.getElementById("result1").innerText="Correct"; /* document.getElementById("result").src="/images/correct2.jpg"; document.getElementById("result").style.display="block"; var audio = new Audio("/sound/correct.mp3"); audio.play(); */ }else{ document.getElementById("result1").innerText="Incorrect"; /* document.getElementById("result").src="/images/incorrect2.jpg"; document.getElementById("result").style.display="block"; var audio = new Audio("/sound/worng.mp3"); audio.play(); */ } } function getRndInteger(min, max) { //This JavaScript function … -
How to use KnoxToken with dj_rest_auth
I want to use Knox's Token when I login using dj_rest_auth or allauth, or when I login using Google, but what should I do in this case? This is because the settings specify knox in this way, so other tokens will not be able to access it. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } from django.contrib import admin from django.conf.urls import url from django.urls import path, include from user.views import GoogleLogin, RegisterAPI urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('dj_rest_auth.urls')), path('auth/google/', GoogleLogin.as_view(), name='google_login'), path('registration/', RegisterAPI.as_view(), name='RegisterAPI'), ] class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
Very odd problem with browsers caching my page even when instructed not to
I have a Django app served on EC2, and Cloudflare sits in front of the app to cache the static content (JS and CSS files; images are hosted separately on S3 and served via Cloudfront again with Cloudflare on top). Every time I deploy new CSS, the hash in the filename of my CSS file changes, e.g. my_stylesheet.12345678.css. Occasionally, after a release that involved a CSS change, I get some users emailing me that the website renders as "just text". Investigation led to find that the page in their browser has HTML that points to a previous release of the CSS file, e.g. my_stylesheet.11111111.css, which doesn't exist on my webserver anymore. Since my website is very dynamic (it's a social network, so most pages will change at every request due to new posts, new comments, new likes, etc), to address this issue I have removed all client-side caching: I now send this header with pages like the main page: cache-control: no-cache, no-store, must-revalidate, max-age=0. I achieve this with Django's @never_cache decorator. These are my Cloudflare page rules: And these are the request/response header for the main page when I request it: Request URL: https://www.example.com/ Request Method: GET Status Code: 200 … -
DRF: how to create a model property to count the number of likes and dislikes?
I have a model which looks like this: class Posts(models.Model): title = models.CharField(max_length=100) creation_timestamp = models.DateTimeField(auto_now_add=True) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="likes",blank=True) dislikes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="dislikes",blank=True) I would like to create a property in this model which can count the number of likes and dislikes. I imagine it would look something like this: @property def interaction_count(self): return len(self.likes) + len(self.dislikes) Sadly, calling self.likes doesn't give me a list like I would like it to. Here is an example of the list I am trying to access: Example of likes and dislikes (I don't have enough reputation to embed images) (for clarification, the numbers inside this lists of likes and dislikes are user_ids. Is there another way to access a list of all the likes associated with a particular post instance? Or perhaps is there a better way entirely to create interaction_count? -
Appended elements using Javascript and Django appearing only for a fraction of a second then disappears again
So I have modified this html file that extends the layout html from the project distribution code, like below: {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <div id='post-text-area'> // there is form element here for the new post </div> {% endif %} // THIS IS THE ELEMENT THAT APPEARS AND THEN DISAPPEARS IMMEDIATELY <div id='posts-view'> </div> {% endblock %} {% block script %} // This is the script file where I add elements into #posts-view <script src="{% static 'network/script.js' %}"></script> {% endblock %} Now in my script.js file, I made it so that #post-text-area and #posts-view will be displayed whenever a function I called all_posts() is called: function all_posts() { document.querySelector('#post-text-area').style.display = 'block'; document.querySelector('#posts-view').style.display = 'block'; // after this is a script where I get the data from the python database and create div element fetch('/get_all_posts') .then(response => response.json()) .then(posts => { posts.forEach(function(post) { // I removed the lines I used to get the data from the database const div = document.createElement('div'); div.innerHTML = `<div> <div><b>${posted_by}</b></div> <div><b>Timestamp:</b> ${timestamp}</div> <div>${post_content}</div> <div>${likes}</div> </div>`; document.querySelector('#posts-view').append(div); }); }); } Aside from that, I implemented a code that will hide #posts-view and #post-text-area, when for example, …