Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't copy content from an html tag into another django template
Good night friends. I'm trying to display the content of a tag in a template, in another template, using the django "extends" method. Works perfectly with when it comes to "normal", "typed" content: this works: {% block part_of_site %} <div id='tag2'>Context</div> {% endblock %} using a variable, you can't copy to another template: {% block part_of_site %} <div id='tag2'>{{ variable }}</div> {% endblock %} -
can i make registration form using python and mysql to show it on profile page?
I want to make a registration and login system but I don't know how to connect form to python and mysql , and then can i get the data and put it in the profile page? how can I take the same data and put in the profile page like variables it'll be changing with every user I tried using Django with Mysql but every time I try using something , another function stops. -
How to display code as code with color using python django
how can I display code as code in the browser using python django. Example if True: print("Hello World") I want the above code to be displayed in the browser with different colors -
Disable logging bad requests while unittest django app
I have a tests in my Django app. They're working well, but i want to disable showing console logging like .Bad Request: /api/v1/users/register/ One of my tests code def test_user_register_username_error(self): data = { 'username': 'us', 'email': 'mail@mail.mail', 'password': 'pass123123', 'password_again': 'pass123123' } url = self.register_url response = client.post(url, data=data) self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.filter(username='us').first()) Console output Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .Bad Request: /api/v1/users/register/ ---------------------------------------------------------------------- Ran 1 tests in 0.414s OK Everything works nice, but i want to disable Bad Request: /api/v1/users/register/ output to console. I double checked, there's no print or logging functions, that can possibly log this to console. How can i disable messages like Bad Request: /api/v1/users/register/ logging while tests -
mod_wsgi on Python 3.10 does not update Django templates without Apache restart
I have been running a Django server on Python 3.8 with Apache and mod_wsgi for some time now, and decided it was time to upgrade to Python 3.10. I installed Python 3.10 on my server, installed the Django and mod_wsgi packages, copied the 3.10 build of mod_wsgi.so to Apache's modules folder, and everything works great ... however, it seems with this build of mod_wsgi, changes to template files do not take effect unless I restart Apache. As an example, I added a random HTML template file to my website, and started the server with some initial text in that template. Running on the Python 3.8, I am able to change the contents of that template (e.g. echo "More Text" >> test_template.html) and upon refreshing my browser the new text will show up. However doing the same test in 3.10, the new text will not show up. I have tried different browser sessions and hard reloading, it is not a caching issue on the client side, and looking at the response sizes in Apache's access log confirms the data being sent to the client changes in 3.8 but not in 3.10. I have stood up a test server to isolate the … -
Need random number generated in html for embedding into iframe
I am using this embed code for a site. The site is a Django site. I apologize if my terms are wrong, I'm not a developer. . Periodically I return to the site and the graph will not display, but the logo from the host site does. I suspect that it's a caching issue. I tried "no-store" but I'm not sure if I pasted it in properly. I want to add a random number generator to the embed code. In my mind that would be similar to a refresh - again, not a programmer. Django strips css and possibly more. Can anyone either solve my problem or write the random number generator to make the "border-width" 1, 2, or 3? Here is my site with the bug. https://www.twelvebridges.com/twelve-bridges-market-report/. I encounter the bug on Chrome on a macbook. Never the first visit and a refresh solves it every time. I tried "no-store" but probably in the wrong place. I tried Classic Cache Killer as a Chrome extension on my site. I added a gif on the site even though I cannot really articulate what I thought that would accomplish. -
upload larger files with python , Django and IIS server
I have file upload code in Django + python and I have my site register with IIS server. when running python code from command prompt on localhost:5000 and upload larger files (275 MB) is working perfectly. but when runs from websitedomain which is set with IIS version 10 , error 500 page is coming. I have set system.webServer/security/requestFiltering -> maxAllowedContentLength to 4294967295 -> maxQueryString 2048 and maxUrl 4096. I have also set to system.web/httpRuntime -> maxRequestLength to 2147483647 . I am expecting to upload larger files. any help ? Thank you in Advance PB -
Django - FileField - PDF vs octet-stream - AWS S3
I have a model with a file field like so: class Document(models.Model): file = models.FileField(...) Elsewhere in my application, I am trying to download a pdf file from an external url and upload it to the file field: import requests from django.core.files.base import ContentFile ... # get the external file: response = requests.get('<external-url>') # convert to ContentFile: file = ContentFile(response.content, name='document.pdf') # update document: document.file.save('document.pdf', content=file, save=True) However, I have noticed the following behavior: files uploaded via the django-admin portal have the content_type "application/json" files uploaded via the script abobe have the content_type "application/octet-stream" How can I ensure that files uploaded via the script have the "application/json" content_type? Is it possible to set the content_type on the the ContentFile object? This is important for the frontend. Other notes: I am using AWS S3 as my file storage system. Uploading a file from my local file storage via the scirpt (i.e. using with open(...) as file: still uploads a file as "applicaton/octet-stream" -
Recommended Books & Videos for Vue, Javascript, NUXT, Django
After reading several Django books I found these two books to be the best so far. Two Scoops of Django 3.x A Wedge of Django The best practices for production class websites and class based views with cookiecutter really helps a lot! I'm looking for more Django 3.2/4.0+ books and videos or suscriptions but also for JavaScript, Vue & Nuxt since I may need to use Django with DRF as backend and Nuxt 3 for front end. Any recommendations? -
Parts of Development Setting does not overide production settings
So I have being trying to separate my dev from production side and of my setting. However parts work and part do not. #dev.py from lms.settings.prod import * from decouple import config #overide settings DEBUG = True STRIPE_PUBLIC_KEY =config('DEV_PUBLIC_KEY') STRIPE_SECRET_KEY =config("DEV_SECRET_KEY") STRIPE_WEBHOOK_SECRET =config('DEV_WEBHOOK_SECRET') #prod.py from decouple import config from pathlib import Path import os DEBUG = False STRIPE_PUBLIC_KEY =config('STRIPE_PUBLIC_KEY') STRIPE_SECRET_KEY =config("STRIPE_SECRET_KEY") STRIPE_WEBHOOK_SECRET =config('STRIPE_WEBHOOK_SECRET') My folder structure is lms -settings --__init__.py --dev.py --prod.py -
how to send multiple files to backend via GraphQL in Django
I have this code: test_image = SimpleUploadedFile(name='test.jpg', content=b'test') response = self.file_query( ''' mutation createBook($input: BookMutationInput!) { createBook(input: $input) { success, book {id} } } ''', input_data={ "name": "Test Book", "description": "Test Description", "pages": [ {"name": "Page 1"}, {"name": "Page 2"} ] }, op_name='createBook', files={'image': test_image}, ) test_image belongs to Book instance. But each page should also contain an image. How can I pass these images for each page in this payload to backend? -
Jquery Validation remote method always shows invalid
I am trying to validate an html function with django and jQuery validation. I want jQuery validation to check if the inserted email already exists, This is my jQuery valdiation remote email: { validators: { notEmpty: { message: 'email field can not be empty' }, emailAddress: { message: 'is not a valid email' }, remote: { message: 'email is already in use', url: '/validate_email/', type: 'post', data: { email: function() { return $('#email').val(); } }, }, }, }, The url calls to my view def which is def validate_email(request): email = request.GET.get('email', None) data = not Vendors.objects.filter(email__iexact=email).exists() if data is True: data = "true" else: data = "false" return JsonResponse(data, safe=False) I am getting a correct "true" or "false" JsonResponse, but the message always shows that the email is already in use and keep asking me to correct it. I tried passing the JsonResponse as true or false without "", also tried passing the JsonResponse as is_taken: true or is_taken: false. -
How to Count quantity of my QuerySet. Django
Well, i have the following function: employees_birthday = Employees.objects.filter(EmployeeDataNasc__gte=first_day, EmployeeDataNasc__lte=last_day) It serves to return employees born between the dates. She returns: <QuerySet [<Employees: Alberto Santos>, <Employees: Josney Arman>]> But, I would just like to display the number of employees in the QuerySet, i.e. make a Count function. Can someone help me with the syntax? -
CSRF Cookie not Set using Axios
I get this error since a week ago. I've been reading a lot of answers here in other sites but nothing yet. I've been change the setting many times and I don't know where is my error. I have an API Django RF and the frontend using React. To make the call I'm using Axios. When I do a POST request I get the Forbidden (CSRF cookie not set.): /api/cart/add-item/ This is my settings.py enter image description here This is my View enter image description here And this is my Axios enter image description here -
Django - Catch moment when Celery has finished running a task
I'm running some Celery tasks and I'm trying to get a clear view when a Celery task has been completed, whether it succeeded or failed. I have created a Backlog model: class Backlog(models.Model): """ Class designed to create backlogs. """ name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) #Status time = models.DateTimeField(blank=True, null=True) has_succeeded = models.BooleanField(default=False) I have created a Test task in tasks.py to see if I could get a result: @shared_task(name='Test task', bind=True) def test_task(self): task_id = self.request.id result = test_task.AsyncResult(task_id) print('Task started with id:', task_id) add(2, 2) print(result.state) if result.state == 'SUCCESS': print('Task completed successfully') response = { 'state': result.state, 'status': str(result.info), 'date': result.date_done, } Backlog.objects.create(name=f'Success in task {task_id}', description=str(result.info), time=result.date_done, has_succeeded=True) elif result.state == 'FAILURE': print('Task is still running or failed with status:', result.state) response = { 'state': result.state, 'status': str(result.info), 'date': result.date_done, } Backlog.objects.create(name=f'Error in task {task_id}', description=str(result.info), time=result.date_done, has_succeeded=False) And I just test with a simple function: def add(x, y): return x + y I get the following traceback in the worker: [2023-02-01 18:47:02,580: WARNING/ForkPoolWorker-6] Task is still running or failed with status: [2023-02-01 18:47:02,582: WARNING/ForkPoolWorker-6] [2023-02-01 18:47:02,582: WARNING/ForkPoolWorker-6] STARTED [2023-02-01 18:47:02,585: INFO/ForkPoolWorker-6] Task Test task[06f71596-3082-4012-8ea8-05a22d57ca89] succeeded in 0.0534969580003235s: None I can't manage … -
How to ordering category items a to z in django admin panel?
I have a business directory and when i add new company, categories listing mixed style. How can i order categories a to z. I added my model these meta ordering but didn't worked. class Category(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ['name'] -
django and nextjs shared authentication
I am building a new front end with nextJs for my Django App. I have been splitting the development to keep all the dashboard running on Django, while the rest runs on nextJs. nextJs is running on domain.com the existing django will be running on dashboard.domain.com I have setup all the Rest authentication for NextJs and is working fine. Now what I'm trying to achieve is when you login from domain.com you don't need to authenticate to the dashboard and reuse the same authentication. Django seems to have some cookie authentication and I'm using JTW for NextJS. What would be my options to solve this dilemma? -
Django: How to write a function based view used for URL with parameter
I am learning Django, using function based views, and I am struggling with the following: I have this path in urls.py path('user/<str:username>',views.UserProjectList,name='user-projects') that is supposed to show all the projects of the particular user (client). In order to reach it, username should be parameter of the function based view, however I am struggling how to write such view... I have this: def UserProjectList(request,username): user = User.objects.get(username=username) #THIS IS WRONG and should return id of the user #user = User.objects.filter(username=username) #also wrong tag_list = ProjectTagsSQL.objects.all() #ProjectTagsSQL and ProjectSQL are connected project_list = ProjectSQL.objects.filter(client=user) #ProjectSQL table has column client_id (pk is id in User) and table contains all the projects context = { 'tagy' : tag_list, 'projecty' : project_list } return render(request, 'home_page/user_projects.html', context) #SHOULD THE PARAMETER BE INCLUDED HERE? I tried to inspire with the code from class based view I found on the internets (thats is working for me but i didnt manage to connect it with ProjectTagsSQL as i managed in FBV, but that's a different problem) but i didnt manage class UserProjectListView(ListView): model = ProjectSQL template_name = 'home_page/user_projects.html' context_object_name = 'data' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return ProjectSQL.objects.filter(client=user) # original qs qs = super().get_queryset() # filter by … -
Estou com erro de CORS no client-side, porém no serve-side, em Node, consigo realizar a requisição [closed]
Estou com problema de CORS quando tento fazer uma requisição do lado do cliente, no arquivo javascript ligado ao html. imagem do axios lado cliente imagem do erro de cors Por outro lado, no lado do servidor, no node, funciona normalmente, a mesma requisição! imagem do axios lado servidor imagem dos dados recuperados Preciso de ajuda urgente! OBS: estou pegando dados de uma API Rest em django! tentei usar o AJAX e o Fetch, deram o mesmo problema de cors. -
Django selecting a record if its Many-to-Many relation contains data
I have these 2 tables class Job(models.Model): name = models.CharField() collaborators = models.ManyToManyField(User, through="Collaborator") created_by = models.ForeignKey(User) class Collaborator(models.Model): job = models.ForeignKey(Job) user = models.ForeignKey(User, related_name="jobs") role = models.CharField() For a user, I want to select all those Jobs where either created_by=user or the user is in collaborators. The following query does not produce correct results Job.objects.filter(Q(created_by=user) | Q(collaborators=user)) Upon looking at the raw query generated by above code I have found out that this is because the query produced by django ORM creates a LEFT OUTER JOIN between Job and Collaborator, so if there are multiple Collaborators for the same Job then it returns multiple rows of the same job. What I have come up with is the following query Job.objects.filter(Q(created_by=user) | Q(pk__in=user.jobs.all().values("job_id"))) My question is, is there a better query than the above that I can use? P.S. I am using django 4.0 -
How to Merge Two Model Serialisers in Django Rest Framework
I want to merge the results of two models. I have two models as below. First is Product and the other is ProductChannelListing class Product(models.Model): name = models.CharField() category = models.ForeignKey() # has many other fields which I want in the response class ProductChannelListing(models.Model): product = models.ForeignKey() channel = models.ForeignKey() is_visible = models.BooleanField() price = models.IntegerField() I want the result in the following way. { "name": "ABC", "category": {}, "is_visible": true, "price": 200, ** } I want make the query efficient query such that it should not make so many queries. -
How to refer to a related object after deleting an object?
As in the title: How to refer to the related object after deleting the object? Simple example: ModelA(models.Model): ... ModelB(models.Model): model_a = models.ForeignKey("ModelA", on_delete=models.CASCADE) class TestView(APIView): def delete(self, request, pk): object_b = get_object_or_404(ModelB, pk=pk) object_a = object_b.model_a object_b.delete() It is now impossible to use object_a, this error pops up: 'NoneType' object has no attribute 'id' This approach does not work either: class TestView(APIView): def delete(self, request, pk): object_b = get_object_or_404(ModelB, pk=pk) object_a = ModelA.objects.get(id=object_b.object_a.id) object_b.delete() Related queryset can be used later with list(queryset), what about one object? -
How do I send a list of items from my UI to my Django Rest Framework API?
my project uses multithreading to work on several tasks simultaneously. I'd like my UI (I'm using Vue.js) to send a list/array of items to my API to work on each individual item task. ex. [{ "1": "item1", "2": "item2", "3": "item3", ...}] (API searches the items to find what commands to use, that's why I used multithreading so I can work on several tasks at once instead of sending each individual item which takes too long) How do I send a list or array of objects to the API? -
dj-rest-auth overriding reset password default email template not working
I wanna override the default email that gets sent to the user when he forgets his password here is the implementation: #urls.py path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path("password-reset/confirm/<uidb64>/<token>/",TemplateView.as_view( template_name="main/password_reset_confirm.html"),name='password_reset_confirm'), #serializers.py class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'html_email_template_name': 'custom_email_template.html', } def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(self.reset_form.errors) elif not User.objects.filter(email=value).exists(): raise serializers.ValidationError("A user with this email already exists!") return value # settings.py REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'main.serializers.UserSerializer', 'PASSWORD_RESET_SERIALIZER': 'main.serializers.CustomPasswordResetSerializer' } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I tried the solutions from many stackoverflow questions and github issues none of them was working Other than overriding the get_email_options method i tried overriding the save method like so: def save(self): request = self.context.get('request') opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'html_email_template_name': 'custom_email_template.html', 'request': request, } self.reset_form.save(**opts) and it did not work , i tried putting it under -templates -registration password_reset_email.html and it still did not work, while tried the above solutions i have it under templates custom_email_template.html -
Django - How to update a parent model using a child model?
I am sorry that I am not good at English. I have a two models something like this: Models.py class Parent(models.Model): id = models.BigAutoField(primary_key=True) quantity = models.DecimalField(max_digits=3, decimal_places=0, null=True) class Child(models.Model): parent = models.ForeignKey('Parent', related_name="parent_child", on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=3, decimal_places=0, null=True) If the parent quantity is different from the sum of the child quantities, Updates the parent quantity to the sum of the child quantities. I tried to get an object whose parent quantity is different from the sum of the child quantities: parent = Parents.objects.annotate(sum_quantities=Sum('parent_child__quantity')).exclude(quantity=F('sum_quantities')) It works! But I'm having trouble updating this. Is there a good way? Thanks a lot for your help!