Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Errors during configuration of the neo4j django-neomodel
I'm trying to do a simple project in Django using the Neo4j database. I've installed a django-neomodel library, set the settings as follows: import os from neomodel import config db_username = os.environ.get('NEO4J_USERNAME') db_password = os.environ.get('NEO4J_PASSWORD') config.DATABASE_URL = f'bolt://{db_username}:{db_password}@localhost:7687' created a model: class Task(StructuredNode): id = UniqueIdProperty() title = StringProperty() added 'django_neomodel' to INSTALLED_APPS, removed the default database configuration and when I try to enter the website it raises the error: ImproperlyConfigured at / settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.. It's the only error because after running the python manage.py install_labels command it raises: ServiceUnavailable("Failed to establish connection to {!r} (reason {})".format(resolved_address, error)) neo4j.exceptions.ServiceUnavailable: Failed to establish connection to IPv6Address(('::1', 7687, 0, 0)) (reason [Errno 99] Cannot assign requested address). I'm pretty sure that the database works correctly because as you see I can access this. screenshot docker-compose: version: "3.9" services: api: container_name: mm_backend build: context: ./ dockerfile: Dockerfile.dev command: pipenv run python manage.py runserver 0.0.0.0:8000 volumes: - ./:/usr/src/mm_backend ports: - 8000:8000 env_file: .env depends_on: - db db: container_name: mm_db image: neo4j:4.1 restart: unless-stopped ports: - "7474:7474" - "7687:7687" volumes: - ./db/data:/data - ./db/logs:/logs -
When i am trying to upload file its showing FieldFile is not JSON serializable - Django
TypeError at /web/ticketcreation/ Object of type FieldFile is not JSON serializable here is my models.py class Ticket(models.Model): Email=models.CharField(max_length=60) to=models.CharField(max_length=60) cc=models.CharField(max_length=60) subject=models.CharField(max_length=25) module = models.CharField(max_length=25) priority = models.CharField(max_length=25,null=True) message = models.CharField(max_length=70) choosefile = models.FileField(null=True, blank=True) -
How to make a blogpost model in Django?
I am trying to make a website and I want to add blogs and articles to my website using the admin page. How do I make a model that takes both text and the images I want after every paragraph in my article? If that's not possible how do I input both separately and render it in the correct order together? -
How to get the uploaded file content in json format using django rest framework?
Hi I was trying to get the get the uploaded file content in json format as response ( not file details) Upto now I did the upload of file using django rest framework which I did mention in my previous question “detail”: “Method \”GET\“ not allowed.” Django Rest Framework now I am getting the json response as follows in the given picture link https://ibb.co/wzTmG6W please help me thanks in advance -
Compare two text files to show changes made like in version control systems in python
Background: I'm trying to make a VCS for text articles using django as a learning project, like so, where anyone can edit an article and the changes made can be displayed on the site. Till now I've only found the difflib module. I've copied and tried code from here. import difflib lines1 = ''' How to Write a Blog Post This is an extra sentence '''.strip().splitlines() lines2 = ''' How to Write a Blog Post '''.strip().splitlines() for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm='', n=0): print (line) It outputs the following: --- file1 +++ file2 @@ -2 +1,0 @@ -This is an extra sentence But this code only shows the differences between two files and even in that it won't show differences properly if for example words or letters in a line are edited. Is there a python library/module which can help show the changes made to the file or even the differences between any two edits? -
How to calculate the price of Order using (sum of) OrderItems prices in django rest framework
I am able to calculate the OrderItem model prices using @property decorator but unable to calculate the total price of the Order model while creating the order object. When I called the post api for creating the orde, there is no error but I am not getting total_price in the api response. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) #logic to calculate the total_price, and its not working @property def total_price(self): return sum([_.price for _ in self.order_items_set.all()]) #realted name is order_items def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) #total_item_price = models.PositiveIntegerField(blank=True,null=True,default=0) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') #Logic to calculate the total_item_price, it works. @property def price(self): total_item_price = self.quantity * self.order_variants.price return total_item_price My serializers: Class OrderItemSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(read_only=True) #price = serializers.ReadOnlyField() class Meta: model = OrderItem fields = ['id','order','orderItem_ID','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) # total_price … -
How to make Django link to different html pages based on the result of a form?
I am confused on how to change html pages based on the results of a form. I want to create a form to get a search query. Based on this query, a page should be rendered to the user. For example, if the page query is chocolate, then a page should be main/chocolate. Same for any other query: main/"query". How is it possible to do this? I have tried using a normal form in order to do this, but this did not work. I have tried: this is from views.py: if request.method == "GET": ask = NewForm(request.GET) if ask.is_valid: Muk = ask.cleaned_data("Stuff") result = util.get_entry(Muk) good = markdown2.markdown(result) return page(request, good) else: return render(request, "encyclopedia/index.html") return render(request, "encyclopedia/layout.html", { "form": ask })``` And it always meets me with an error page, since earlier in views.py, I defined: def page(request, name): ```stuff = util.get_entry(name) if stuff is None: return render(request, "encyclopedia/error.html") things = markdown2.markdown(stuff) return render(request, "encyclopedia/content.html", { "things":things })def page(request, name): stuff = util.get_entry(name) if stuff is None: return render(request, "encyclopedia/error.html") things = markdown2.markdown(stuff) return render(request, "encyclopedia/content.html", { "things":things })``` -
How to count and make addition with for loop with a table in Django?
I created a customer system. In this system, a user has several customers. I have a Customer model and this model has multiple fields like risk_rating, credit_limit, country, etc... I want to list the countries where customers are located and show data about them in a data table. I am using .distinct() method for that, but I cannot figure out how can I show some data. For example, I want to total credit_limit (adding operation) in the related country and I want to count all customers that have Low risk risk_rating. I can do this the long way with if statement. But I can't think of anything other than just creating a concatenated if statement for all countries. This would be a very long and inefficient way. Because there are 208 countries in the world. How can I do that? Note: I try to use for loop counter for counting the number of risks but it did not work properly. models.py class Customer(models.Model): RISK_RATING = [ ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ('Moderately High Risk', 'Moderately High Risk'), ... ] customer_name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) credit_limit = models.FloatField(default=0, null=True) risk_rating = models.CharField(max_length=50, default='Select', choices=RISK_RATING, … -
Django suddenly gives me error that Apps aren't loaded yet
I am using Django3.1. All was working fine. I pip installed a new app and tried to run makemigrations. It suddenly doesn't work anymore. I get error 'Apps are not loaded yet'. I thought it was the app. Uninstalled it. Didn't work. Deleted the virtualenv directory. Created new one and installed all apps again except the last one. It didn't work. I had installed another version of Postgres and hadn't restarted my computer since then. Restarted but didn't work. Tested by running another project to make sure it was not new Postgres issue. That worked as expected. Commented out my url confs and installed apps in the settings.py. But still the same error. Tried multiple SO suggestion related to this error but nothing works. Can anyone please help. Error from console: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\myuser\Envs\myproject\lib\site-packages\django\core\checks\translation.py", line 60, … -
Why are there so many ways in doing the same thing in Python Script Commands in calling dependencies?
Forgive me because I came from Laravel 8 (to be specific) I am still a newbie in Django and in Python in general because I want to learn both at the same time because I always see in social media sites that they're always marketing python hence a trending language nowadays and I like to be a web developer so I also want to learn Django like i did with php, javascript, css-pre-processors, vue and react alll inside of the Laravel Ecosystem Like for example I just discovered you can do this but on a different command call of dependency libraries and I am confuse both the py and python starting commands in calling and importing python scripts and is there going to be some slight sort of technical issues Example 1: Via Package Manager Installation of the Django Web Framework and additional Parameters @MINGW64 ~/backend Opt1: pip install django djangorestframework django-cors-headers Opt2: py -m pip install Django djangorestframework django-cors-headers Opt3: python -m pip install django gunicorn psycopg2-binary Opt4: py -3 -m pip install Django djangorestframework django-cors-headers Example 2: And in testing and running the server (venv)@MINGW64 ~/backend/djangoreactProj Opt1: py -m manage runserver 0.0.0.0:5000 Opt2: py -3 -m manage runserver … -
enable/disable password protection for website
I want to give my client the option to enable/disable password protection on their website through a admin panel kind of like how Shopify does it. first question would be is this option available in any existing headless cms. if not can this be done with my own custom cms using Django or a different backend framework? i'v looked around for resources but can't seem to find anything so any advice/resources would be appreciated note will be built in react -
“detail”: “Method \”GET\“ not allowed.” Django Rest Framework
I know this question was duplicate I am beginner in django I tried in all ways but not able to find solution I was trying to upload a file and get a json response as ok using django rest framework So far I tried is views.py: from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: from django.conf.urls import url from .views import FileView urlpatterns = [ url(r'^upload/$', FileView.as_view(), name='file-upload'), url(r'^upload/<int:pk>/$', FileView.as_view(), name='file-upload'), ] The error is: Method /GET/ is not allowed please help me thanks in advance -
Code works locally but not on the server (Django, Opencv)
I'm trying to convert the image and save it in the static folder temporarily by using the cv2.imwrite function, but I'm getting an error that says No such file or directory: './static/images/0.png' (In order to convert the image, I had to save images temporarily). It works locally but not on the server. What am I supposed to do? class Article(models.Model): writer = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='article', null=True) project = models.ForeignKey(Project, on_delete=models.SET_NULL, related_name='article', null=True) title = models.CharField(max_length=200, null =True) image = models.ImageField(upload_to='article/', null=True, blank=True) image_converted = models.ImageField(upload_to='article/converted/', null=True, blank=True) style = models.CharField(max_length = 50, blank = True, null=True, choices=ACTION_CHOICES) content = models.TextField(null=True) created_at = models.DateField(auto_now_add=True, null=True) like = models.IntegerField(default=0) def convert_image(self, *args, **kwargs): image_converted = convert_rbk(self.image, self.style) self.image_converted = InMemoryUploadedFile(file=image_converted, field_name="ImageField", name=self.image.name, content_type='image/png', size=sys.getsizeof(image_converted), charset=None) def convert_rbk(img, style): if style == "HAYAO": img = Image.open(img) img = img.convert('RGB') img = ImageOps.exif_transpose(img) img.save("./static/images/0.png") model = Transformer() model.load_state_dict(torch.load('pretrained_model/Hayao_net_G_float.pth')) model.eval() img_size = 450 img = cv2.imread('./static/images/0.png') T = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size, 2), transforms.ToTensor() ]) img_input = T(img).unsqueeze(0) img_input = -1 + 2 * img_input img_output = model(img_input) img_output = (img_output.squeeze().detach().numpy() + 1.) /2. img_output = img_output.transpose([1,2,0]) img_output = cv2.convertScaleAbs(img_output, alpha = (255.0)) cv2.imwrite('./static/images/1.png', img_output) result_image = "./static/images/2.png" cmd_rembg = "cat " + "./static/images/0.png" + " … -
How to add one to one unique relationship between multiple models in django?
class User(models.Model): # User's fields such as username, email etc class Agent(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields class Seller(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields class Buyer(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) # Other agent fields Here I have one custom User model and 3 different models, Agent, Seller, Buyer, so the relationship must be one-directional from user to any of the 3 models. Suppose I have a user User1, he can be either an agent or a buyer or a seller, he cannot be both a buyer and seller. So for instance, User1 is a buyer, after creating an object of the Buyer model with User1, User1 cannot be used to create Seller object or ``Agent` object How can I do that? -
How to render html file in Django
In my views.py from django.shortcuts import render def home(request): return render(request, "app/base.html") In my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="Home") ] I'm so confuse, it is not working -
To test a POST request for an authenticated route in Django Rest Framework
I want to test a post request for a route with authentication required(Knox from Django Rest Framework). Here the post request should object for a logged in user. Following is urls.py path('cards', addCard.as_view(), name="cards"), Following is addCard view class addCard(generics.ListCreateAPIView): serializer_class = CardSerializer permission_classes = [permissions.IsAuthenticated, IsOwnerOrNot] def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) card = serializer.save(owner=self.request.user) return Response({'card': CardSerializer(card, context=self.get_serializer_context()).data,}) def get_queryset(self): return self.request.user.cards.order_by('-id') Following is the test case, I used this answer, I got 401!=201 error, clearly Unauthorized user. class addCardAPIViewTestCase(APITestCase): url = reverse("cards") def setUp(self): self.username = "john" self.email = "john@snow.com" self.password = "you_know_nothing" self.user = get_user_model().objects.create_user(self.username, self.password) self.token = Token.objects.create(user=self.user) def test_create_cards(self): client = APIClient() client.login(username=self.username, password=self.password) client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = client.post(self.url,{ "bank": "Citibank", "card_number": "5618073505538298", "owner_name": "c1", "cvv": "121", "expiry_date_month": "03", "expiry_date_year": "2023" },format='json') self.assertEqual(response.status_code, 201) -
Django allauth with custom fields in User Moel
I am trying to use Django All Auth for login and signup using custom User Model and Form. class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True,default=create_new_ref_number()) country_code = models.IntegerField(default='91') two_factor_auth = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'student'), (2, 'teacher'), (3, 'unassigned'), (4, 'teacherAdmin'), (5, 'systemadmin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,default=3) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['full_name', 'phone_number', 'country_code'] I am not sure how or where should I get phone_number from users who are signing up. Since the field is required and unique, I am using random number to temporarily have some value. Please suggest. -
Django a simple query makes me crazy ''int' object is not iterable'
I have two Models: class MasterData(models.Model): ID = models.AutoField(primary_key=True) Companyname = models.CharField('Companyname', max_length=128, blank=True, null=True) UserID = models.IntegerField('UserID') class Prefixes(models.Model): ID = models.AutoField(primary_key=True) UserID = models.ForeignKey('MasterData', on_delete=models.CASCADE) InvoiceNoPrefix = models.CharField('InvoiceNoPrefix', max_length=5, blank=True, null=True) No I want in my view a make a simple objects.get_or_create if you visit the site the first time and no records exist should it create one. @login_required(login_url='/backend/') def edit_prefixes(request): user_id = request.user.id userfrommasterdata = MasterData.objects.filter(UserID__in=user_id) prefixes_data = Prefixes.objects.get_or_create(UserID=userfrommasterdata) And all what I get is a: 'int' object is not iterable What do I miss? On my MasterData view it's working perfectlit: @login_required(login_url='/backend/') def edit_masterdata(request): user_id = request.user.id # stamdata_data = get_object_or_404(Stamdata, pk=user_id) stamdata_data, _ = MasterData.objects.get_or_create(UserID__iexact=user_id, UserID=user_id) -
Managing post data from external API (callback URL)
I have a Django app in the MENA region and can't use Stripe as the payment gateway there, I'm relying on a payment page created on the site as a response to my payment request ( I'm not hosting the payment form on my own site ) this is the response I get when my server sends the payment page creation {'callback': 'https://example.com/mycallback', 'cart_amount': '{amount}', 'cart_currency': '{currency}', 'cart_description': 'Subscription 123', 'cart_id': '4244b9fd-c7e9', 'redirect_url': 'https://payment-gateway.com/payment/page/9B8E682', 'tran_ref': 'TST2109500134074', 'tran_type': 'Sale'} and when the user proceeds to the payment form gets redirected to my callback URL with a HTTP POST like this: acquirerMessage=&acquirerRRN=&cartId=4244b9fd-c7e9&customerEmail=user@email.com&respCode=G95839&respMessage=Authorised&respStatus=A&token=&tranRef=TST2109500134074&signature=c93f8f98c46e8bf972b8848f4a59f81583304f125bd7e4d136fd8b4432baf7b3 and based on this response my callback view will handle the user data. If you supplied a callback URL, then the Payment gateway will send the transaction results to that URL using a HTTP POST. This will be a purely server-to-server request, the customers browser will not be involved. Your systems should provide HTTP response with response codes 200 or 201. how should I handle this in the callback URL how can I grap this data ? -
why the Django rest framework ModelSerializer. create and ModelSerializer.validate not working properly?
I am developing an authentication system for User registration through Django rest framework. serializers.py from rest_framework import serializers from .models import NewEmployeeProfile class RegistrationSerializers(serializers.ModelSerializer): ''' We need to add the password2, as its not the part of the NewEmployeeProfile model. So, we need to make it manually. ''' password2 = serializers.CharField(style={'input_type: password'}, write_only=True) class Meta: model = NewEmployeeProfile fields = ('email', 'first_name', 'last_name', 'employee_code', 'contact', 'dob', 'password', 'password2') extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): """ before we save the new user, we need to make sure that the password1, and password2 matches. In order to do that, we need to override the save() method. """ password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': f'password must match..'}) return NewEmployeeProfile.objects.create(**validated_data) def validate(self, attrs): if attrs: account = NewEmployeeProfile( email=self.validated_data['email'], first_name=self.validated_data['first name'], last_name=self.validated_data['last name'], employee_code=self.validated_data['employee code'], contact=self.validated_data['contact'], dob=self.validated_data['dob'], ) account.save() return account views.py class UserRegisterView(ListCreateAPIView): create_queryset = NewEmployeeProfile.objects.all() serializer_class = RegistrationSerializers(create_queryset, many=True) permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = RegistrationSerializers(data=request.data) if serializer.is_valid(): newUser = serializer.save() serializer = RegistrationSerializers(newUser) return Response(data={"status": "OK", "message": serializer.data}, status=status.HTTP_201_CREATED) return Response(data={"status": "error"}, status=status.HTTP_400_BAD_REQUEST) models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, … -
Uploading and Retrieving Images to MongoDB Atlas using Django Rest (HELP)
I'm having trouble uploading images to Mongo and retrieving them using Django Rest. I am using GridFS and I'm simply trying to upload a profile picture of a user.This what my api looks like after uploading my image It does not show me a viable link to access it. It just points me back to the create view for some reason. I checked my Mongo Atlas page and it seems like the images are being stored. How can I properly retrieve my images? Here is the code I wrote: settings.py BASE_URL = 'http://127.0.0.1:8000/' models.py grid_fs_storage = GridFSStorage(collection='myfiles', base_url=''.join([settings.BASE_URL, 'myfiles/'])) class ProfilePic(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='users', default='avatar.png',storage=grid_fs_storage) serializers.py class ProfilePicSerializer(serializers.ModelSerializer): class Meta: model = models.ProfilePic fields = ('id', 'profile_pic') views.py class ProfilePicView(viewsets.ModelViewSet): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = models.ProfilePic.objects.all() serializer_class = ProfilePicSerializer -
is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found
is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found in the dictionary. instead of multiple ifs?? name = None type_of_transaction = None customer = None transaction_id = None for key, value in data_value.items(): if "unique_element" in key: customer = value if "type" in key: type_of_transaction = value if "product_name" in key: name = value if "transactionId" in key: transaction_id = value -
A form submit returns {"error": "'action'"}
I have a form submit that crashes in production with the following error {"error": "'action'"}, but for some weird reason does not happen in local way. The input with id="btnEditar" is the one that push the error. The error is displayed in a white page. Nothing appears in the console of the browser and as far as the error doesnt ocurr in local no messages appears in the backend. I have tried to reload js in several browsers but with the same results... running on Django local dev server the form is submitted OK and the data is updated as well, but in pythonanywhere prod server the error mentionated error comes up. hope you can help me to figure it out!! Here is the template code: {% extends 'core/home.html' %} {% load static %} {% load bootstrap %} <!doctype html> <html lang="es"> <head> </head> <body class="text-center"> {% block content %} <form method="post"> {% csrf_token %} <div style="visibility: hidden;" id="HiddenId">{{ object.id }}</div> <div style="visibility: hidden;" id="HiddenFecAnt">{{ object.start_time }}</div> <div class="container mb-4" style="margin-top: 10px;"> <div class="row justify-content-center"> <div class="card w-24" style="height: 7rem; width: 14rem; margin: 2px"> <div class="card-header" style="height: 2.5rem;" > Fecha de Reprogramación </div> <div class="card-body"> <div class="row justify-content-center"> {{form.start_time|bootstrap}} </div> … -
Give access to my Google Drive to the users of my website
I am developing an application in django and I need that the users who enter my website have access to my Goolge Drive, I am trying to save the google accesses in the user's session, but it does not work SCOPES = ['https://www.googleapis.com/auth/drive'] credentials = Credentials.from_authorized_user_file('token.json', SCOPES) request.session['credentials'] = {'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes } -
How do I force my heroku django project to use https?
I have a django site hosted by Heroku (tachlisgeredt.com), but I am having a weird problem. Basically, for anyone going to my site going to 'tachlisgeredt.com' doesn't work, only going to 'tachlis.herokuapp.com', and even that shows 'not secure'. However, going to 'https:/www.tachlisgeredt.com' works, and it shows 'secure'. So basically, how do I force my django site hosted by Heroku to use https?