Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to retrieve request.user from form in django
I have the following codes: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... ... class Category(models.Model): name = models.CharField(max_length=30) ... forms.py class FooForm(forms.Form): # how to call 'request.user' here so i can achieve something like the two lines below ??? # user = User.objects.filter(username=request.user).first() <=== GOAL # profile = Profile.objects.filter(user=user).first() <=== GOAL categories = list(Category.objects.values_list("name", flat=True)) categories_values = list(zip(topics, topics)) categories = forms.TypedChoiceField( label="Select a category", choices=categories_values, coerce=str, widget=forms.RadioSelect, initial=topics[0], required=True) def __init__(self, *args, **kwargs): super(ExperienceStart, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout(InlineRadios('categories'),) views.py def experience_start(request): form = FooForm(request.POST) if request.method == "POST": if form.is_valid(): # do something ... else: form = FooForm() context = {"form": form} This work as far as displaying the different categories available in a form so the user can select one of them to compute some result. Now my issue is that i want to include the possibility to retrieve the current user logged in user, which is usually done in the view using request.user but because i am using crispy forms the logic has to be implemented in the forms.py above and i cant seem to find a solution. I am running out of ideas, any help would be helpful … -
Django rest framework user model referring to several other model
I have a couple of models like: class Organization(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Supplier(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... Each model have their own one or more users, I created a user model like this: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email_address = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) My question is how can I create a relationship between User and Organization, Customer, Supplier...? I found one solution like: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email_address = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) organization = models.ForeignKey(Organization) customer = models.ForeignKey(Organization) supplier = models.ForeignKey(Supplier) Which I did not like to do because I have several models that have their users. Another way I found is GenericForeignKey Relationship but also not a very good solution. One of the reasons for this is I have more models to implement similar relationships which becomes very complicated. Can anyone suggest an elegant solution for this? Thanks in advance! -
REST API Django does not show all tables in different endpoints
I am learning REST API Django and would appreciate your patience and help in understaing the below case. in myproject/abcapp/forms.py from django import forms from .models import * class ProfileForm(forms.ModelForm): class Meta: model=Profile fields = "__all__" class Zoo_data_2020Form(forms.ModelForm): class Meta: model=Zoo_data_2020 fields = "__all__" in myproject/abcapp/models.py from django.conf import settings from django.db import models class ProfileQuerySet(models.QuerySet): pass class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model,using=self._db) class Profile(models.Model): name=models.CharField(settings.AUTH_USER_MODEL,max_length=200) subtype=models.CharField(max_length=500) type=models.CharField(max_length=500) gender=models.CharField(max_length=500) objects = ProfileManager() class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' managed = False db_table ='profiles' def __str__(self): return '{}'.format(self.name) class Zoo_data_2020QuerySet(models.QuerySet): pass class Zoo_data_2020Manager(models.Manager): def get_queryset(self): return Zoo_data_2020QuerySet(self.model,using=self._db) class Zoo_data_2020(models.Model): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=3,max_digits=100000000) weight=models.DecimalField(decimal_places=3,max_digits=100000000) age=models.DecimalField(decimal_places=3,max_digits=100000000) objects = Zoo_data_2020Manager() class Meta: verbose_name = 'zoo_data_2020' verbose_name_plural = 'zoo_data_2020s' managed = False db_table ='zoo_data_2020' def __str__(self): return '{}'.format(self.name) in myproject/abcapp/api/views.py: from rest_framework import generics, mixins, permissions from rest_framework.views import APIView from rest_framework.response import Response import json from django.shortcuts import get_object_or_404 from abcapp.models import * from .serializers import * def is_json(json_data): try: real_json = json.loads(json_data) is_valid = True except ValueError: is_valid = False return is_valid class ProfileDetailAPIView(generics.RetrieveAPIView): permission_classes = [] authentication_classes = [] queryset= Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'id' class ProfileAPIView(generics.ListAPIView): permission_classes = [] authentication_classes= [] serializer_class = ProfileSerializer passed_id = None search_fields … -
Trying to save to database via ModelForm Django
My form is not saving to the database or at least i know the form is not valid i just dont know why? because it will always skip to the else in the if form.is_valid() (print("didnt work!")) the view.py: def index(request): component = Component.objects.all() form = ComponentModelForm() if request.method == 'POST': form = ComponentModelForm(request.POST) if form.is_valid(): form.save() return redirect('/maintenance') else: form = ComponentModelForm() print("didnt work!") context = { 'components': component, 'form': form, } return render(request, 'maintenance/index.html', context) forms.py: class ComponentModelForm(forms.ModelForm): note = forms.CharField(widget=forms.Textarea) image = forms.ImageField(error_messages = {'invalid':("Image files only")}, widget=forms.FileInput) class Meta: model = Component fields = ("name", "manufacturer", "model", "serial_number", "price", "note", "image", "parent",) the template form: {% load widget_tweaks %} <form class="component-update-grid" enctype="multipart/form-data" method='POST' action=''> {% csrf_token %} <div class="component-form-data"> <span class="component-label-text">Name</span> {% render_field form.name class="component-form-data-inputs" %} <span class="component-label-text">Manufacturer</span> {% render_field form.manufacturer class="component-form-data-inputs" %} <span class="component-label-text">Model</span> {% render_field form.model class="component-form-data-inputs" %} <span class="component-label-text">Serial Number</span> {% render_field form.serial_number class="component-form-data-inputs" %} <span class="component-label-text">Price</span> {% render_field form.price class="component-form-data-inputs" %} <span class="component-label-text">Note</span> {% render_field form.note class="component-form-data-inputs" %} {% render_field form.parent class="component-form-data-inputs " %} <input type="submit" class="button1" value='Create Component' /> </div> <div class="component-form-img"> <img class="maintenance-component-img" src='{%static 'imgs/sidebar/logo.png'%} ' /> {% render_field form.image %} </div> </form> -
How to run scheduler in different apps of same django project
I have two apps viz: app1 and app2 in my-project. I am running a scheduled task in views.py of app1 and app2 on every month basis on different timing. But app1 is functioning properly but app2 scheduler is not calling at all. here is my code. app1 views.py code ''' from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() def start_job(): global job scheduler.add_job(ampplan, 'cron', day=15, hour=18, minute=46) scheduler.add_job(calib, 'cron', day=27, hour=5, minute=15) scheduler.add_job(oildue, 'cron', day=27, hour=5, minute=30) scheduler.add_job(sdrmplan, 'cron', day=27, hour=5, minute=45) try: scheduler.start() except: pass start_job() ''' app2 views.py code ''' scheduler = BackgroundScheduler() def nlr_start_job(): global job scheduler.add_job(ampplan, 'cron', day=15, hour=20, minute=0) scheduler.add_job(calib, 'cron', day=27, hour=6, minute=1) scheduler.add_job(oildue, 'cron', day=27, hour=6, minute=10) scheduler.add_job(sdrmplan, 'cron', day=27, hour=6, minute=20) try: scheduler.start() except: pass nlr_start_job() ''' -
GitHub user authentication in GitHub application through Django framework
I want to authenticate GitHub user to my GitHub application and serve to my local server 127.0.0.1:8000, but I am not able to take tokens. This is how GitHub is showing authentication. From GitHub documentation, I am not able to understand the process of authentication after generating private key, then how to create JWT and installation tokens ? Could someone show me what to do next ? -
Django Testing the model file midels.py
I am trying to test the models.py file using Django TestCases but after sovling few portion rest I could not figure out how to solve it Here the models.py file looks like import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) … -
Missing Imports [Django] [Pip External Packages]
I started using django for the first time today and I have been encountering one issue I want to use the PDFNetPython3 library for my project in Django framework. I ran the command pip install PDFNetPython3 and it is says its already installed, however Django isn't able to resolve the import Error/Warning Import "PDFNetPython3" could not be resolvedPylancereportMissingImports This is the line below being shown as unresolved import. from PDFNetPython3 import PDFDoc, Optimizer, SDFDoc, PDFNet views.py from http.client import HTTPResponse from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return render(request, 'index.html') def compress(request): return render(request, 'compress.html') def showName(request): if request.method == 'POST': user_initial_pdf = request.POST['user_initial_pdf'] from PDFNetPython3 import PDFDoc, Optimizer, SDFDoc, PDFNet return HttpResponse("ok") Python Version - 3.9.7 Django Version - 4.0.1 Please note : I havent created any virtual environment as of now cause I just started django and found out its a good practice to do so, can it be the cause django not able to resolve the library through pip ? Help would be appreciated :) -
how to set simplejwt token as authentication_classes in django rest
so I'm using django rest framework and I'm using simpleJWT for authentication. now i have some APIs that require the user to be logged in which means they require the token that was given to them beforehand. My problem is that I don't know what to do to make this happen. Is there anything that I could write any value for the following variable to make this automatic? authentication_classes = () and if that's not possible, how would I be able to do this? -
Django HTML issue with HTML text formatting
I am developing django site locally, I have some issues with Formatting of text (highlighted yellow). On a main blog yellow is incorrectly showing that HTMl tags, although when I enter detailed view of post I see all is ok. Do you know what can be issue? incorrect: correct: base.html: <!DOCTYPE html> <html> <head> <title>Django Central</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Tangerine", serif; font-size: 37; background-color: #fdfdfd; } .shadow { box-shadow: 0 4px 2px -2px rgba(0, 0, 0, 0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background: #3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } img { width: 00%; height: auto; object-fit: contain; </style> {% load static %} <center> <img src="{% static 'blog/moj.png' %}" alt="My image"> </center> <!-- Navigation --> <nav class="navbar navbar-expand-sm navbar-light bg-light shadow" id="mainNav"> <div class="container-fluid"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item text-black"> <a class="nav-link text-black font-weight-bold" href="/">Blog</a> </li> <li class="nav-item text-black"> <a class="nav-link text-black font-weight-bold" href="portfolio/">Moje projekty/ Portfolio</a> </li> <li class="nav-item … -
Django sorting objects with Dropdown-List / url parameter
I have problems with sorting objects from database in main template which are based on url parameters. I want to sort objects on different ways. Mainly by date, price etc. I have my form in template, my views.py function where I'm trying to get the parameter "sort=new". If I'm using checkboxes or radio then everything works. But I need to sort objects with select and option. My template: <h2>Number of adverts: {{num}}</h2> <form action="{% url 'adverts' %}"> <span>Sort by:</span> <select name="sort"> <option value="new">newest</option> <option value="old">older</option> <option value="price_low">price low</option> <option value="price_high">price high</option> <option value="mileage_low">mileage lowest</option> <option value="mileage_high">mileage higher</option> <input type="submit" value="Sort"> </select> </form> My views.py function: def adverts(request): page = 'adverts' if request.GET.get('sort', 'new'): adverts = Advert.objects.all().order_by('-created') elif request.GET.get('sort','old'): adverts = Advert.objects.all().order_by('created') else: adverts = Advert.objects.all().order_by('-mileage') a = 0 for num in adverts: a += 1 context = {'adverts': adverts, 'num': a, 'page': page} return render(request, 'adverts/adverts.html', context) As I mention above. I want to sort objects which I’m printing in my template. I want it to be a Dropdown list not a checkbox or radio. Maybe I need to create a form in forms.py file and then get access to form fields in my template? I’m confused. -
Trying to change new_manager.user.is_employee = False and set it as new_manager.user.is_manager = True , but not working
Upon converting a user into a manager, I need to set 'is_employee = False' and 'is_manager = True'. The process appears to be quite straightforward, but I can't get it to work. models.py class User(AbstractUser): is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=True) is_manager = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} as {self.username}' class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_profile = models.OneToOneField(Profile, on_delete=models.CASCADE) business_unit = models.OneToOneField(BusinessUnit, on_delete=models.SET_NULL, null=True) previous_business_units = models.CharField(max_length=100, default=None, blank=True, null=True) manager_description = models.TextField(blank=True, null=True) manager_created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' views.py @login_required @admin_required def manager_create_view(request): form = ManagerCreationForm() if request.method == 'POST': form = ManagerCreationForm(request.POST) if form.is_valid(): new_manager = form.save(commit=False) group = Group.objects.get(name='Manager') new_manager.user.groups.add(group) new_manager.user.is_employee = False new_manager.user.is_manager = True new_manager = form.save() new_manager = form.cleaned_data.get('user') messages.success(request, f'{new_manager} is now a Manager!') return redirect ('list-managers') messages.error(request, 'Something went wrong, please check the hilighted field(s)') context = { 'title': 'Create Manager', 'form': form } return render(request, 'managers/manager-form.html', context) I tried using signals as well but, no luck. signals.py from django.db.models.signals import post_save from accounts.models import User, Manager from django.dispatch import receiver @receiver(post_save, sender=Manager) def change_user_type(sender, instance, created, **kwargs): if created: instance.user.is_manager = True instance.user.is_employee = False Trying to learn on my own, so any help … -
best way to filter and search with vue3&django_rest
I'm new to vue and Django ,I want to implement a search component for a e-commerce project and filter the results as user want. i spent some time to find a proper way and here is what i understand so far: front solution: for vue3 i can use vuex store and computed properties to implement search and filter the search results for example (https://softauthor.com/vuejs-composition-api-search-bar-using-computed-properties/#disqus_thread) the question is: 1) is it a good solution still when scaling, to store all products in vuex and filter and search them when search results are containing for example more than 500 or more products... backend solution: with Django rest_framework: one way is to send the search result from Django and send a request for every filter and search option that maybe valid for getting highest discount in all products but not all cases i think...the question i have here is : 2) is it better to do the search through django and limit the number of result sending back instead of vue solution... finally, should i mix the ways and use searching in all products through Django and some other conditions with vue I saw lots of questions for search and filtering but didn't … -
Django filter applied when kwargs else return all
I would like to display list of all Team objects or narrow to only those related to country passed via kwarg parameter. class TeamListView(ListView): """View to display all or filtered teams.""" model = Team def get_queryset(self): filters = {} country = self.kwargs['country'] if 'country' in self.kwargs else None filters.update({ 'country': country }) return super(TeamListView, self).get_queryset() \ .filter(**filters) I can easilly achieve filtering but for no parameter instead of all objects I get None. Of course I know, I can return super()...all() instead of filter() but that looks ugly and I'm asking if there's any magic keyword like __all__ or I should give some Q object but how to prepare it? -
Django Rest Framework Unable to Load Fixtures ManyToOneRel has no attribute 'to_python'
I'm trying to develop and REST API Based upon DRF, I have two models for this and one many relationship between Author and Genre, when I'm trying to load some data into the created tables using fixtures [ { "model":"inventory.genre", "pk":"1", "fields":{ "tag":"fiction", "description":"Fiction is the telling of stories which are not real. More specifically, fiction is an imaginative form of narrative, one of the four basic rhetorical modes. Although the word fiction is derived from the Latin fingo, fingere, finxi, fictum, works of fiction need not be entirely imaginary and may include real people, places, and events. Fiction may be either written or oral. Although not all fiction is necessarily artistic, fiction is largely perceived as a form of art or entertainment. The ability to create fiction and other artistic works is considered to be a fundamental aspect of human culture, one of the defining characteristics of humanity." } }, { "model":"inventory.genre", "pk":"2", "fields":{ "tag":"graphic novel", "description":"A graphic novel is a narrative work in which the story is conveyed to the reader using sequential art in either an experimental design or in a traditional comics format. The term is employed in a broad manner, encompassing non-fiction works and thematically … -
Class inheritance python
In the case creating a model, for example class Student(models.Model) name=models.charfield(),roll=models.integerfield() similarly, In the case creating a form, class newform(forms.Form) name=forms.charfield(),roll=forms.integerfield() similarly, In the case creating a serializer, class serial(serializers.Serializer) name=serializers.charfield(),roll=serializers.integerfield() I understood that in each classes,a base class is inherited but i am confused that if different objects of different classes are created inside a class in each scenario then what is the meaning of inheriting models.model, forms.Form,serializers.Serializer what these inherited classes do? -
How to create a class and connect it with an existing table in Django?
I am new to Django, and I have a SQL Server database. I don't want to create a class and make a migration because I already have a table with its data. Migration will create a new table for the class. I want to create a class and connect it with the existing table in models.py. How can I do that? Here is my table: CREATE TABLE [dbo].[login]( [lo_id] [int] IDENTITY(1,1) NOT NULL, [lo_username] [nvarchar](50) NOT NULL, [lo_password] [nvarchar](max) NOT NULL, [lo_name] [nvarchar](50) NOT NULL, [lo_email] [nvarchar](50) NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] Here is the connection in the sittings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DjangoTest', 'USER': 'sa', 'PASSWORD': 'p@$$W0rd', 'HOST': 'HostName\\SQLSRV2019', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } -
Django DRF router reverse with kwargs
class API(ModelViewSet): @action(detail=True, methods=['post'], ) def invite_users(self, request, pk=None): chat_group = self.get_object() invite_users_url = reverse('group-detail', kwargs={'pk':group_id, 'format':'invite_users'},) I want path/pk/invite_users but I got NoReverseMatch: Reverse for 'group-detail' with keyword arguments '{'pk': 'SvY9aA1SK6ok', 'format': 'invite_users'} -
ERROR: No matching distribution found for GDAL==2.4.0 (Heroku/Django)
I have been troubleshooting this error for a long time and can't get my head around it. My app deploys over Heroku successfully but when I run it - it throws an Application Error. Consulting build output I see that GDAL Library is causing the issue (traceback below). I have tried to enable GDAL following the Heroku docs. My Aptfile contains: gdal-bin (as per the Heroku docs, as I understand them). I have tried manually setting the GDAL version in requirements.txt to GDAL==2.4.0, GDAL=3.4.1(latest version) and, following this SO answer, GDAL without a version attached. (requirements.txt) below. Requirements.txt: asgiref==3.4.1 beautifulsoup4==4.10.0 bs4==0.0.1 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.10 cryptography==36.0.1 defusedxml==0.7.1 dj-database-url==0.5.0 Django==4.0.1 django-allauth==0.47.0 django-bootstrap-modal-forms==2.2.0 django-heroku==0.3.1 django-on-heroku==1.1.2 django-widget-tweaks==1.4.11 djangorestframework==3.13.1 GDAL gunicorn==20.1.0 idna==3.3 oauthlib==3.1.1 psycopg2==2.9.3 psycopg2-binary==2.9.3 pycparser==2.21 PyJWT==2.3.0 python3-openid==3.2.0 pytz==2021.3 requests==2.27.1 requests-oauthlib==1.3.0 soupsieve==2.3.1 sqlparse==0.4.2 urllib3==1.26.8 whitenoise==5.3.0 Traceback from Heroku build-output [...] Collecting GDAL==2.4.0 Downloading GDAL-2.4.0.tar.gz (564 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pnmrbd3c/gdal_00a97084715441d78d0780b0c9cd0780/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pnmrbd3c/gdal_00a97084715441d78d0780b0c9cd0780/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-j_z5wzv2 cwd: /tmp/pip-install-pnmrbd3c/gdal_00a97084715441d78d0780b0c9cd0780/ Complete output (73 lines): WARNING: … -
How can a website be run without the user having the language it was built on installed
This refers to all languages. How is it that if I don't have for example Ruby on Rails or Django installed, I can open a website it was built on without having to download it? Because running the source code will definitely not work, so why does it work in a browser? -
Django with Google Cloud Storage
I have been trying to implement google cloud storage (media file uploads) for my django app on google app engine using the django-storages package. I have followed all the specification given by the package. I also set the relevant policies and roles for the service account to access the storage bucket but I keep getting the error "anonymous caller does not have storage.objects.get access to the google cloud storage object." when trying to view the images in my html template. I can only view the images in the template when I include the permission for allUsers in storage bucket settings. Does anybody know how to fix this issue without making your bucket publicly accessible. This is the screenshot of my configuration for django-storages in the settings.py file -
Cutting video using moviepy in Django
How can I set video duration like TikTok.com. I don't a user to upload a video that is more than 3 minutes or 4 minutes using moviepy in django. how can i cut the video. This is my views: From Moviepy.editor import * def addvideo(request): if request.method == 'POST': file = request.FILES.get('video') videos = Video.objects.create( file=file ) return redirect('home') return render(request, 'addvideo.html') -
Using python manage.py migrate --check in kubernetes readinessProbe never succeeds
I have a django deployment on kubernetes cluster and in the readinessProbe, I am running python manage.py migrate --check. I can see that the return value of this command is 0 but the pod never becomes ready. Snippet of my deployment: containers: - name: myapp ... imagePullPolicy: Always readinessProbe: exec: command: ["python", "manage.py", "migrate", "--check"] initialDelaySeconds: 15 periodSeconds: 5 When I describe the pod which is not yet ready: Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 66s default-scheduler Successfully assigned ... Normal Pulled 66s kubelet Successfully pulled image ... Normal Created 66s kubelet Created container ... Normal Started 66s kubelet Started container ... Warning Unhealthy 5s (x10 over 50s) kubelet Readiness probe failed: I can see that migrate --check return 0 by execing into the container which is still in not ready state and running python manage.py migrate echo $? 0 Is there something wrong in my exec command passed as readinessProbe? -
Django admin: order by a nullable date, with null values at the end
I have a model with a DateTimeField which I would like to use to order the table in admin. Using ordering = ('-completed',) in admin.py works, but those with null values come first in the sort. Is there a way to make them appear at the end instead? So at the moment I have something like: Column A Completed Column C x - y x - y x Today's date y x Yesterday's y Is there a way to make it like this? Column A Completed Column C x Today's date y x Yesterday's. y x - y x - y -
Websocket connection is failed [env: django channel, gunicorn, uvicorn, nginx, postgre and redis over https(wss)}
I have deployed my app on digitalOcean using this tutorial link ,https and all pages rendering properly and django working fine, The issue right now is websocket connection is failed, the error messages I got are from console web page says: WebSocket connection to 'wss://mysitedomain/ws/chat/2_3/' failed: Other error message from gunicorn server shows 404 not found page: "GET /ws/chat/2_3/ HTTP/1.0" 404 Regardless what wss configuration I add it to nginx configuration file; connection is failed!!.. below is mysite configuration file under 'etc/nginx/sites_available' folder in linux for your reference ( I have removed all wss configuration blocks): please note I already have installed uvicorn[standard] version but didn't help!! server { listen 80; server_name IP domain name; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/DjangoProject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } }