Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get data from second api call based on data coming from the first api (python/django)
I am making a simple web application in pycharm (python/django) that displays data that it picks up from growstuff.org. The main page displays all the crops based on what it finds on growstuff.org/crops.json like the plant's name,scientific name and description. However, info of the plants themselves (like spread,height,days to harvest,sun requirements) are contained in growstuf.org/crops/ID.json. I have already managed to get the data from crops.json and display it on the website,however i can't combine the two files to display the full info i need. How can I make the second call based on the first one's data? views.py apidata = requests.get('https://www.growstuff.org/crops').json() #cropdata = requests.get(f"https://www.growstuff.org/crops/{}.json").json() return render(request, 'index.html', {'apidata':apidata}) index.html <table Width="70%" Height="180px"> <thead> <tr style="font-family:asul; "> <td>Crop</td> <td>Name</td> <td>Scientific Name</td> <td>Description</td> <td>Suniness</td> <td>Companions</td> </tr> </thead> <tbody id="myTable"> {% for i in apidata %} <tr> <td><img src="{{i.thumbnail_url}}" style=" border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px;"></td> <td><h4>{{i.name}}</h4></td> <td><h4>{{i.scientific_name}}</h4></td> <td><h4>"{{i.description}}"</h4></td> {% for j in cropdata %} <td><h4>{{i.j.sun_requirements}}</h4></td> <td><h4>{{i.j.relationships}}</h4></td> {% endfor %} </tr> {% endfor %} </tbody> </table> -
orator migrate command not working in django
When i'm running orator migrate command then with giving config path like orator migrate -c db.py Then the result is comming Command Cancelled! I have installed orator in django Orato 0.9 Python 3.9.7 django 4.0.5 I create a migration and model in the mean project that you can see my code and set the connection but when I'm running migrate command db connection from orator import DatabaseManager, Schema import environ env = environ.Env() environ.Env.read_env() databases = { 'mysql': { 'driver': 'mysql', 'host': 'localhost', 'database': env('DB_DATABASE'), 'user': env('DB_USERNAME'), 'password': env('DB_PASSWORD'), 'prefix': '' } } db = DatabaseManager(databases) schema = Schema(db) migration file from orator.migrations import Migration class CreateProductsable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('products') as table: table.increments('id') table.integer('category_id').unsigned() table.timestamps() table.foreign('category_id').references('id').on('jobs').on_delete('cascade') def down(self): """ Revert the migrations. """ self.schema.drop('products') model file class Product(Model): __table__ = 'products' -
Django adding new courses by users in Learning Management System app from UI
On my app, I can add new courses from Django Admin Panel Only by using the model in Django Admin Panel. Picture 1 - Django Admin Panel Picture 2 - Adding New Course from Admin Panel I want to automate this whole process. I want to create a form where users can fill out the form and submit their Course using UI. And That course will automatically be added to the Courses. So, to achieve my goal, what are the necessary steps I should take? For a better understanding of my problem here is the GitHub repo link to my project. GitHub Repo of My Project -
Django view to download a file from server
I have a views.py that: creates some .xlsx files select the correct .zip and place the file inside After that, I want this .zip to be automatically downloaded. I did some research and tested some codes but none worked. I created a "temp" folder in the root of the app where the created files are stored. simplified view.py def generate_ws(request,cource,ca_id): ca = get_object_or_404(CreditAnalysis,pk=ca_id) ca_owners = CAOwner.objects.filter(ca_operation=ca) mo_farms = MOFarm.objects.filter(ca_operation=ca) misses = [] generate_owner_mo(ca_owner,misses,city) zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip' zf = zipfile.ZipFile(zip_name,'w') zf.close() generate_farm_mo(mo_farm,misses,city) generate_production_mo(ca,misses,city,production_city,pks) files = glob.glob('temp/*.xlsx') for file in files: file_key = file.split('.')[0] file_key=file_key.split(' - ') for ca_owner in ca_owners: zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip' if str(ca_owner.owner) in file_key: zf = zipfile.ZipFile(zip_name,'a') new_file_name = file[5:] zf.write(file,new_file_name) zf.close() break for file in files: if file[5:8]=='MOs': download_mo(request,file) misses = list(set(misses)) return render(request,'generate_mo.html',{'misses':misses,}) download_mo def download_mo(request,file): path_to_file = os.path.realpath(file) with open(path_to_file,'rb') as fh: response = HttpResponse(fh.read()) file_name = file[5:] response['Content-Disposition'] = 'inline; filename=' + file_name return response Everything works correctly except the download which never starts -
How to use opencv-python for Java blob in Django
I'm building a Django website. My users can record a video and then others can see these videos. The recording is done with javascript: const mimeType = 'video/mp4'; shouldStop = false; const constraints = { audio: { echoCancellation: true, noiseSuppression: true, }, // audio: true, video: { width: 480, height: 480, facingMode: 'user', }, }; const stream = await navigator.mediaDevices.getUserMedia(constraints); const blob = new Blob(recordedChunks, { type: mimeType }); And the sent to a django view: let response = await fetch("/send-video/", { method: "post", body: blob, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken":csrftoken, }, }).then( ... ) In my views if request.method == 'POST': user = request.user file_name = f"{user}.mp4" if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'): file_path = file_name else: file_path = f"{your_media_root}temp/{file_name}" webm_bytes = bytes(request.body) video_file = open(file_path, "wb") video_file.write(webm_bytes) if mimetypes.guess_type(file_path)[0].startswith('video/mp4'): print(mimetypes.guess_type(file_path)) video_file.close() else: video_file.write(b"") video_file.close() I like to understand how I can use opencv-python instead of raw file saving. How can I implement this ? -
Handling different SSO implementations in Django webapp
I am not very experienced in SSO so please forgive me if my question sounds silly. I have a Django webapp which currently uses the embedded model-based Django authentication. This application of mine is meant to work in different companies where different authentication/authorization systems are used (Microsoft AD, Google, Oracle, etc.). So I want to implement SSO in my webapp but without knowing which implementation will be used. My question would be if there is a Python SSO library that can handle different SSO implementations? Naturally that would be fine if there were separate config parameters per SSO engine. Or do I have to use different libraries per SSO implementations? Thank you! -
Django Postgres makemigrations only Autofield at 0001_initial.py
Python 3.10.4 Django 4.0.5 PostgreSQL 14 When I start "python manage.py makemigrations" i got the file "0001_initial.py" but all Fields, except autofields, are missing. models.py from django.db import models # Create your models here. class Username(models.Model): #id = models.AutoField(primary_key=True) username: models.CharField(max_length=100) class Carrier(models.Model): #id = models.AutoField(primary_key=True) carriername: models.CharField(max_length=100) desc: models.TextField() 0001_initial.py # Generated by Django 4.0.5 on 2022-06-29 13:18 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Carrier', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Username', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] -
Mysql-python for upgraded Django
I'm upgrading a system from Django 1.11.16 Debian 9.6 Python 2.7.13 mysql-server 5.5.9999+default to Django 4.0.5 Debian 11.1 Python 3.9.2 mariadb-server 10.5.15 . My plan is to make a dump from the existing database and use it in the new server within the very new, upgraded environment. With Django 1.11.16 I used MySQL-python==1.2.5 as a connector to the database. My question is what package with what version do You advise to use for the same purpose with the given set of versions? -
Not all stylesheets are loaded
There are 2 stylesheets. One is under the project folder (created for base.html) and another is inside the app folder (for applist.html). collectstatic command did collect both the stylesheets and put inside the STATIC_ROOT folder 'assets'. But when runserver is on, the app's stylesheet isn't loaded only the base.html's stylesheet got loaded and working. base.html {% load static %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> {% block title %} {% endblock %} </title> <!-- Add additional CSS in static file --> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> </head> <body> {% block content %}{% endblock %} </body> </html> applist.html <!DOCTYPE html> {% extends "base.html" %} <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> {% load static %} <meta charset="utf-8" /> <title>List</title> <!-- Add additional CSS in static file --> <link rel="stylesheet" type="text/css" href="{% static 'css/dstyles.css' %}"> </head> {% block content %} <body> <h2>Testing for stylesheet linking</h2> </body> {% endblock content %} </html> folder structure is like, Dev_ static css styles.css app static css dstyles.css assets static css styles.css dstyles.css The base.html's styles are working whereas app's stylesheet is not working. I did F12 and checked to see only style.css got loaded and dstyles.css didn't appear. attaching … -
Connecting Django on Ubuntu EC2 to AWS RDS MySQL: pymysql tries to connect to localhost instead of foreign server
I am in the process of deploying a Django project on an Ubuntu EC2. It should connect to a MySQL server on AWS RDS. The project works fine on the built-in Django development server you start with runserver and it also connects to the RDS instance properly there. However, if I try running it in production, it throws a 500 Internal Server Error that creates the following output in the error log: mod_wsgi (pid=18656): Exception occurred processing WSGI script '/home/ubuntu/mysite/mysite/wsgi.py'. Traceback (most recent call last): File "/home/ubuntu/mysite/mysite_venv/lib/python3.8/site-packages/pymysql/connections.py", line 613, in connect sock = socket.create_connection( File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: ... pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") This socket error occurs both with my custom views and with the mydomain.com/admin view. The relevant snippet of views.py looks like this: # get environment variables db_host = os.environ.get('DB_HOST') db_user = os.environ.get('DB_USER') db_pass = os.environ.get('DB_PASS') # connect to db conn = pymysql.connect(host=db_host, user=db_user, password=db_pass) c = conn.cursor() c.execute('''USE mysitedatabase''') The file is generally executed properly, log statements I inserted as a test before … -
Outlook office 365 mail SMTP email authentication doesn't work in django?
django settings config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@outlook.com' EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_USE_TLS = True EMAIL_USE_SSL = False it shows error smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful [BM1P287CA0013.INDP287.PROD.OUTLOOK.COM]') -
Python Django - Making changes to Model
So I had a model with fields which was in use. Now, I removed some fields from original model and created their own model and linked this new model with the original model using some constraint. Now, when I add new instances, they are being added. But how to handle instances which are already in database before changes were made. Can add more information if required or some confusion is there. Thanks. -
Want to save returned value or printed value of another python file in postgresql's existing table of a specific column.from django file DB created
I have the smtp mailing code in smtp.py file with following below code. In the field "number_of_emails_sent in (models.py).At the beginning when the user will post his details that field will be empty as default. But when we start our process to implement the smtp.py file it(number_of_emails_sent in database) should be appended each time we run the code for the specific user with his details. For example there are 3 users["king","queen","soldier"], when they post at the first time he has fields in api like {"user_email" :"King@gmail.com", "password":"1587687", "SMTP_PORT" :" 078", "SMTP_HOST" : "025", "Is_Active" :"True", "subject" : "Hi", "Body" : "How are you", "Number_of_emails_sent: "" } So this data will be saved in Database of specific table but the number of fields will be empty for all users.So here I want to insert value which should be increases each time the smtp flow of a specific user will done. For example today for user "king" I run the smtp flow 3 times so the value of particular user will be 3.And if I run the flow after two days,the code I run in that day suppose 5 times so the value in the ("Number_of_emails_sent") should be 8. So it should … -
How to upload a file using forms in django
I have being having issues with uploading an image file into my database. Here is the code. models.py from django.db import models from datetime import datetime class Product(models.Model): name = models.CharField(max_length=1000, blank=False, null=False) image = models.FileField() price = models.IntegerField(default=0, blank=False, null=False) stock = models.IntegerField(default=0, blank=False, null=False) forms.py from django import forms from .models import Product class ProductCreationForm(forms.ModelForm): class Meta: model = Product fields = ( "name", "image", "price", "stock", ) views.py from .models import Product from .forms import ProductCreationForm def product_create(request): form = ProductCreationForm() if request.method == "POST": form = ProductCreationForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] image = form.cleaned_data['image'] price = form.cleaned_data['price'] stock = form.cleaned_data['stock'] item = Product.objects.create(name=name, image=image, price=price, stock=stock) item.save() return redirect('product-view') else: messages.info(request, 'Invalid information entry!') return redirect('product-create') else: return render(request, "create.html", {"form": form}) create.html {% if user.is_authenticated %} <form method="post"> {% csrf_token %} {% for message in messages %} {{ message }} {% endfor %} {{ form.as_p }} <input type="submit", value="Done"> </form> {% endif %} settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Everytime i create a new product from … -
How to create correct url in tepmplate Django
I have this link in my templates: <a href="{% url 'main:user-main-account' %}?=client_account{{ client_account.id }}"> like a link it looks like: https://mysite.ua/main/user_main_account/?=client_account=1 How can I change my template link to get link like this: https://mysite.ua/main/client_account/1/user_main_accounts My 2 urls in urls.py look like this: path('user_main_account/<int:pk>/', ........) path('client_account'/<int:pk>/'.........) Please help me!I am stuck of 3 days. -
How to make REST Search-filter case-insensitive for none english letters?
Accordance to the REST's search-filter, "By default, searches will use case-insensitive partial matches". Everything works fine for english letters but for none-english ones it doesn't. class ProductsAPIView(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.SearchFilter,) search_fields = ['title', 'name'] My view path('all/', views.ProductsAPIView.as_view()), My url path For example: When I search in english letters: When I search in none-english letters: I have an item: { "id": 10, "productType": "Напитки", "measurment": "л", "product_image": "http://127.0.0.1:8000/images/logo.png", "title": "Фанта (0.5)", "name": "Фанта", "price": 40, "description": "", "created": "2022-06-21T07:20:07.582387Z", "updated": "2022-06-21T07:20:07.582435Z" }, "title": "Фанта (0.5)", - starts with upper case. So when I try /api/all/?search=ф. ( ф - lower, Ф - upper, in this case I wrote the lower ). I don't get this item. But I get it when I try with /api/all/?search=Ф (The upper one) I get the item what is contrary to case-insensitive. -
Django Recursive Query with self Foreign Key
I have following django model with parent attribute being as self foreign key class PolicyCoverage(TimeStampedModel): policy = models.ForeignKey(Policy, on_delete=models.CASCADE) name = models.CharField(max_length=100) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify) amount = models.DecimalField(max_digits=19, decimal_places=10) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True) I have setup my serializer to send data for front end but I am not getting desired output but I am not getting desired output for easiness I want to get data in this way {parent A--> {child A of parent A, child B of parent A[ {child A of Parent B Child B of Parent A} ] but data i am getting right now is as {parent A--> {child A of parent A, child B of parent A[ {child A of Parent B Child B of Parent A } ]}, {child A of Parent B}, {Child B of Parent A} how do i make recursive query work I tried almost all previuos stack overflow qsn but I am going nowhere. here is serializer I have been doing class ParentSerializer(serializers.ModelSerializer): class Meta: model = PolicyCoverage fields = [ 'slug', 'policy', 'name', 'amount', 'parent' ] class PolicyCoverageSerializer(serializers.ModelSerializer): parent = serializers.SerializerMethodField() class Meta: model = PolicyCoverage fields = [ 'slug', 'policy', 'name', 'amount', 'parent' … -
Ngnix - Django 413 Request Entity Too Large
i already read and tried the foundable soulutions here but nothing helped me out. I have this conf file of nginx: user nginx; # Sets the worker threads to the number of CPU cores available in the system for best performance. # Should be > the number of CPU cores. # Maximum number of connections = worker_processes * worker_connections # Default: 1 worker_processes auto; # Maximum number of open files per worker process. # Should be > worker_connections. # Default: no limit worker_rlimit_nofile 8192; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; load_module modules/ngx_http_image_filter_module.so; events { # If you need more connections than this, you start optimizing your OS. # That's probably the point at which you hire people who are smarter than you as this is *a lot* of requests. # Should be < worker_rlimit_nofile. # Default: 512 worker_connections 4000; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; client_max_body_size 200M; # Hide nginx version information. # Default: on server_tokens off; sendfile on; #tcp_nopush on; keepalive_timeout 65; include /etc/nginx/conf.d/*.nginx; } I also added this to my settings.py : FILE_UPLOAD_MAX_MEMORY_SIZE = 1005242880 Can anyone help me? -
SuspiciousFileOperation at /report/ The joined path is located outside of the base path component: Django
hi i need to get to generate a pdf with images using xhtml2pdf; I have added the method link_callback like that: def link_callbacke(uri, rel): result = finders.find(uri) print("0") if result: if not isinstance(result, (list, tuple)): result = [result] result = list(os.path.realpath(path) for path in result) path=result[0] else: sUrl = settings.STATIC_URL sRoot = settings.STATIC_ROOT mUrl = settings.MEDIA_URL mRoot = settings.MEDIA_ROOT if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # make sure that file exists if not os.path.isfile(path): return path this is in views.py , how i was getting the image field: image1_full = CustomerPersonalData.objects.get(user_related=request.user) obj_image1 = CustomerPersonalData._meta.get_field("image1" value_image1 = obj_image1.value_from_object(image1_full) in models.py: class CustomerPersonalData(models.Model): user_related = models.OneToOneField(User, on_delete = models.CASCADE) image1 = models.ImageField(blank=True, upload_to="media") def save(self, force_insert=False, force_update=False): img = Image.open(self.image1) super(CustomerPersonalData, self).save(force_insert, force_update) and in the generated_pdf.html: <p><img src="/home/dev/.virtualenvs/django-projects/project1/static/media/{{ value_image1 }}"></p> in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ---> an error displayed : SuspiciousFileOperation at /report/ The joined path (/home/dev/.virtualenvs/django-projects/project1/static/media/media/image1.png) is located outside of the base path component (/home/dev/.virtualenvs/django-projects/lib/python3.7/site-packages/django/contrib/admin/static) ---I want to know what does mean this error and how i can resolve it otherwise the path(/home/dev/.virtualenvs/django-projects/project1/static/media/media/image1.png) is correct. -
the Data doesnt get deleted from CRUD page and aso doesnt get deleted in Database
Hi I am new to django and I am doing CRUD operations,I have successfully completed CRU,only delete remains,I am try to SOFT DELETE the data. below is my del_cat function: def del_cat(request,id): delcategory = Categories.objects.get(id=id) delcat={} delcat['isactive']=False form = CategoriesSerializer(delcategory,data=delcat) if form.is_valid(): print(form.errors) form.save() messages.success(request,'Record Deleted Successfully...!:)') return redirect('categories:show_cat') else: print("sfsdrf",form.errors) return redirect('categories:show_cat') below is the urls path below is the href path for the delete button yet the data doesnt get deleted and it aso remains in the databse,what could the problem in the code be? -
Django / duplicate key value violates unique constraint every time creating new object with CreateAPIView
django.db.utils.IntegrityError: duplicate key value violates unique constraint "publication_article_pkey" DETAIL: Key (id)=(13233) already exists. Seeing this error every time using ArticleCreateView endpoint. Object is created fine, but i can’t understand where and because of what this error raises. I would be grateful for any help and clarification! class ArticleCreateView(generics.CreateAPIView): """Article add""" permission_classes = [permissions.IsAuthenticated] queryset = Article.objects.all() serializer_class = AddArticleSerializer lookup_field = "slug" def perform_create(self, serializer): serializer.save(author=self.request.user, status=0) Serializer: class AddArticleSerializer(serializers.ModelSerializer): tag = serializers.SlugRelatedField( many=True, queryset=Tag.objects.all(), slug_field='name' ) class Meta: model = Article fields = ("title", "content", "description", "language", "tag", "cover") Overrided Article Model save method: def save(self, *args, **kwargs): if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() if not self.slug: super().save(*args, **kwargs) self.slug = slugify(unidecode.unidecode(f'{self.id} {self.title}')) self.save() self.updated_at = timezone.now() super().save(*args, **kwargs) -
Why do I keep getting the axios error in my Django React app on Heroku?
I developed a simple Django React application and deployed on to heroku: https://friendly-interview-duck.herokuapp.com/ Even though the backend and frontend connection was working correctly via axios in local, I started getting the infamous GET http://127.0.0.1:8000/api/questions/ net::ERR_CONNECTION_REFUSED error in the deployed app. Obviously, I thought this had something to do with hosts/CORS. I initially had CORS_ALLOWED_ORIGINS = [ 'https://friendly-interview-duck.herokuapp.com', 'https://127.0.0.1:8000.com', 'https://localhost.com' ] ALLOWED_HOSTS = [ 'https://friendly-interview-duck.herokuapp.com', 'https://127.0.0.1:8000.com', 'https://localhost.com'] in my setting.py but getting this error, I changed it to: CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] to experiment. And guess what? I am still getting connection refused error! I cleared the cash multiple times and even browsed into the deployed url from another computer and the error still exists. As a note, I know many people miss '/' at the end of their urls which causes this but I have a '/' at the end of my request urls as well so that can't be the problem. What am I missing here? https://github.com/gokceozer1/friendly-interview-duck.git -
How to assign a local IP address to a public IP/Port address using NGINX with UWSGI?
I have a web application that is running in a local server using a local IP address and the port 80. However, I would like to be able to access the web application from the Internet. Thus, I have got a public a IP address from a telecommunication company. I have configured the NGINX server as followed: upstream django { server unix:///my_path/my_project.sock; # server 127.0.0.1:8000; } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name local_ip_address; charset utf-8; # max upload size client_max_body_size 75M; # Django media location /media { alias /my_path/media; } location /static { alias /my_path/static; } location / { uwsgi_pass django; include /my_path/uwsgi_params; } } In my setting.pyfile, I have used the local IP address in the ALLOWED_HOSTS = ['local IP address']. But in my firewall, I have forwarded this IP to the public one. I have done all the nginx configurations. When I run the application from the local IP address, it is working perfectly, but I run the application from the public IP, it is showing page not found. How can I assign the local IP address … -
How to get request user or logged user from model manager?
We have created a manager class in models.py We can not access request user. class Course(models.Model): instructors = models.ManyToManyField(get_user_model(), .... class InstructorCourseManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(instructors=request.user) class ProxyInstructorCourse(Course): objects = InstructorCourseManager() class Meta: proxy = True Do you have any idea? -
Issues playing mp4 on apple on django website
I'm building a Django website. My users can record a video and then others can see these videos. The recording is done with javascript: const mimeType = 'video/mp4'; shouldStop = false; const constraints = { audio: { echoCancellation: true, noiseSuppression: true, }, // audio: true, video: { width: 480, height: 480, facingMode: 'user', }, }; const stream = await navigator.mediaDevices.getUserMedia(constraints); const blob = new Blob(recordedChunks, { type: mimeType }); And the sent to a django view: let response = await fetch("/send-video/", { method: "post", body: blob, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken":csrftoken, }, }).then( ... ) In my views if request.method == 'POST': user = request.user file_name = f"{user}.mp4" if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'): file_path = file_name else: file_path = f"{your_media_root}temp/{file_name}" webm_bytes = bytes(request.body) video_file = open(file_path, "wb") video_file.write(webm_bytes) if mimetypes.guess_type(file_path)[0].startswith('video/mp4'): print(mimetypes.guess_type(file_path)) video_file.close() else: video_file.write(b"") video_file.close() Now I can save these files to a django model field. I use django-private-storage to make sure only users with the correct authentication can view the files. django-private-storage uses a FileReponse to play the video. and it generates a template with: <video controls="" autoplay="" name="media"> <source src="http://127.0.0.1:8000/play-job-video/" type="video/mp4"> </video> All works fine on any browser on android. I can record …