Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give permission to users of one group to create users of another group?
I want to create an application in which only organizations can register themselves and then they register their students. I can't find a way to do it. Is it possible to do it without making the organization as admin as multiple organizations can register on app. This is my user model. ''' from django.db import models import uuid from django.contrib.auth.models import User class OrganizationModel(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) email = models.EmailField(max_length=250,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE) organization_name = models.CharField(max_length=264,unique=True) is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['organization'] def __str__(self): return self.organization_name class StudentModel(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) email = models.EmailField(max_length=250,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE) roll_no = models.CharField(max_length=20) organization_name = models.ForeignKey(OrganizationModel,to_field="organization_name",on_delete=models.CASCADE,related_name="student") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['organization','roll_no'] def __str__(self): return self.organization_name class Meta: constraints = [ models.UniqueConstraint(fields=['organization_name', 'roll_no'], name='unique_student') ] ''' -
Django Celery, Celery beat workers
In celery I've 3 types of tasks first task executes in every 3 minutes and take almost 1 minute to complete, second task is periodic which runs on every monday and takes almost 10 minutes to complete, the third and last one is for sending users emails for register/forget password, I'm confused how many workers/ celery beat instances I should use, can anyone help me out please? -
check if someone already answered the post Question in Django
I am building a discussion Forum where user can ask question and can reply on other's questions. I want to show "Answered" if the Question is already answered and show "Not answered yet" if Question is not answered by any user My model.py class Post(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post_id = models.AutoField post_content = models.CharField(max_length=5000) timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' class Replie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) reply_id = models.AutoField reply_content = models.CharField(max_length=5000) post = models.ForeignKey(Post, on_delete=models.CASCADE, default='') timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' View.py def forum(request): user = request.user profile = Profile.objects.all() if request.method=="POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect('/forum') return render(request, "discussion.html", {'post':post, 'replies':replies}) -
getting ModuleNotFoundError at /admin/login/. How to solve this error
While login in as a superuser getting this error. Below I have mentioned the installed app and middleware in settings.py and I have gotten the error named ModuleNotFoundError. Exception Type: ModuleNotFoundError Exception Value: No module named 'account.backends' Exception Location: , line 973, in _find_and_load_unlocked Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 3.2.13 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chatbot_app', 'account'] Installed Middleware: ['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'] error Traceback (most recent call last): File "D:\PROJECTS\src\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\PROJECTS\src\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PROJECTS\src\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 398, in login **self.each_context(request), File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 316, in each_context 'available_apps': self.get_app_list(request), File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 505, in get_app_list app_dict = self._build_app_dict(request) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 450, in _build_app_dict has_module_perms = model_admin.has_module_permission(request) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\options.py", line 548, in has_module_permission return request.user.has_module_perms(self.opts.app_label) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth\models.py", line 458, in has_module_perms return user_has_module_perms(self, module) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth\models.py", line 221, in user_has_module_perms for backend in auth.get_backends(): File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 38, in get_backends return get_backends(return_tuples=False) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 27, in get_backends backend = load_backend(backend_path) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 21, in load_backend return import_string(path)() File "D:\PROJECTS\src\lib\site-packages\django\utils\module_loading.py", … -
Create folder and subfolder with django app
Maybe this is to trivial question, but please assist me. How can I create folder and subfolder in it with django python. When I google I just get some information about folder structure, but it is not what I am looking for. Please share some code examples if it is possible Many thanks. -
How can i make different login for buyer and seller ? then they will redirect their own profile
details about the questions .................................................................................................................................................................................................... ##I follow this post same to same. ###https://areebaseher04.medium.com/how-to-implement-multiple-user-type-registration-using-django-rest-auth-39c749b838ea ''' ##core/models.py) from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): #Boolean fields to select the type of account. is_seller = models.BooleanField(default=False) is_buyer = models.BooleanField(default=False) class Seller(models.Model): seller = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) area = models.CharField(max_length=100) address = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.seller.username class Buyer(models.Model): buyer = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.CharField(max_length=100) def __str__(self): return self.buyer.username #serializers.py from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from rest_framework.authtoken.models import Token from core.models import Seller, Buyer class SellerCustomRegistrationSerializer(RegisterSerializer): seller = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False area = serializers.CharField(required=True) address = serializers.CharField(required=True) description = serializers.CharField(required=True) def get_cleaned_data(self): data = super(SellerCustomRegistrationSerializer, self).get_cleaned_data() extra_data = { 'area' : self.validated_data.get('area', ''), 'address' : self.validated_data.get('address', ''), 'description': self.validated_data.get('description', ''), } data.update(extra_data) return data def save(self, request): user = super(SellerCustomRegistrationSerializer, self).save(request) user.is_seller = True user.save() seller = Seller(seller=user, area=self.cleaned_data.get('area'), address=self.cleaned_data.get('address'), description=self.cleaned_data.get('description')) seller.save() return user class BuyerCustomRegistrationSerializer(RegisterSerializer): buyer = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False country = serializers.CharField(required=True) def get_cleaned_data(self): data = super(BuyerCustomRegistrationSerializer, self).get_cleaned_data() extra_data = { 'country' : self.validated_data.get('country', ''), } data.update(extra_data) return data def save(self, request): user = super(BuyerCustomRegistrationSerializer, self).save(request) user.is_buyer = True … -
Comment POST request working but comments not appearing under post
I'm relatively new to all this. I'm in the process of creating a social media page with django/python. The ability to create a post in a news feed (i.e. list of posts) and the ability to click on one post to see a more detailed view is working properly. When a user clicks on a single post to see it in more detail they also have the ability to add a comment.Here's the problem: the 'create a comment' input box is working fine, as is the 'post comment' button, but when you click the 'post comment' button my terminal does show that the comment is being posted, but the list of comments never appears. What appears in my Powershell/Terminal when I click the 'post comment' button: [DD/MONTH/2022 HH:MM:SS] "POST /social/post/5 HTTP/1.1" 200 3995 screenshot of what appears on my website my settings.py installed apps: INSTALLED_APPS = [ 'social', 'landing', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_bootstrap5', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.facebook', ] my views.py: from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.views import View from django.views.generic.edit import UpdateView, DeleteView from .models import Post, Comment from .forms import PostForm, CommentForm class … -
Django corsheaders not affecting staticfiles - CORS errors only on static content
I've been successfully using CORS_ORIGIN_ALLOW_ALL = True with my views and I have been able to serve Django views to other domains, no problem. Now, I replaced a call to view to just getting a static file, and this is failing with a CORS error. This is not a problem in production, because I don't use Django to serve static files in production. Yet, how can I enable CORS_ORIGIN_ALLOW_ALL for staticfiles in development? -
digital ocean deployment error: 502 Bad Gateway
I had my site up and running, but the admin CSS was not loading, I am not sure what I did that the server did not agree, but now the entire site is down with a 502 Bad Gateway message. Here are the content of some key files sudo nano /etc/systemd/system/gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn.service file (sudo nano /etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=eson Group=www-data WorkingDirectory=/home/eson/example ExecStart=/home/eson/example/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ example.wsgi:application [Install] WantedBy=multi-user.target Here is what Nginx has sudo nano /etc/nginx/sites-available/example: server { server_name www.example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/eson/example; } location /media/ { root /home/eson/example; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.example.com example.com; return 404; # managed by Certbot … -
Django Can't recreate Database table?
Unfortunately I deleted two database table from my phpmyadmin database, I deleted migration file from corresponding app, and run this two command python manage.py makemigrations app_name python manage.py migrate But still cant recreate my database table. how to fix this issue? -
Django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net'
After starting project django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' or FileNotFoundError: [Errno 2] No such file or directory: '/proc/5390/task/56199' Full trace of OSError: 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 "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 638, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 623, in start_django reloader.run(django_main_thread) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 329, in run self.run_loop() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 335, in run_loop next(ticker) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 375, in tick for filepath, mtime in self.snapshot_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 391, in snapshot_files for file in self.watched_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 294, in watched_files yield from directory.glob(pattern) File "/usr/lib/python3.8/pathlib.py", line 1140, in glob for p in selector.select_from(self): File "/usr/lib/python3.8/pathlib.py", line 587, in _select_from for p in successor_select(starting_point, is_dir, exists, scandir): File "/usr/lib/python3.8/pathlib.py", line 535, in _select_from entries = list(scandir_it) OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' Trace of … -
How to run pytest on Get or Post 200 in Django?
I want pytest to call a function that can run if a REST API post or entry in django is successfull? My project is a django rest framework project and the field is routed as a URL having a single field only My field is called raddress as you can see in the urls.py below from django.contrib import admin from django.urls import path, include from rest_framework import routers from rframe import views ###this gets rid of admin authentication class AccessUser: has_module_perms = has_perm = __getattr__ = lambda s,*a,**kw: True admin.site.has_permission = lambda r: setattr(r, 'user', AccessUser()) or True ###### router = routers.DefaultRouter() router.register(r'raddress', views.RaddressViewSet, basename='raddress') #router.register(r'admin',) #router.register(r'users', views.CheckRaddr) #router.register(r'raddress', views.OrganizationViewSet, basename='raddress') urlpatterns = [ path(r'', include(router.urls)), path('admin/', admin.site.urls), As you can see the view is registered as a URL and I don't know how can I test if the post is successful -
Django middleware runs before drf permissions
I have a middleware class that looks something like this: class DogMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): dog_id = view_kwargs.get("dog_id") if dog_id is not None: dog = Dog.objects.get(id=dog_id) request.dog = dog I have a view that looks something like this: class DogDetail(APIView): def get(self, request, dog_id, *args, **kwargs): return "some nice doggy info" My permissions default to IsAuthenticated: "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), When I call the DogDetail view from a logged-out state, with a dog that doesn't exist, I get a 500 error, and a DoesNotExist exception. I infer from this that the middleware runs before the permissions. My questions: Is this expected behavior? If not, what am I doing wrong? If so, it is very un-ideal, because it would be very easy to leak data through middleware. In my example, it would be very easy for a un-authenticated user to determine which dog_id's existed. What is a good way to mitigate this? I guess I could check for authentication in the middleware, and pass unauthenticated requests through without getting the dog_id? That feels like I'm headed for a deep bug in the future where middleware runs properly, … -
How does Instagram use django for both web and mobile app?
I found that Django rest framework is needed to build both Progressive web app and mobile app.. Instagram uses django for backend, React.js for web, native for mobile Here is the question.. DRF might be too slow to be used by millions of people.. isnt it? How instagram sticks django with both PWA and mobile? What tech they use? -
Is it possible to share the same session for multiple domain names in Django?
I have a Django application (domain name: app.com) that allows users to create a template and host it on a subdomain (example.app.com) using the Django sites framework. Using this option: SESSION_COOKIE_DOMAIN=".app.com" The sites under this domain share the same session but once the user hosts the template on his domain name (custom.com) each site has its own session. Is it possible to make all the sites of this Django application share the same session? Why? So I don't have to log in again each time I visit one of these websites. I tried this middleware but still not working. import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import http_date from django.contrib.sessions.middleware import SessionMiddleware class SessionHostDomainMiddleware(SessionMiddleware): def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session … -
How can I count total likes?
I added a like button to my blog. It's working perfectly but I can't count the total number of likes present. What should I do now? models.py: class FAQ(models.Model): likes = models.ManyToManyField(User,default=None, related_name="faqLIKES") views.py: def index(request): allFAQ = FAQ.objects.all() context = {"allFAQ":allFAQ} return render(request,'0_index.html',context) def likeView(request, pk): post = get_object_or_404(FAQ, id=request.POST.get('faqLIKEid')) post.likes.add(request.user) return redirect("/") -
Django initial migrate of existing Application
I have an application with everything working on local dev machine, and I am trying to set it up on another dev machine with fresh DB (Postgres). I wasnt able to run migrations due to a cannot find field error, so i removed all migrations and tried to make them again, but same error. django.db.utils.ProgrammingError: relation "questionnaire_projectquestionanswerchoice" does not exist LINE 1: ...rojectquestionanswerchoice"."id") AS "count" FROM "questionn... So it seems that makemigrations checks code for issues before it makes them, and obviously it wont find them and always errors. The culprit is below, and commenting out, then doing the migrations works but is a bit of a hack, so if i ever need to do again i would have to follow same process. I have left the culprit commented below. This code works, and then i have to uncomment after. Is there an official way to handle this? class ProjectQuestionMostUsedAnswerChoiceViewset(viewsets.ModelViewSet): # dupes = ( # models.ProjectQuestionAnswerChoice.objects.values("name") # .annotate(count=Count("id")) # .order_by("-count") # .filter(count__gt=0)[:10] # ) # queryset = ( # models.ProjectQuestionAnswerChoice.objects.filter( # name__in=[item["name"] for item in dupes] # ) # .distinct("name") # .order_by("name") # ) queryset = models.ProjectQuestionAnswerChoice.objects.all() serializer_class = serializers.ProjectQuestionAnswerChoiceSerializer filter_backends = ( filters.QueryParameterValidationFilter, django_filters.DjangoFilterBackend, ) filterset_fields = { "id": … -
Filter objects that have a foreign key from another object - Django
I want to filter Employee, only those that have a ForeignKey, how to do it? My solution does not returned any results. Models.py class Employee(models.Model): name = models.CharField(max_length=200) class ExperienceCategory(models.Model): name = models.CharField(max_length=100, unique=True) class Experience(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) category = models.ForeignKey(ExperienceCategory, on_delete=models.CASCADE) Views.py experience_category = *ExperienceCategory object (1)* #solution - final query employee_query = Employee.objects.filter(experience__category = experience_category) How to get employees who have a foreign key from Experience? -
Django runserver hangs on Apple M1 macbook
I have django 3.2.12 application. It is running in docker with image python:3.9.12-slim-buster. When I'm accessing my app through web browser, it often hangs for some time (request pretty always takes exactly 5s - weird). This happens on chrome, firefox, safari. But only on Macbook with M1 CPU, on intel works fine. This problem only exist on runserver, it doesn't exist on gunicorn. The only solution, which I found, is to add '--nothreading' but this is not really a solution. Do you maybe know what can be an issue here? -
Git Bash automaticaly quits the server
When I use a command py manage.py runserverin Git Bash i get: "Watching for file changes with StatReloader" but nothing happens. If i press "Ctrl+C" i get URL and the server instantly stops https://i.stack.imgur.com/J7LWr.png If I don't press "Ctrl+C" but print http://localhost:8000/ in browser myself - URL works P.S. In Cmd everything works properly -
Does Django support all types of website templates(downloaded from web) that have different styles.?
enter image description here When i used a template to my project the styles dont appear correctly. What am i doing wrong? -
Django admin: Editing records with unique fields fails
Python 3.9, Django 3.2, Database is PostgreSQL hosted on ElephantSQL. I have a model, with a slug-field which I have set to unique: class website_category(models.Model): fld1 = models.CharField(primary_key=True, max_length=8) fld2 = models.TextField() fld3 = models.SlugField(unique=True, db_index=True, max_length=100) I can create new records for this model without any issue. However, when I try to edit an already existing record via the Django admin interface (e.g., change the text field - fld2), Django throws this error: website_category with this fld3 already exists I can delete the said record and re-enter the modified one without any issues. I can edit the record if I change the slug field but not otherwise. My guess is this is happening due to the "unique=True" set in the slug field (fld3). However, I do want the slugs to be unique. Is this an expected behaviour of Django or can I do something to make it possible for me to edit the records directly without having to delete and recreate them? -
Wagtail {{document.url}} is returning a 404 for user-uploaded files, in production
I've inherited a Wagtail CMS project but have been unable to solve an issue relating to document uploads. Having uploaded a file through the CMS, it arrives in the documents directory /var/www/example.com/wagtail/media/documents/test_pdf.pdf which maps to the /usr/src/app/media/documents/test_pdf.pdf directory inside the docker container. In the front end (and within the Wagtail dashboard) the document.url resolves to https://example.com/documents/9/test_pdf.pdf/ which returns a 404. Obviously the model number segment is missing from the file path above, but I read on a forum that In Wagtail, documents are always served through a Django view (wagtail.wagtaildocs.views.serve.serve) so that we can perform additional processing on document downloads so perhaps this, in itself, is not an issue. There are a couple of lines in urls.py file which look correct: urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), url(r'^sitemap\.xml$', sitemap), url(r'', include(wagtail_urls)), # url(r'^pages/', include(wagtail_urls)), ] if settings.DEBUG: ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and in base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ So, my hunch is one of either: Uploads being stored incorrectly, in a single folder rather than in subdirectories by model The routing to this “virtual” directory is broken, so it’s breaking at the "check permissions" stage (but I couldn't figure out … -
remove first and last quote from python list
I have a list list = ['1,2,3,4,5,6,7'] I want my list as under: desire output = [1,2,3,4,5,6,7] how to get this, i read other similar answer where strip method used. i had tried strip but strip method not work with list, it work with strings. 'list' object has no attribute 'strip' -
Upload files and send to API with Javascript
I want to receive a file from the user in the frontend and send it to the API so it can be stored, alongside with some other data. However, in the backend (Django), I only receive the path for that file instead of the file itself and I'm sending the data with the "multipart/form-data" encoding type. HTML: <input [(ngModel)]="file" type="file" id="file" name="file" accept=".edf" required> TypeScript service: submitEEG(patientID: string, operatorID: string, file: File) : Observable<EEG> { let formData = new FormData(); formData.append("file", file); formData.append('patientID', patientID); formData.append('operatorID', operatorID); console.log(patientID); console.log(operatorID); console.log(file); return this.http.post<any>(this.BASE_URL + 'createEEG', formData); Data received in the REST API: Can someone help me? Thanks!