Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF : How to edit the default URLs generated by SimpleRouter?
I have a viewset as : class UserViewset(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): ... Router for this viewset is as : router = routers.SimpleRouter() router.register(r'(?P<uid>[^/.]+)/user', views.UserViewset) For the RetrieveModelMixin, I want to use this 'uid' parameter as in the url for retreiving the object, not the 'pk' parameter that DRF automatically appends to the URL. How can this be done ? -
Django-Haystack is not able to fetch the data in template .txt file
Below are my files. My issue is the print statement within index_queryset() prints all the record, but nothing is shown on the front-end. It says "No Result Found" for all the queries. models.py class Jobs(models.Model): ID = models.CharField(primary_key = True, max_length = 50) JOB_TITLE = models.TextField(db_index=True) JOB_COMPANY = models.TextField() JOB_LOCATION = models.TextField(db_index=True) JOB_SALARY = models.CharField(max_length= 200,null=True) search_indexes.py from haystack import indexes from .models import Jobs class JobIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) type = indexes.CharField(model_attr='JOB_TITLE') location = indexes.CharField(model_attr='JOB_LOCATION') def get_model(self): return Jobs def index_queryset(self,using=None): print(self.get_model().objects.all()) # prints all the objects return self.get_model().objects.all() search.html {% extends 'base.html' %} {% block content %} <h2>Searching</h2> <form method="get" action="."> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td> <input type="submit" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for result in object__list %} <p> <a href="{{ result.object.get_absolute_url }}">{{ result.object.JOB_TITLE }}</a> </p> {% empty %} <p>No results found.</p> {% endfor %} <p>"PAGE": {{ page.object_list }} </p> {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% else %} … -
Access denied in DRF testing even thought user has permission
I grant my test user all permissions and I still get acces denied response when testing. Everything works in production. I am using DjangoObjectPermissions in my permission classes. Deleting DjangoObjectPermissions results in granting permission in testing. Both delete and patch tests are failing. views.py class DeventDetailAPIView( generics.RetrieveAPIView, mixins.UpdateModelMixin, mixins.DestroyModelMixin): permission_classes = [permissions.IsAuthenticated, permissions.DjangoObjectPermissions] serializer_class = CalendarSerializer queryset = Devent.objects.all() def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) def patch(self, request, *args, **kwargs): day = Day.objects.get(date__iexact=request.data['day']).pk request.data['day'] = day return self.update(request, *args, **kwargs) test_api.py class TestDeventAPIView(APITestCase): @classmethod def setUpTestData(cls): cls.test_user1 = User.objects.create_user( username='testuser1', password='1X<ISRUkw+tuK') newgroup = Group.objects.create(name='testgroup') for each in Permission.objects.all(): newgroup.permissions.add(each) cls.test_user1.groups.add(newgroup) ( test data creation omitted from post) def test_patch_gets_pk(self): user = self.test_user1 token = get_token(user) data = { 'day':'2020-01-20', 'title':'test devent patch', 'description':'test description' } request = self.factory.patch( '/calendar/api/devent/1/', data, HTTP_AUTHORIZATION='JWT ' + token, format='json') view = DeventDetailAPIView.as_view() response = view(request, pk = 1) response.render() print(json.loads(response.content)) prints {'detail': 'You do not have permission to perform this action.'} -
How to find migrations of external installed django apps?
Given a number of external Django apps that I use in INSTALLED_APPS, I need to restore the whole db. I don't understand how I could access migrations folders for these external apps. Is there a way to find these migrations folders or to completely cancel all the made migrations? -
Get total played time with React Player
I am working on a video subscription site using Django and React. As we will have multiple people who want to make content for us, I would like to be able to track the time a user has spent in any video, then update the database by adding that time when the page is left. This is in order to know how much each video has contributed to our revenue. I am currently using React player to play videos, but I can easily transition to other type of player. Also, if anyone has a better way to track the time without using any player, I would appreciate any answer. <ReactPlayer url={this.state.lectie.link} controls type="video/mp4" /> -
Django how to pass context which inside if statement? [closed]
I getting this error Django local variable referenced before assignment def Count_Notifications(request): count_notifications_author = 0 if request.user.is_authenticated: commnet_user = BlogComment.objects.filter(user=request.user) if request.user == commnet_user: count_notifications_comment= 0 count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count() count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count() return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author} If add count_notifications_comment= 0 at the beginning then the error gone but actual count not showing in template. it's just showing 0 in my template: def Count_Notifications(request): count_notifications_comment= 0 count_notifications_author = 0 how to solve this problem??? how to pass the count_notifications_comment to template which inside my if statement? -
Customizing serializer response in django rest framework
I want to change the response format. I have my models as: class A(models.Model): a = models.ForeignKey(ab, blank=True, null=True, on_delete=models.CASCADE) b = models.ForeignKey(bc, blank=True, null=True, on_delete=models.CASCADE) My serializers.py class ASerializer(serializers.ModelSerializer): add = MymodelSerializer() #model bc serializer class Meta: model = A fields = ('id', 'add') class BASerializer(serializers.ModelSerializer): add= serializers.SerializerMethodField() def get_add(self, obj): b_id = A.objects.filter(a=obj.id) serializer = ASerializer(b_id, many=True) return serializer.data class Meta: model = ab My view is returning data as this: { "id": 2, "add": [ { "add": { "key":"value" } }, } ] }, I want it to be : { "id": 2, "add": [ { "key":"value" }, { "key":"value" }, } ] }, Where should the code be changed so that the ouput will be as above. -
How to implement change password modal form?
I have implemented authentification using Django django.contrib.auth and it work but I would like change_password to be displayed using modal form and Ajax. And I do not manage to even display the form inside modal (with all validation stuff). I have already use bootstrap modal to display information but not for form submission. As it did not call a change_password view that render change_password_form.html template, form is not available and I got an error Parameter "form" should contain a valid Django Form. How should I do this? urls.py class PasswordChangeView(SuccessMessageMixin, auth_views.PasswordChangeView): success_message = "Your password have been changed successfully." def get_success_url(self): return reverse('export:index') app_name = 'registration' urlpatterns = [ ... path('change_password/', PasswordChangeView.as_view(), name='password_change'), ... ] password_change_form.html {% extends 'layouts/base.html' %} {% load bootstrap4 %} {% load crispy_forms_tags %} {% load i18n %} {% block title %}{% trans 'Change password' %}{% endblock %} {% block content %} <div class="row justify-content-center" style="margin-top:100px;margin-left:0px;margin-right:0px"> <div class='col-6'> <div class='card' > <div style="background-color:#326690;padding:5px 5px 5px 16px;color:white;font-weight:bold;border-radius: 2px 2px 0 0;">Change password</div> <div class='card-body' style="padding-bottom:0px"> <form method="post" class="form-signin"> {% csrf_token %} {% bootstrap_form form layout="horizontal" placeholder="None" size="medium" label_class="form-label col-md-3" %} </div><hr style="margin:1px"> <div class='card-body' style="padding-top:5px;padding-bottom:5px;"> <div> <button type="submit" class="btn block" style="float:right;background-color:#326690;color:white;min-width:110px;">{% trans 'Confirm' %}</button> <a href="{% url … -
what is the best way to filter result in modelviewset per user?
I am creating an api with Django rest framework. I use only ModelViewsSet. I need the result of some viewset to be different depending on the user who makes the request. For the moment I have overloaded the get_query_set method for each ModelViewSet. This works very well, depending on the user the results are different for the "list" and also for the "read" which returns a 404 if the user tries to access an element he doesn't have the right to. def get_queryset(self): if self.request.user.is_staff: return cache.get_or_set( 'machine_machines_list', Machine.objects.all() \ .select_related('category') \ .prefetch_related('machine_stock') \ .prefetch_related('components'), 60) else: return cache.get_or_set( f'machine_machines_list_user_{self.request.user.pk}', Machine.objects.filter(site__user=self.request.user)\ .select_related('category') \ .prefetch_related('machine_stock') \ .prefetch_related('components'), 60) However I'm not sure if this is the best method or if it is really secure. Is it the right method? Or is there a better way to do it? -
sort data per datetime (python, django)
I am trying to sort my operation by date. The data is formed of couple columns similarly to the one drawn here: Company Income datetime X 520305 03.06.2020 11:20:00 Y 480305 06.06.2020 13:20:00 In my case for example, if the user inputs a start date of 10.05.2020 00:00:00 til 05.06.2020 10:00:00. the expected output would be only X. I hope I am being clear, sorry in advance if I am confusing. Here is what I did so far: def home(request): if request.method == 'POST': file = request.FILES['myFile'] csv = pd.read_csv(file) StartDate = request.POST.get('startdate') EndDate = request.POST.get('enddate') user_start = pd.to_datetime(StartDate) user_end = pd.to_datetime(EndDate) csv['Date'] = pd.to_datetime(csv['Date'], dayfirst=True) montant_init = csv.groupby("Initiateur")["Montant (centimes)"].sum() err_count = csv.groupby(['Résultat']).size() return render(request, "index.html", {'something': True, 'montant': montant_init, 'error': err_count}) html: {% if something %} <label for="startdate">Start Date (y.m.d h.m.s):</label> <input type="text" name="startdate"><br><br> <label for="enddate">End Date (y.m.d h.m.s):</label> <input type="text" name="enddate"><br><br> <input type="submit" name="submit"> <p>{{ montant }}</p> <p>{{ error }}</p> thank you -
Why is my post request is flagged as unauthorized when using AllowAny permission class
I have a request which take POST headers only and I have used the permission_classes([AllowAny]) decorator as below: @api_view(["POST"]) @permission_classes([AllowAny]) def endpoint(request): print(request.data) return Response({"status": "success"}, status=status.HTTP_200_OK) and have also tried switching order of decorators: @permission_classes([AllowAny]) @api_view(["POST"]) def endpoint(request): print(request.data) return Response({"status": "success"}, status=status.HTTP_200_OK) However whenever I make the request it is blocked as unauthorized. I have also tried to make the request crsf_excempt and that responds with - WSGIRequest object has no attribute 'data'. I am running on django 2.2.5 -
remove 'this field is required' text above django form
I cannot remove bullet points saying 'this field is required' above my django form (see picture). I have been through other questions and tried setting form.auto_id = False, form.use_required_attribute = False and form.label_suffix = "" I am not sure what attribute of the form is causing this to appear so don't know what to change. I couldn't find the answer in the docs here the .view function is def new_page(request): if request.method == "POST": form = WikiSubmitForm(request.POST) if form.is_valid(): # data cleaning? Title = form.cleaned_data["Title"] Body = form.cleaned_data["Body"] if Title in util.list_entries(): return HttpResponse("This wiki page already exists") else: util.save_entry(title=Title, content=Body) return HttpResponseRedirect("wiki/"+ Title) #would be better to make this not hardcoded! else: form = WikiSubmitForm(request.POST) # form.use_required_attribute = False return render(request, "encyclopedia/new_or_edit_page.html", { "new": True, "form": form }) The HTML file, called new_or_edit_page.html is: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1> {% if new %} <h1>New page</h1> {% else %} <h1>Edit page for {{ Title }}</h1> {% endif %} </h1> {% if new %} <form action="{% url 'new_page' %}", method="POST"> {% else %} <form action="{% url 'edit' Title %}", method="POST"> {% endif %} {% csrf_token %} <div> {{ form … -
Django select_related Not Working as Expected
I have 2 classes, Country and Coordinates. When making an API call to the Country table, I would like the API (using DRF) to return the related Coordinate information as well. By default, the following is understandably returned (localhost:8000/api/country/): { "id": 1, "name": "TestCountry", "coordinates": 1 } The problem is that after implementing select_related in my views.py file, and modifying the CountrySerializer as well, the output remains exactly the same. I had expected something like: { "id": 1, "name": "TestCountry", "coordinates": { "longitude": 123, "latitude": 456, } } Or even this would suffice: { "id": 1, "name": "TestCountry", "longitude": 123, "latitude": 456, } And here are the relevant code in models, views, and serializer files. class Coordinates(models.Model): longitude = models.DecimalField() latitude = models.DecimalField() class Country(models.Model): name = models.CharField() coordinatesID = models.ForeignKey(Coordinates, on_delete=models.SET_NULL, verbose_name="Coordinates", db_column="CoordinatesID", blank=True, null=True, related_name="coordinates") class CountryViewSet(viewsets.ReadOnlyModelViewSet): queryset = Country.objects.select_related('coordinatesID').all() serializer_class = CountrySerializer class CountrySerializer(DynamicFieldModelSerializer): longitude = serializers.ReadOnlyField(source='coordinates.longitude') latitude = serializers.ReadOnlyField(source='coordinates.latitude') class Meta: model = Country fields = '__all__' Additionally, in the Country table, I specified the related_name="coordinates", however select_related does not recognize this option, and I still have to use "coordinatesID" to reference the coordinate table. Is this a bug or related to incorrect implementation? -
How to get last_error of background_task_completedtask in django for a specific run
I use django-background-tasks to run queued tasks. the tasks are triggered by a client request and when a task fails, I want to show client the last_error field of background_task_completedtask table so they know why their request has failed. I tried the documents but did not find anything useful so I'd be glad if anyone shares a way to achieve this goal -
I am using Django Elasticsearch and currently I'm getting this kind of error:
from django_elasticsearch_dsl import ( Document, Index, fields ) from django_elasticsearch_dsl.registries import registry from accounts.models import Profile PUBLISHER_INDEX = Index('profile') @registry.register_document @PUBLISHER_INDEX.doc_type class DisbtrAdSale(Document): class Django: model = Profile fields = [ 'user', 'referral_id', 'phone_number', 'first_name', 'last_name', 'email' ] -
Django Rest Framework AttributeError 'CustomUser' object has no attribute 'user'
I have different types of users. That's why, each user type should have own profile details. So I am trying to code API for these profiles. However, I couldn't resolve this error. I am following an example from a course. My code is completely similar as this example. I don't understand where am I going wrong. It seems that I am making a mistake in reconciling the related models. I checked the aliases and tried over and over to solve it. I tried many alises to solve it but i couldn't be successful each time. Error message AttributeError at /api/account/child-profile-update Got AttributeError when attempting to get a value for field user on serializer ChildProfileSerializer. The serializer field might be named incorrectly and not match any attribute or key on the CustomUser instance. Original exception text was: 'CustomUser' object has no attribute 'user'. Custom User Model class CustomUser(AbstractUser): GENDER_CHOICES = ( (1, AccountStrings.CustomUserStrings.gender_choice_male), (2, AccountStrings.CustomUserStrings.gender_choice_female), (3, AccountStrings.CustomUserStrings.gender_choice_other), ) USER_TYPE_CHOICES = ( (1, AccountStrings.CustomUserStrings.user_type_choice_default), (2, AccountStrings.CustomUserStrings.user_type_choice_child), (3, AccountStrings.CustomUserStrings.user_type_choice_parent), (4, AccountStrings.CustomUserStrings.user_type_choice_instructor), ) objects = CustomUserManager() email = models.EmailField(max_length=255, unique=True, null=False, blank=False) identity_number = models.CharField( max_length=11, unique=True, verbose_name=AccountStrings.CustomUserStrings. identity_number_verbose_name) birth_date = models.DateField( null=True, blank=True, verbose_name=AccountStrings.CustomUserStrings.birth_date_verbose_name) gender = models.PositiveSmallIntegerField( choices=GENDER_CHOICES, default=1, verbose_name=AccountStrings.CustomUserStrings.gender_verbose_name) user_type = models.PositiveSmallIntegerField( … -
Django aggregating records for each foreign key
class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey( Category, null=True, on_delete=models.SET_NULL ) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) placed = models.DateTimeField(auto_now=True) shipped = models.DateTimeField(null=True) delivered = models.DateTimeField(null=True) I want to calculate statistics on how fast the order has been processed for each category where process time is delivered - shipped In result I want to achieve something like this: [ { "category": <category 1> "processed_time": <average processed time in seconds> }, { "category": <category 2> "processed_time": <average processed time in seconds> }, { "category": <category 3> "processed_time": <average processed time in seconds> }, ] I can calculate this outside of the ORM but I'd like to achieve this somehow with annotation/aggregation delivered = delivered_qs.annotate(first_processed=Min("delivered"), last_processed=Max("delivered")) \ .aggregate(processed_time=F("last_processed")-F("first_processed")) This QS returns time only for all categories and I dont know how to retrieve time for each individual category -
Using double url tag in django
I got two urls.py file first one is for project urls.py urlpatterns = [ path('admin/', admin.site.urls , name = 'admin'), path('',homeView, name='home'), path('post/',post, name='post'), path('post/',include('post.urls'), name='posturl'), path('student/',studentM, name = 'student' ), path('student/',include('student.urls') , name='studenturl'), ] second one is url for app urlpatterns = [ path('index', post_index, name = 'index'), path('details/' + '<int:id>', post_detail, name = 'detail'), path('create', post_create, name = 'create'), path('update', post_update , name = 'update'), path('delete', post_delete , name = 'delete'), ] I am trying to reach the adress like :8000/post/details/5 but when i try to use in html <a href = "{ % url 'post.detail' %}"> =>> {{post.id}}</a> <a href = "{ % url 'detail' %}"> =>> {{post.id}}</a> <a href = "{ % url 'post' %}"> =>> {{post.id}}</a> None of these are not working I got 404 error. How can I reach the link which I want def post(request): context = { } return render(request,'post/post.html',context) def post_detail(request,id): post = get_object_or_404(Post,id=id) context = { 'post' : post } return render(request,"post/details.html",context) -
Issue with using django celery when django signals is being used to sent email?
I have used the default Django admin panel as my backend. I have a Blogpost model. What I am trying to do is whenever an admin user saves a blogpost object on Django admin, I need to send an email to the newsletter subscribers notifying them that there is a new blog on the website. I have to send mass emails so I am using django-celery. Also, I am using django signals to trigger the send email function. But Right now, I am sending without using celery but it is too slow. class Subscribers(models.Model): email = models.EmailField(unique=True) date_subscribed = models.DateField(auto_now_add=True) def __str__(self): return self.email class Meta: verbose_name_plural = "Newsletter Subscribers" # binding signal: @receiver(post_save,sender=BlogPost) def send_mails(sender,instance,created,**kwargs): subscribers = Subscribers.objects.all() if created: blog = BlogPost.objects.latest('date_created') for abc in subscribers: emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) else: return Using celery documentation i have written following files. My celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE','travel_crm.settings') app = Celery('travel_crm') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Mu init file: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ … -
How can I attach a newly created file to the model
The user adds a video and a watermark is automatically applied to the video. It turns out to process the user's video and put a watermark, but I don't know how to attach this video to the model, so that later this video with a watermark would be displayed on the site. Just attach obj.video_uploaded = final_ to the model - it doesn't work, writes the error object has no attribute '_committed' model.py class Video(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') photo = models.ImageField(upload_to='photo/%Y/%m/%d') video_uploaded = models.FileField(upload_to='video/%Y/%m/%d',blank=True,null=True) views.py def add_video(request): if request.method == "POST": form = VideoUploaderForm( data=request.POST, files=request.FILES, ) if form.is_valid(): obj = form.save(commit=False) vid = request.FILES['video_uploaded'] clip = VideoFileClip(vid.temporary_file_path()) # watermark video = VideoFileClip(clip.filename) logo = (ImageClip('faiklogo.png') .set_duration(video.duration) .resize(height=50) .margin(right=8, top=8, opacity=0) .set_pos(("center", "bottom"))) final_ = CompositeVideoClip([video, logo]) final_.write_videofile('media/video/videwithwatermark.mp4') obj.save() else: form=VideoUploaderForm() return render(request, 'firstapp/add_video.html', {"foenter code hererm": form}) form.py class VideoUploaderForm(forms.ModelForm): class Meta: model = Video fields = '__all__' -
How can I Create Stripe Checkout Session for multiple products with Django and JavaScript?
I'm building a site with a few products for purchase using Django and Stripe Checkout. I can get the checkout page for one product without a problem. But what I would like to do is create a checkout page with multiple products. This is my function in my Django views.py. Note that it takes product name as a parameter. If I hard code my stripe products into the line_items I can get a checkout session with multiple products. def create_stripe_checkout_session(request, product_name): domain_url = 'http://localhost:5000/' try: checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], shipping_rates=[''], shipping_address_collection={'allowed_countries': ['US', 'CA']}, metadata={'product_name': product_name, }, line_items=[{'price': PRODUCTS_STRIPE_PRICING_ID[product_name], 'quantity': 1, 'adjustable_quantity': {'enabled': True, 'minimum': 1, 'maximum': 10, }, }], mode='payment', success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled.html',) return JsonResponse({'id': checkout_session.id}) except Exception as e: print(e) raise SuspiciousOperation(e) Where I'm struggling is with my JavaScript fetch. My .html page has a bunch of product buttons with class 'buy-button' as well as unique button values and add/subtract to cart buttons. I'm able to keep track of how many and which products I need to create a checkout session for. I just can't figure out how to replace the JS productName variable with an object literal/dictionary or other data structure that I can pass … -
Django admin page redirecting to the same login page even after providing correct credentails
I'm working on a django project where i cant access the admin page when deployed to Digitalocean droplet with nginx/gunicorn , it is redirecting to the same login page again and again However when i run the server using python manage.py runserver on port 80 , it works fine -
ParseError On Django Restframework
I have created a Custom user Model for my project, using Django 3.2. To POST/PUT the details in the user I am using restframework. But while giving the data for "PUT" operation to change some change I am getting the error as JSON parse error - Expecting value: line 1 column 1 (char 0) def update_masteruser(request,pk): try: user = MasterUser.objects.get(pk=pk) except MasterUser.DoesNotExist: return JsonResponse({'message': 'The User does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == "PUT": user_data = JSONParser().parse(request) #problem seems to be on this line serializer = RegisterUserSerializer(user, data=user_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I searched the error cause, but couldnt find the reason on it. Why cant it parse the data from request? -
Error 404 serving media files in a Django app hosted on DigitalOcean
I am making a small Django app and I want to use files uploaded via Django admin panel in production This is from my settings.py file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '' MEDIA_ROOT = BASE_DIR I trust admin uploaded files and want to serve them easily(without Amazon S3 and similar services), so i tried to place the uploaded files with other static files image = models.ImageField(upload_to='static/images') After uploading an image via admin panel i run python manage.py collectstatic in the DigitalOcean console. Whenever i try to access the image i get Error 404, while all other static files(which are real static files, not uploaded via admin panel) load successfully I did the same thing locally and there is no problem, everything loads as expected(DEBUG=True is set both locally and on DigitalOcean). Is it some security measure that doesnt let uploaded files end up in static? How can i bypass it if i trust files uploaded via admin panel? -
Django, celery and kombu: how to allow pickle?
I want to use picker as the celery serializer. I'm getting a kombu error that pickle is not allowed. Celery documentation says (https://docs.celeryproject.org/projects/kombu/en/master/userguide/serialization.html#guide-serialization) By default Kombu will only load JSON messages, so if you want to use other serialization format you must explicitly enable them in your consumer by using the accept argument: But I have no idea how to implement that. I have celery[redis]==5.1.2 and in my project's settings.py I have tried CELERY_TASK_SERIALIZER = 'pickle' which leads to the error. (This setting is not documented here, is it old? https://docs.celeryproject.org/en/stable/userguide/configuration.html#task-settings)