Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get() returned more than one Product -- it returned 2 Django Rest Framework
DRF returning this: get() returned more than one Product -- it returned 2!, when im trying to get objects from my DB by PK Serializers class ProductSerializer(serializers.ModelSerializer): # cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True) class Meta: model = Product fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo') Views class CategoryProductView(APIView): def get(self, request, pk): product = Product.objects.get(cat_id=pk) serializer = ProductSerializer(product) return Response(serializer.data) Urls path('api/categorylist/<int:pk>', CategoryProductView.as_view()) -
Django serialize One to One
I have a model named client and it has a two foreign key relationships. One is to the region they are from and the other is to an agent. I am trying to serialize all clients. Using, use_natural_foreign_keys=True is giving me the region name. How would I get the agent name without using DRF? Model: class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Client(models.Model): name = models.CharField(max_length=20, default="") agent = models.ForeignKey("Agent", on_delete=models.CASCADE) region = models.ForeignKey("Region", on_delete=models.CASCADE) View: class ClientLog(View): page_limit = 100 def get_paginated_context(self, queryset, page, limit): if not page: page = 1 if limit: self.page_limit = limit paginator = Paginator(queryset, self.page_limit) page_obj = paginator.get_page(page) serialized_page = serialize("json", page_obj.object_list, use_natural_foreign_keys=True) serialized_page = [{**obj["fields"], **{"pk": obj["pk"]}} for obj in json.loads(serialized_page)] return { "data": serialized_page, "pagination": { "page": page, "limit": limit, "has_next": page_obj.has_next(), "has_prev": page_obj.has_previous(), "total": queryset.count() } } def get(self, request, *args, **kwargs): page = request.GET.get('page') limit = request.GET.get('limit') queryset = Client.objects.all() to_return = self.get_paginated_context(queryset, page, limit) return JsonResponse(to_return, status = 200) -
ModuleNotFoundError: No module named 'blog.models'
I was experimenting with my database and made some errors and messed up the whole database. I deleted the database and created a new blank db. When I go to makemigrations i get the error ModuleNotFoundError: No module named 'blog.models' refering to the line in my views.py where i import my models. I tried creating a a new project and moving the files over same error. Everything was working fine before I messed up the DB. Sorry for not a ton of information I dont know what the issue really is -
Django permissions view access for only one permission in the list
I have a Django class based view in which I am using the PermissionRequiredMixin. I would like a user who has at least one of the permissions in the permissions_required attribute to be able to access the view. From the Django documentation: The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view. So, if User1 has permission, "add_polls" and User2 has "change_polls", and I have a form view that lets a user add a poll and another view that lets a user change a poll (with permissions_required="add_polls" and permissions_required="change_polls" on each of those views, respectively), it works great. But, what if I have an interim page/view that has links to both of those views with permissions_required = ("add_polls", "change_polls") that I need the user to pass through first? Now, neither user will be able to access to that page because the users only have access to one or the other permission, not both - if I understand the documentation correctly, a user will need BOTH those permissions to access the interim page. If I did give both users access to both those permissions so … -
This QueryDict instance is immutable (Trying to manually set form data)
When I go to save. It will not allow me. I am trying to add details into the database through inputting the form manually. I am struggling to actually input the data into the form so I can save it. For example, I have tried to get the form data then set the data I would like it to be set to however Im guessing this is incorrect? I cannot find a command to set the form data manually. Is this possible? views from telnetlib import LOGOUT from django.shortcuts import redirect, render from django.http import HttpResponse from matplotlib import use from matplotlib.pyplot import get from matplotlib.style import context from werkzeug import Request from .models import Account, Question, sni, Option from django.contrib.auth.hashers import make_password, check_password from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, logout from django.contrib.auth import login as dj_login from django.forms import ModelForm, forms from django.contrib.auth.decorators import login_required from .forms import AccountAuthenticationForm, SNIForm, createUserForm, resultForm def login(request): context = {} if request.method == 'POST': username = request.POST.get('username').lower() password = request.POST.get('password') user = authenticate(request, userID = username, password = password) form = AccountAuthenticationForm(request.GET) if user is not None: dj_login(request, user) return redirect('dashboardPage') else: messages.info(request, "userID or password … -
How to know the key of a DRF Serializer DictField from within that field's child?
Let's say we have some Django Rest Framework Serializer (we'll call it "serializer") that has a custom DictField as one of its fields. Within that custom DictField, the child field is tasked with recording the dictionary key that it is the value of whenever serializer.save() is called. How would one go about knowing the key of the dictionary being deserialized when interpreting the internal value to be saved? class ChildField(Serializer): parent_key = CharField() def to_internal_value(self, data): # At this point, the likely candidate for the # key is self.field_value, but it is actually '' # data['parent_key'] = ??? return super().to_internal_value(data) class ParentField(DictField): child = ChildField() Assume the data being deserialized is the following: { "the_dictionary": { "key_we_want_to_save": { "arbitrary_other_child_data": True } } } -
Django if statements in forms
I am trying to allow a user to upload a file of unknown type through a form and then save it to a folder depending on the type of file it is. I was hoping I could use 'if' statements, but I can't make them work inside the form. I currently just have direct upload paths: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to='priority/', blank=True, null=True) title = models.CharField(max_length=100) content = models.FileField(default='text', upload_to='text/', blank=True, null=True) image = models.ImageField(default='default', upload_to='images/', blank=True, null=True) video = models.FileField(default='video', upload_to='videos/',blank=True, null=True) large_video = models.FileField(default='large_video', upload_to='large_video/', blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) # user owns the post, but post doesn't own the user. author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I'd like to do something like this, but it doesn't work: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to='priority/', blank=True, null=True) title = models.CharField(max_length=100) if(*image ends in .txt*) content = models.FileField(default='text', upload_to='text/', blank=True, null=True) if(*image ends in .png*) image = models.ImageField(default='default', upload_to='images/', blank=True, null=True) ... is there any way to do this? -
Problems running the app locally with heroku and django
I'm trying to use my project locally to do some migrations since I was using heroku, but to migrate I need the local environment. Suddenly I got these errors whenever I use: python manage.py collectstatic and python manage.py runserver I already have my .env file with its variables, the SECRET_KEY and DEBUG. What I did notice is that in the file of settings, the config marks it in red from decouple import config I don't know where to start or how to translate them. -
How can I package my Django project with a server software so that it is ready to run on any machine?
I want to share the project to multiple clients so that they can use it on their own local networks without doing a lot of work. So somehow packaging the Django project along with a secure server software together so that it easily can be run on any machine would be nice. -
Escape single curly brace in Django template
I am looking to generate a string like \usepackage{mypackage} from a Django template. Suppose there is a variable package.name in the context how can I generate this? Firstly I tried, \usepackage{{{package.name}}} but that throws TemplateSyntaxError Then I tried \usepackage{ {{package.name}} } which works but has the two spaces in the output, ie, \usepackage{ mypackage } Is there an easy way to generate this string with Django template engine? -
Django default image not saving
I am having an issue while saving a default image whenever I am not uploading an image in ImageField. I can't understand what I am doing wrong, for me it seems everything ok but couldn't find where the bug is. models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) date_of_birth = models.DateField() fiscal_code = models.CharField(max_length=50) phone = models.CharField(max_length=50) license = models.ForeignKey( License, on_delete=models.CASCADE, blank=True, null=True) picture = models.ImageField( blank=True, null=True, default='default.png') id_card = models.ForeignKey( IDCard, on_delete=models.CASCADE, blank=True, null=True) address = models.CharField(max_length=100) cap = models.CharField(max_length=10) city = models.CharField(max_length=100) province = models.CharField(max_length=100) country = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py def create_student(request): context = { } if request.method == 'POST': username = request.POST.get('username') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') date_of_birth = request.POST.get('date_of_birth') email = request.POST.get('email') phone = request.POST.get('phone') password = request.POST.get('password') address = request.POST.get('address') cap = request.POST.get('cap') province = request.POST.get('province') country = request.POST.get('country') fiscal_code = request.POST.get('fiscal_code') id_number = request.POST.get('id_number') expire_date = request.POST.get('expire_date') picture = request.FILES.get('picture') id_image = request.FILES.get('id_image') # fs = FileSystemStorage() # filename = fs.save(picture.name, picture) # profile_pic_url = fs.url(filename) # filename2 = fs.save(id_image.name, id_image) # id_image_url = fs.url(filename2) try: user = CustomUser.objects.create_user( username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=3) user.student.address = address user.student.date_of_birth = date_of_birth user.student.cap = cap user.student.province = province … -
new locale not redirecting properly
I have a basic django cms running with lots of localised content. I have been assigned to add few more languages before content can take over. here is a sample english url: <domain>/en/myhelp/ this is the sample menu which is supposed to render the menu dropdown: <body> {% cms_toolbar %} <div class="container faq-main main-block"> <div class="select-wrapper"> <select name="language" id="faq-lang" class="lang-btn hide"> <option value="en">English</option> <option value="hi">हिंदी</option> <option value="mr">मराठी</option> <option value="te">తెలుగు</option> <option value="ta">தமிழ்</option> <option value="kn">ಕನ್ನಡ</option> <option value="bn">বাংলা</option> <option value="ml">മലയാള൦</option> <option value="gu">ગુજરાતી</option> </select> </div> {% block content %}{% endblock content %} {% block contact %}{% endblock contact %} {% block actions %}{% endblock actions %} </div> {% render_bundle 'faq' 'js' %} {% render_block "js" %} </body> any language selected from menu dropdown updates the url accordingly. for example on selecting mr, url mentioned above would change to: <domain>/mr/myhelp/ All good so far. Now i have added 2 more langs in this menu: <option value="od">ଓଡିଆ</option> <option value="as">অসমীয়া</option> Problem is that when i select od / as from menu, url changes to: <domain>/en/od/myhelp/ <domain>/en/as/myhelp/ basically, en is not removed from url locale causing page not found error. Any help or indication in right direction to correctly add this locale is appreciated. version: django-cms: 3.7.1 Django: … -
Django admin login SSL_do_handshake() failed
I get following in nginx-error log while logging in to admin page of django website 2022/01/28 17:04:50 [crit] 22184#22184: *263 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.232.184, server: 0.0.0.0:443 2022/01/28 17:08:12 [crit] 22184#22184: *277 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.239.221, server: 0.0.0.0:443 2022/01/28 17:08:30 [crit] 22184#22184: *288 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 107.178.232.251, server: 0.0.0.0:443 2022/01/28 17:10:09 [crit] 22184#22184: *302 SSL_do_handshake() failed (SSL: error:14201044:SSL routines:tls_choose_sigalg:internal error) while SSL handshaking, client: 45.56.98.215, server: 0.0.0.0:443 2022/01/28 17:28:03 [crit] 22184#22184: *344 SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshaking, client: 165.227.140.0, server: 0.0.0.0:443 One possible reason is I do not have the secret key I used while making the django project as I lost the .env file. I used this answer to generate a secret key and to store in the .env file. Could this be the reason, or is there some other reason? -
Updating is_issued in Book model after adding a book in Issued. Django restframework
This is models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) is_issued = models.BooleanField(default=False) isbn = models.CharField(max_length=100) def __str__(self): return self.title class IssuedBooks(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) issued_to = models.CharField(max_length=100) issued_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.book.title viewsets.py from rest_framework import viewsets from .models import Book, IssuedBooks from .serializers import BookSerializer, IssuedBooksSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class IssuedBooksViewSet(viewsets.ModelViewSet): queryset = IssuedBooks.objects.all() serializer_class = IssuedBooksSerializer # Add book to IssuedBooks and update book's is_issued field # Also be able to issue books when is_issued is false I assume the solution has something to do with the viewsets. It basically needs to have create and delete methods for Issuedbooks route while also updating and referencing Book model. -
ERRORS: inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I am a beginner in Django. I am trying to build an app with user authentication. However I want extra fields like country and phone number, and I don't want any username field (I want the phone number to act as the username), so I built a custom user class. There are questions that have already been asked that have the same error, but they are not exactly relevant to my use case and the solutions don't work for me. models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django_countries.fields import CountryField # Create your models here. class UserProfile(AbstractBaseUser): user = models.OneToOneField(User, on_delete = models.DO_NOTHING) phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False) country = CountryField() uid = models.UUIDField( default = None, blank = True, null = True, unique = True, ) USERNAME_FIELD = "uid" REQUIRED_FIELDS = ['phone_number', 'country'] forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile from django_countries.fields import CountryField # Create your forms here.. class NewUserForm(UserCreationForm): phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$') country = CountryField() class Meta: model = UserProfile fields = … -
django-filter and django custom pagination with ModelViewSet
I implemented a modelviewset with django-filter and django default pagination comnbined. Its working fine when I use either django-filter or django pagination. But when they are used simultaneously then I am getting duplicate results in response. So whats the correct way to use pagination in django-filter with CBV? class TableMetaView(ModelViewSet): """ This will be used to create new tables. You require to add the table fields in json request and also the job request associated with that table. If you want to create new table then pass CREATE NEW TABLE In response you will get the table list along with the job request for each tables """ serializer_class = TableMetaSerializer queryset = TableMeta.objects.all() renderer_classes = [JSONRenderer] filterset_fields = [ "schema_name", "type", "status", "grouping__name", "dataset__name", ] ordering_fields = ["created_on", "modified_on"] ordering = ["-modified_on"] pagination_class = StandardResultsSetPagination permission_classes = [ UserHasDatasetChangeAccess & IsTableEditable, ] def get_queryset(self): if getattr(self, "swagger_fake_view", False): # queryset just for schema generation metadata return TableMeta.objects.none() return TableMeta.objects.filter( dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, "")) ) -
Django get Browser of user
I am trying to get the browser of the current logged in user. To do it I put this in the template {{ request.headers.user_agent }} It works but the output is this: (even if i try it with something like edge browser) Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4692.99 Safari/537.36 Edg/96.0.1072.69 My settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ...... ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Based on the browser I want to display a different content in the HTML. What is the best way to get the exact browser? -
Django how to upload CSV file using Form to populate postgres database and display all items in browser
Django 3.2.1, Python 3.6, Postgres database I am writing a small Django app that will use the browser to import products from an uploaded csv file via a Form and populate the database. I currently have the app set up so that users can manually add, edit, or delete individual products. These get saved to the database properly. However, I also want an option where a user can upload a csv with many thousands of products using a Django Form. I have written the backend logic for the app using Custom Management Commands and have read the docs but am still really unclear about how to achieve this using Forms while maintaining full functionality. I have tried many variations on using forms and completed the tutorials on Django's site, but have not been successful at actually getting the file to upload via Form, parse all lines correctly, save to database, and display all newly saved items at /show_products alongside where the products that have been manually added are displayed. Example of the csv file: name,sku,description Brian James,skus-will-look-like-this,The products will have various descriptions. And multiple lines too. Here is an example of my backend code that can upload a local csv … -
Structure of models to store a subset of choices to be available dependent on row being edited
I'm building a site that tracks parts, these part belong to a subsection of project, denoted by section codes. I want to be able to limit the choices of codes based on which project the part belongs to, but not sure the best way to store a list of acceptable codes. I started with: class Project(models.Model): name = models.CharField(max_length=40) number = models.IntegerField() class Section(models.Model): code = CharField(max_length=1) class Part(models.Model): number = models.IntegerField() project = models.ForeignKey(Project, on_delete=models.PROTECT) section = models.ForeignKey(Section, on_delete=models.PROTECT) The problem with this is that all parts then get to choose from the same list of section codes. -
models.py order of the models gives NameError: name 'Category/Post' is not defined
I'm new to Django so this is probably a dumb question but, when I put the class Category model above the class Post model I get an NameError: name 'Post' is not defined error. but when I try to put class Category model underneath the Post model (as in the code here) I get categories = models.ManyToManyField(Category) NameError: name 'Category' is not defined error. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) #if is deleted than delete their posts location = models.CharField(max_length=100, default="") tags = TaggableManager() likes = models.ManyToManyField(User, related_name='blog_posts') categories = models.ManyToManyField(Category) def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): post = models.ForeignKey(Post, related_name="categories") name = models.CharField(max_length=20) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Post, Comment, Category #, Konum # Register your models here. admin.site.register(Post) admin.site.register(Comment) admin.site.register(Category) #admin.site.register(Konum) -
Django href for html
How i can make link to this urls.py? I tried to pass the link through all the methods I know but they don't work and gave an error path('category/<slug:gender_slug>/<slug:category_slug>/', views.StuffCategory.as_view(), name='category'), html: {% get_genders as genders %} {% for gender in genders %} <li> <!-- First Tier Drop Down --> <label for="drop-2" class="toggle">Категории <span class="fa fa-angle-down" aria-hidden="true"></span> </label> <a href="/">{{ gender }} <span class="fa fa-angle-down" aria-hidden="true"></span></a> <input type="checkbox" id="drop-2"> <ul> {% get_categories as categories %} {% for category in categories %} <li><a href="/">{{category.name}}</a></li> {% endfor %} </ul> </li> {% endfor %} views.py class StuffCategory(ListView): model = Stuff template_name = 'shop/shop.html' context_object_name = 'stuffs' def get_queryset(self): queryset = Stuff.objects.filter(draft=False) if self.kwargs.get('category_slug'): queryset = queryset.filter(category__slug=self.kwargs['category_slug']) if self.kwargs.get('gender_slug'): queryset = queryset.filter(gender__slug=self.kwargs['gender_slug']) return queryset -
Cron jobs run ok as script but not @reboot
I'm running a Django (v3.1.7) application on a headless remote Ubuntu (v20.04.3) that I'm looking to have start at reboot using crontab. The script below runs all ok from the command line. I've been through here crontabs-reboot-only-works-for-root and the linked suggestions as well but still haven't identified the issue. I've added logging (see *.log below) but do not get any helpful output. /home/myapp/reboot.sh #!/bin/bash echo "$(date) Starting reboot.sh" start_django () { echo "$(date) Entering start_django" screen -S django -dm bash -c 'cd /home/myapp && /usr/local/bin/gunicorn myapp.wsgi:application --bind 0.0.0.0:8000' > /home/myapp/django_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_django" } start_stream () { echo "$(date) Entering start_stream" screen -S streaming -dm bash -c 'cd /home/myapp/data_api && python3 api_stream_client.py' > /home/myapp/stream_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_stream" } start_test () { echo "$(date) Entering start_test" screen -S testa -dm bash -c 'cd /home/myapp && exec bash' > /home/myapp/test_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_test" } if screen -list | grep -q "No Sockets found"; then echo "$(date) No screens available" echo "$(date) Starting test" start_test echo "$(date) Starting django" start_django echo "$(date) Starting stream" start_stream else if screen -list | grep -q "django"; then echo "$(date) django exists" else echo "$(date) … -
Caching TemplateView
I want to use cache from django to cache one template that makes expensive queries. I am not sure if I can just use render() in the get handler as in snippet below: class MyTemplateView(TemplateView): template_name = "my-template.html" def get(self, request, *args, **kwargs): cached = cache.get("my-view-response") if cached: return cached response = super().get(request, *args, **kwargs).render() # <--- cache.set("my-view-response", response) return response def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... # expensive queries return context Normally TemplateView.get returns TemplateResponse instance so by calling render it feels like I am skipping some steps. So my question is: is it ok to return string from TemplateView.get? inb4: The webpage loads correctly; I can't cache the TemplateResponse instance itself because it throws an exception; I have to use "low-level" cache API cause I am invalidating it when rows are added/deleted or modified (which will not happen often) -
How to list information on another page for a form
I am trying to make a question page where a user can click the questions ID. Upon clicking they will be redirected to another page to answer this question with the question text appearing and showing the multiple choice questions. How would I go around doing this? So far I have this Clicking number one will take the user to the question with the multiple choices for this question and question text Model from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=256, primary_key=True) Used = models.IntegerField(null=True, blank=True) password = None USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(primary_key= True ,max_length=256, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, … -
display video using django FileField uri [react-native]
Hi I'm working on a react-native and I want to display a video, using expo-av, a django FileField uri, here's my code: <Video source={{ uri: "my/django/HE7sU4ABuNRAvwpFfW3qME.MP4" }} onError={(e) => { console.log(e); }} /> Now the problem is that if I try to load a video using uri for django FileField video the following error occurs: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". How can I configure django to allow video displaying in react-native?