Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to do an if to check if a date is between two dates. Python
I need to check if a certain date is between the month of February, but I can't use year, only month and day. How can i do this using if and else in python? -
#Django How to fetch data with permissions.IsAuthenticatied in views.py using Postman?
I'm trying to fetch data with my Django Restframework API endpoints. This is my UserViewSet in views.py: class UserViewSet(viewsets.ModelViewSet): queryset = PortalsUser.objects().all().order_by('name') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] So this will need the user to login first to view the user information. I tried to GET my user on Postman, and this is the my Postman configuration I'd like to know am I doing it correctly? Should I input my username and password like this? Thanks for your help! -
Getting localhost for next page url in production
hlo, I have deployed a Django rest app in production. When I call a list API there is a pagination, and I am getting localhost for next page URL. I am using GenericViewSet and LimitOffsetPagination for pagination. My app is running in docker container.And it is pointed to a specific domain. We can access it using domain name "https://abc.xyz.com". But I have used python manage.py runserver:0.0.0.0:8000(it's just for testing) CMD for running the server. -
How to save down Django user's updated social media post?
Goal A user can edit the post that that specific user made. Bly clicking edit than editing than pressing save. Problem When I edit the social media post it does not get saved Description I can make a mew post like in social media Post it in to a list where all the other users post (shortened 200 character visible only) Than I can click on a "Details button" that jumps me to another page where I can see the full length of the post There is a button here called "edit" it should only appear to the post creator If you click edit than a window pop up where you already have your existing post copied in to an inout field here you can edit your post the goal would be it you click save it should save it down but that does not happens Interestingly if i close down the pop up windows with the small window [X] button or the "cancel" button and I go back it memorizes my edit there View function @login_required def social_post_detail(request, pk): social_post = get_object_or_404(social_post, pk=pk) form = None if request.user == social_post.created_by: if request.method == 'POST': print(request.POST) form = social_postForm(request.POST, instance=social_post) … -
NOT NULL constraint failed: tasks_task.user_id
I'm working on a Django project using Python3. I have this error come ups when I'm trying to create a new task. django.db.utils.IntegrityError: NOT NULL constraint failed: tasks_task.user_id The web application works fine, but when I try to create a new task is when the error occurs, I have read all the posts related to the problem, but I have not found the solution. I tried to update my sqlite3, but it didn't work. This is my code from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from .forms import TaskForm def home(request): return render(request, 'home.html') # Create your views here. def signup(request): if request.method == 'GET': return render(request, 'signup.html', { 'form': UserCreationForm }) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user( username=request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect('tasks') except IntegrityError: return render(request, 'signup.html', { 'form': UserCreationForm, 'error': 'Username already taken' }) return render(request, 'signup.html', { 'form': UserCreationForm, 'error': 'Passwords did not match' }) def tasks(request): return render(request, 'tasks.html') def create_task(request): if request.method == 'GET': return render(request, 'create_task.html', { 'form': TaskForm, }) else: try: form = TaskForm(request.POST) new_task = form.save(commit=False) new_task.User = request.user new_task.save() … -
Invalid host header in django
Environment: Request Method: GET Request URL: http://abampdb.......nust.edu.pk:83/ Django Version: 4.0.2 Python Version: 3.9.12 Installed Applications: ['abampdb.apps.AmpdbConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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'] Traceback (most recent call last): File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/utils/deprecation.py", line 125, in __call__ response = self.process_request(request) File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/http/request.py", line 135, in get_host raise DisallowedHost(msg) Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: 'abampdb.......t.edu.pk:83'. You may need to add 'abampdb...........du.pk' to ALLOWED_HOSTS. I have used nginx and gunicorn for the deployement from this link https://djangocentral.com/deploy-django-with-nginx-gunicorn-postgresql-and-lets-encrypt-ssl-on-ubuntu/. I have edited the settings.py Settings.py also with the domain name in the Allowed Host but still getting the same error and after editing i have also run the gunicorn restart command and nginx reload command. here is my Nginx configuration file -
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.