Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Axios post request is getting timed out after 4 minutes
Building React app. Using Axios to upload file. Simple post request with FormData and multipart/form-data header is getting time out after 4 minutes in Chrome and 2 minutes in Safari. As backend I'm using Django. In dev environment I'm using proxy parameter in package.json to connect to backend via localhost. As production environment I'm building static files via npm run build command and Django is serving them directly without any proxy like nginx. The issue is present in local/dev and production environment. Need help as I'm getting insane here, as any work around is not working. Thanks in advance. loadData = () => { let formData = new FormData(); formData.append('file', this.state.file); let path = `/path` this.setState({loading: true}); axios(path, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data' }, data: formData }) -
NoReverseMatch at /34/order/update/
Problem: When updating a form, I`ve got the following error: Reverse for 'detail_order' with keyword arguments '{'pk': 34}' not found. 1 pattern(s) tried: ['(?P<purchaseorder_id>[0-9]+)/detail_order$'] Error: The error comes from the way how I am writing the get_success_url and the url. def get_success_url(self): return reverse_lazy('accounting:detail_order', kwargs={'pk': self.object.pk}) How can I modify my view to link pk to purchaseorder_id? views.py class OrderUpdate(UpdateView): model = PurchaseOrder template_name = 'accounting/orders/edit_order.html' form_class = PurchaseOrderForm success_url = None def get_context_data(self, **kwargs): data = super(OrderUpdate, self).get_context_data(**kwargs) if self.request.POST: data['lines'] = OrderLineFormSet(self.request.POST, instance=self.object) else: data['lines'] = OrderLineFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() lines = context['lines'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if lines.is_valid(): lines.instance = self.object lines.save() return super(OrderUpdate, self).form_valid(form) def get_success_url(self): return reverse_lazy('accounting:detail_order', kwargs={'pk': self.object.pk}) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(OrderUpdate, self).dispatch(*args, **kwargs) @login_required(login_url="/login/") def detail_order(request, purchaseorder_id): order = get_object_or_404(PurchaseOrder, pk=purchaseorder_id) orderlines = OrderLine.objects.all() return render(request, 'accounting/orders/order_detail.html', {'order': order, 'orderlines': orderlines}) urls.py url(r'^(?P<purchaseorder_id>[0-9]+)/detail_order$', views.detail_order, name='detail_order'), -
Is it possible to integrate Moodle LMS with Django?
I've created a basic static website using Django and want to know is it possible to integrate Moodle LMS with my website. If yes then tell me how should I do it? Any help will be appreciated? -
Is it possible to make certain images in easy thumbnails to be png
I'm using easy-thumbnails in a django app. In order to print images to pdf using Weasyprint I need them as png files. The system already has thousands of jpg images and I don't really want to convert them all so I know I can have easy-thumbnails save as png by adding THUMBNAIL_EXTENSION = 'png' within settings.py but I would really like to set it a alias level. I've tried this THUMBNAIL_ALIASES = { '': { 'full_width_image': {'size': (2220, 0), 'upscale': False}, 'hero': {'size': (2220, 0), 'upscale': False}, 'content_width_image': {'size': (1520, 0), 'upscale': False}, 'awards_image': {'size': (50, 50)}, ... 'pdf_image': {'size' : (340, 200), 'extension':'png'}, }, } Didn't work. Is there a way to do this? Thanks -
ordering on custom calculated field in django-admin panel
i have following mentioned modelAdmin in django admin panel. right now i want to ordering on calculated field frequency i also tried admin_order_field on it. but it's not make sense at all. anyone has idea about to implement on different way. class LoginFrequencyAdmin(admin.ModelAdmin): list_display = ['frequency','company_name','company_id'] within = now() - timedelta(days = 30) # for fetching only past 30 days def frequency(self,obj): return self.model.objects.filter(object_pk = obj.object_pk,object_repr = "Access ERP",created_at__gte=self.within).count() def company_id(self, obj): try: return obj.action_info.get('company_id') if obj.action_info.get('company_id') else Company.get_by_id(obj.object_pk).id if obj.object_pk else '' except Company.DoesNotExist: return '' def company_name(self, obj): try: return obj.action_info.get('company_name') if obj.action_info.get('company_name') else Company.get_by_id(obj.object_pk).organisation_name if obj.object_pk else '' except Company.DoesNotExist: return '' -
How to convert Json to array?
I created a system with Django. In this system, I read a .xlsx file with panda and I convert it to JSON. I will make some operations and display them in my template. Because of that I want to convert it an array. Here are my codes: views.py, def test_view(request): # Financial Ratios fr = pd.read_excel('media/test.xlsx', usecols='A:G', skiprows=lambda x: x < 0 or x > 42, sheet_name='Scoring') json_fr = fr.to_json() context = { 'json_fr': json_fr } return render(request, 'json_test.html', context) How can I convert json_fr to an array? -
Django model test
I have a model and I want to test the borrowed_books function tests that I want to implement are these: checks if it returns None checks if the list content (genre) is not correct checks if the count is correct but the content is irrelevant checks if the member is wrong models.py from django.db import models # Create your models here. class Member(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def borrowed_books(self, genre): def borrowed_books(self, genre): borrowed_ids = Borrowed.objects.filter(member=self, book__genre=genre).values_list('book__id', flat=True) return list(borrowed_ids) def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): title = models.CharField(max_length=50) genre = models.CharField(max_length=50) def __str__(self): return self.title class Borrowed(models.Model): member = models.ForeignKey('Member', on_delete=models.CASCADE) book = models.ForeignKey('Book', on_delete=models.CASCADE) tests.py from django.test import TestCase from .models import * # Create your tests here. class Member_test(TestCase): def setUp(self): # MEMBER CLASS Member.objects.create(first_name='1', last_name='2') # BOOK CLASS Book.objects.create(title='x', genre='y') # BORROWED CLASS mem = Member.objects.get(first_name='1') boo = Book.objects.get(title='x') Borrowed.objects.create(member=mem, book=boo) def tests(self): # TESTS NONE RESULT mem = Member.objects.get(first_name='1') mem_books = mem.borrowed_books(genre='y') value = None self.assertIsNotNone(value, mem_books) # TESTS WRONG GENRE self.assertEqual(('y',), mem.borrowed_books(genre='y').values_list('book__genre').get()) # TESTS COUNT IS CORRECT BUT WRONG CONTENT self.assertListEqual(mem_books, mem.borrowed_books(genre='y')) # TESTS WRONG MEMBER borrowed_mem = Borrowed.objects.get(member=mem) self.assertEqual(mem, mem_books) coverage shows 78 percent and all of the assertions except … -
Django Http404 raise Http404 message not showing up
Please, help me I have been struggling with this error since hours I am getting no useful answer Link is here: Django Http404 message not showing up -
Django Paginating MCQ questions - Remembering responses across pages
I am new to Django and I am building a MCQ Quiz model. I want to display only 1 question per page. However, whenever I navigate through the pages, the checked radio button gets unchecked. Is there any way to remember the user's POST request while paginating? I have a Finish button on the last page and I don't want to create a button on every page to store the response. I went through remembering-checked-checkboxes-across-pages-whats-the-best-way but I want it to be done using Django and JavaScript. Here is my models.py from django.db import models from django.contrib.auth.models import User class Quiz(models.Model): name = models.CharField(max_length=120) topic = models.CharField(max_length=120) number_of_questions = models.IntegerField() time = models.IntegerField(help_text="duration of the quiz") required_score_to_pass = models.IntegerField(help_text="required score in %") created = models.DateTimeField(auto_now_add=True, null=True) expires = models.DateTimeField(null=True) def __str__(self): return f"{self.name}-{self.topic}" def get_questions(self): return self.question_set.all()[:self.number_of_questions] class Meta: verbose_name_plural = 'Quizes' class Question(models.Model): text = models.CharField(max_length=300) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) def get_answers(self): return self.answer_set.all() class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default = False) question = models.ForeignKey(Question, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"question: {self.question.text}, answer: {self.text}, correct: {self.correct}" class Result(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.FloatField() … -
Comment Form in Detail View using Ajax
I want to add comments without the page refreshing but when I submit the form I think the object on the page changes to a comment object instead of a question object so it gives me a .NoReverseMatch: Reverse for 'question_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['question/(?P[-a-zA-Z0-9_]+)/$'] error and when I delete the links from the page to see what happens I get a Failed lookup for key [comments] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'form': , 'view': <question.views.UserCommentForm object at 0x000001BF59A47310>}] My Views class QuestionDetailView(DetailView): model = Question template_name = 'question/question_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) comments = Comment.objects.filter(question=self.object) context['comments'] = comments context['form'] = CommentCreateForm return context class UserCommentForm(LoginRequiredMixin, CreateView): template_name = 'question/question_detail.html' form_class = CommentCreateForm model = Comment def form_valid(self, form): form.instance.author = self.request.user # question = Question.objects.get(slug=self.kwargs.get('slug')) # form.instance.question = question result = form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result':result, 'user':user}) # return super().form_valid(form) def get_success_url(self): return reverse('question:question_detail', kwargs={'slug': self.object.question.slug}) class QuestionView(View): def get(self, request, *args, **kwargs): view = QuestionDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = UserCommentForm.as_view() return view(request, *args, **kwargs) My Urls urlpatterns = [ # All Questions path('', views.QuestionListView.as_view(), name='question_list'), # Search Page path('search/', … -
How to send different emails for each individuals using django backend
I have a problem arises while sending emails to users my system takes too long for sending each different emails to users it single mail to multiple users is fine, but different mail to each user is time consuming I'm Using Sendinblue transactional email for sending email https://developers.sendinblue.com/reference#sendtransacemail -
The `.create()` method does not support writable dotted-source fields by default. Write an explicit `.create()` method for serializer
I am trying to enable post methods in my borrowedview to enable admins, select from current users, and also select from the available books. serializers.py class BookListSerializer(serializers.ModelSerializer): authors = serializers.SlugRelatedField(many = True, queryset = models.Author.objects.all(),slug_field = 'name',) #To represent the relationship as a string instead of id genre = serializers.SlugRelatedField(many = True,queryset = models.Genre.objects.all(),slug_field = 'name') class Meta: model = models.Book fields = ('name','authors','rating', 'genre') class BorrowedSerializer(serializers.ModelSerializer): who_borrowed = serializers.PrimaryKeyRelatedField(queryset = get_user_model().objects.all() ,source = 'who_borrowed.username',) name = serializers.PrimaryKeyRelatedField(queryset = models.Book.objects.all(), source = 'name.name',) #borrowed_date = serializers.DateTimeField(format = "%H:%M, %d-%m-%Y") #returned_date = serializers.DateTimeField(format = "%H:%M, %d-%m-%Y" ) class Meta: model = models.Borrowed fields = ('who_borrowed','name','has_returned','borrowed_date','returned_date',) Then my models models.py class Book(models.Model): name = models.CharField(max_length = 150,) #Name of books authors = models.ManyToManyField(Author,) genre = models.ManyToManyField(Genre) publisher = models.ForeignKey(Publisher, on_delete = models.SET_DEFAULT, default = '2') #A book should have a publisher will include a none field for books without publishers pub_date = models.DateField() price = models.DecimalField(max_digits = 10, decimal_places = 2) isbn = models.CharField(max_length = 13, unique = True, null = True, blank = True, validators = [MinLengthValidator(13)]) class Borrowed(models.Model): #Model for users borrowing and returning name = models.ForeignKey(Book, on_delete = models.CASCADE,) #Consider making one to many field borrowed_date = models.DateTimeField(auto_now_add = … -
Retrieve data from models created by django-allauth in views.py
I am using django-allauth for social login. The django-allauth creates models as shown below: I want to access the objects of the Social accounts model in my views.py. How can I do this? -
How can I change the image upload directory in Froala Text Editor?
I am using Django. I want the images uploaded in the blog post to be stores in "media//" -
Upload name and image from postman in Django
I'm trying to upload image and name from postman in Django. I'm able to store name but when I try to store Image it gives me this error - Error This how I'm uploading data-Posting data from postman Here is my code- Views.py @csrf_exempt def uploadApi(request, id=0): if request.method == 'GET': image = Images_model.objects.all() image_serializer = ImageSerializer(image, many=True) return JsonResponse(image_serializer.data, safe=False) elif request.method == 'POST': image = JSONParser().parse(request, request.FILES) image_serializer = ImageSerializer(data=image) if image_serializer.is_valid(): image_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to Add", safe=False) elif request.method == "PUT": image = JSONParser().parse(request) image_get = Images_model.objects.get(id=image['id']) image_serializer = ImageSerializer(image_get, data=image) if image_serializer.is_valid(): image_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update", safe=False) elif request.method == "DELETE": image = Images_model.objects.get(ID=id) image.delete() return JsonResponse("Deleted Successfully", safe=False) -
Is there a package in Django with article editor
I'm looking for a package with Django that could help to write article. Something in Django admin that could be the same editor as wikipedia when someone write an article : ad texte, ad title, ad image, ad link...., AD hyperlink... Thanks a lot if you have any idea. For the moment my dirty solution is to write HTML directly in the database. Gonzague -
How can I create an exe file for Django project
I am working on a project using Django, every time i wanna run the script, i enter the command line: >python manage.py runserver How can I create an exec file that will run this command and open the 127.8.0.0 address in my browser when i just click on it ? -
How to host multiple Django Project under sub domains with uWSGI and NGINX on single server?
I've been trying to deploy two Django projects on a single server using uWSGI and Unix socket Nginx, I've cross-checked the configuration it seems fine, but it behaves oddly. Let me give the project names A for first and B for second for better understanding and referencing. For both projects, I've set up uWSGI and Nginx setup as per this excellent article How To Serve Multiple Django Applications with uWSGI and Nginx in Ubuntu 20.04 Everything is working right emperor.uwsgi.service shows two uwsgi processes for each project A and B. There are socket files at the correct path. But when I tried to serve both with the different subdomain, let's say for A subdomain A.example.com and B subdomain B.example.com at port 80 using Nginx then A.example.com works fine, but B.example.com returns default Nginx page. Still, if I change the , B.example.com's config and use port 8000, it works fine at B.example.com:8000. A.conf symlinked to /etc/nginx/sites-enabled/A from /home/ubuntu/ProjA/nginx/A.conf upstream A_uwsgi { server unix:///run/uwsgi/A.sock fail_timeout=0; } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name A.example.com; # charset utf-8; # max upload size client_max_body_size … -
Making POST request using the requests library over an IAP protected resources does not work
I want to make post request to an API. The API is deployed on GKE over the Google Endpoint service and it's protected by IAP more precisely using google Identity. I want to POST from different sources. first, I want to POST from a serverless Google Cloud Function (python3.7). Then, I want to POST from another django application. I can connect to my API and do GET request with no issue. When I want to do POST request I have this error: {"detail":"CSRF Failed: Referer checking failed - no Referer."} I tried to add the csrf_exempt on my views and on my url but it does not change anything. In my settings.py I have this configuration for rest: REST_FRAMEWORK = { 'PAGE_SIZE': 100, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } I tried to remove the DEFAULT_PERMISSION_CLASSES on production because I read on another post that it could cause trouble but this has not solved my problem. If I let my view without any authentication_classes I have the csrf issue but if I add authentication_classes as follow: @method_decorator(ensure_csrf_cookie, name='dispatch') class DeviceCreate(generics.CreateAPIView): """ Create a new device User Must be staff """ … -
'str' object has no attribute 'decode' on djangorestframework_simplejwt
I was trying to follow this quick start from djangorestframework-simplejwt documentation with link https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html But I have problem when try to obtain token, and always return this error 'str' object has no attribute 'decode' -
Django multiple formset initial datas
I have a formset and a variable with lists of Queryset. I tried: views.py Itemformset = Itemform(initial=[ {'Item': request.session.get('product_ids')} ]) But it's empty and I know it is because in this variable are more than one value. How can I pass the values in the formset? Content of request.session.get('product_ids'): ['2', '1'] model of modelformset: class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey('Products', on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') Price = models.DecimalField('Price', max_digits=10, decimal_places=2) OrderNo = models.ForeignKey('Orders', on_delete=models.DO_NOTHING) -
How to only have one instance of task running in django-q
I created a schedule to repeat a task every 29 minutes with a timeout of 29 minutes using Django-q but when looking at the queued admin view(Using DjangoORM) it has created almost 40+ tasks and going. While having 5 of the same task running asynchronously. How do I set it up so that it only runs one task at a time one after the other? This is my current setup: # settings.py Q_CLUSTER = { 'name': 'cams', 'workers': 4, # 'timeout': 90, # 'retry': 120, 'queue_limit': 50, 'bulk': 10, 'orm': 'default' } # myapp/tasks.py # temp method to mimic how long my actual task takes to finish executing. def test(): sleep(1740) # sleep for 29 minutes # myapp/schedules.py # test schedule to run the correct task def test_schedule(): schedule( func='myapp.tasks.test', name='test method', schedule_type=Schedule.MINUTES, minutes=29, repeats=-1, q_options={'timeout': 1740, 'retry': 1741}, ) -
Why do I get the error "ModuleNotFoundError: No module named 'django-extensions'" when running startapp
I am learning Django through the dj4e course. In my project I have set up django-extensions for a previous section of the course. When I moved to a new section and created a new app with the code python manage.py startapp autos I get the error "ModuleNotFoundError: No module named 'django-extensions'" I have resolved this by commenting out 'django-extensions' in the settings.py file. However can anyone talk me through why this happened, I'm trying to get a better understanding of the processes. -
Django 3.1 Best way to Conditionally load statics
I'm new to django and currently trying to find an effective way to load css files in the django templating language depending on the current page. The url pattern is : path('invoices/', views.list, name='invoice_list'), path('invoices/new/', views.create, name='create_invoice'), path('invoices/<int:pk>/', views.edit, name='edit_invoice'), path('invoices/<int:pk>/lines/new', views.create_line, name='create_line'), path('invoices/<int:pk>/lines/<int:fk>', views.update_line, name='update_line'), In the base.html, this is what i'm doing: <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'invoice/css/common.css' %}"> {% if request.path == '/invoices/'%} <link rel="stylesheet" href="{% static 'invoice/css/invoice_list.css' %}"> {% endif %} {% if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path %} <link rel="stylesheet" href="{% static 'invoice/css/edit_invoice.css' %}"> {% endif %} <title>My invoices </title> </head> the {% if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path %} is not great at all and would like to know if there's a nicer way to do it regexp style maybe? Thanks in advance. -
DjangoUnicodeDecodeError in form
In our app there's organizations and organization admins. We have a tool to let them import a CSV file with their users into their organization. The CSV file gets parsed by csv.reader: [line for line in csv.reader(file_data, delimiter=',') if line] And regular dict with each user entry gets built with the expected fields. Then each user gets validated: for user_dict in users_dict: form = CSVUserForm(data=user_dict) if form.is_valid(): # do stuff Well, it's that very form.is_valid() line where the DjangoUnicodeDecodeError is thrown. The specific error message is: DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xcd in position 4: invalid continuation byte. You passed in 'GARC\xcdA' (<type 'str'>) Now, it seems the 'GARC\xcdA' string (of type str) doesn't ger properly converted at some point. I don't have access to the CSV file they uploaded, so I'm not sure whether the \xcd character was literally in CSV file, whether it's a product of pasting or whether that's just how Python interprets that character. In any case, it seems this CSV import tool is able to import special characters without issues, but every now and then we get this error. What's going on and how can I solve it? I'm using Python 2.7.14 and Django …