Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError at /admin/ [Errno 2] No such file or directory: '//m2n_project/messages.json'
I am facing an issue, like with my local server, it is able to login with admin credentials. But on a live server, it is showing the error "FileNotFoundError". I don't know what is wrong with the code. This is the view of admin login- if user is not None: if user.is_superuser or user.is_staff: user.login(request,user) request.session['user_id'] = id messages.success(request, "Welcome " + str(request.user.username) + "! to the administration.") return redirect('homepage') else: # print("status else") messages.error(request, json.loads(open(os.path.join(os.getcwd() + '/m2n_project/messages.json')).read())[ … "login_denied"]) return render(request, 'admin_app/admin_login.html') else: messages.error(request, json.loads(open(os.path.join(os.getcwd() + '/m2n_project/messages.json')).read())[ -
Intermediate model form django
I'm having trouble creating a form. My models: class Subject(models.Model): name = models.CharField(max_length=30) duration = models.IntegerField() price = models.IntegerField() class Student(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) subject = models.ManyToManyField(Subject,through="StudentSubject") class StudentSubject(models.Model) student = models.ForeignKey(Student,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) discount = models.IntegerField() I'm using the intermediate model StudentSubject to add the discount of each subject however I can't think of how to create the form and how to render it in a template. The form I want to create, is having each subject listed(and a checkbox to select them) and a discount field next to each subject as follows: [] Math DiscountField1 [X] Physics DiscountField2 [X] CompSci DiscountField3 -
Adding custom HTML elements around UserCreationForm's default elements
I am using widget_tweaks to add custom classes to input forms. But how do I add entire HTML elements like this to beautify the username ? <label for="basic-url" class="form-label">Your vanity URL</label> <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon3">https://example.com/users/</span> <input type="text" class="form-control" id="basic-url" /> </div> I am using a basic signup form but want to include custom HTML around it. {% load widget_tweaks %} {% for field in form %} <div class="form-group mt-3 {% if field.errors %}alert alert-danger{% endif %}"> {{ field.errors }} {{ field.label_tag }} {% render_field field class="form-control" %} {% if field.help_text %}<small class="text-muted">{{ field.help_text|safe }}</small>{% endif %} </div> {% endfor %} -
Relay-style pagination with Django
I'm working on a Django 3.x app and I need to expose a REST API that will then be consumed by a GraphQL server in order to provide a GraphQL endpoint to a client. The cursor based pagination provided by Django out of the box only provides a next and previous cursors for each request, but Relay requires one opaque cursor for each returned edge/item. How can I ask Django to generate a cursor for each item? -
Prevent django empty lines in docker console
Hi I'm new to Docker and Django and I wanted to clean up the logging output in the console but I found empty lines with timestamps that are not related to basicConfig of logging(python language) in my app. I don't know if they are generated automatically by Django or docker container. [logging in output console][1] I want to remove these empty lines which only contain a timestamp and no info after [-] [1]: https://i.stack.imgur.com/evlKs.png -
Django get rid of duplicated queries in nested models
I have models as shown below, class Manufacturer(models.Model): name = models.CharField(max_length=100) class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) name = models.CharField(max_length=300) @property def latest_variant(self): return self.carvariant_set.last() class CarVariant(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) name = models.CharField(max_length=300) and I am making a query to get the latest variant of all cars, I am getting much duplicated queries. I couldn't eliminate it work with prefetch_related Car.objects.all().prefetch_related('carvariant_set') How can I eliminate the duplicated queries? -
How can I use process_request in Django for checking if the request contains the header I require?
I am have a Django app with a decent amount of views. What I wish to do is that whenever a request is sent to the app, it gets checked for headers, and if the header SECRET has the value $ecret$tring, only then the request is matched with my urlpatterns and sent to the view. Else, it should return the following- {'MESSAGE': 'UNAUTHORIZED'} with a 401 status. Here is the middleware class that I have written- from django.http import JsonResponse from django.utils.deprecation import MiddlewareMixin class AuthCheck(MiddlewareMixin): def process_request(self, request): if 'SECRET' in request.headers: if request.headers['SECRET'] != '$ecret$tring': return JsonResponse({'MESSAGE': 'UNAUTHORIZED'}, status=401) else: return JsonResponse({'MESSAGE': 'UNAUTHORIZED'}, status=401) However, when I send a request without the header, it still gets sent to the view. What's going wrong? -
django- host a website without python app on cpanel?
I am going to host a website build on the Django framework. There are tutorials on youtube on how to host but they all are using the python app already on Cpanel. But my hosting provider Hostgator does not give the python app in Cpanel. is there any other way to host the Django website without the python app on Cpanel? -
Difference between content_type=application/json and format=json in DRF APIClient
I'm using rest_framework.test.APIClient for unit tests in my project. I used a dictionary as a request data, so None values there are not parsed properly as it doesn't understand the format. I added format="json" as a parameter to client.post() and it worked fine. However adding content_type="application/json" solved the problem as well and I want to know what's the difference. -
How do I implement JavaScript and Django?
I've been learning Django as a backend framework, and now I am starting to have to deal with API and JavaScript. I've been trying to understand how a normal application would be built, but this just confuses me so much. Is Django just used to build the database and API at the end of the day so that you can communicate with it from the front-end? Anything that would clarify this workflow would be appreciated. As of now, it seems like what I learned about injecting data in templates with Django etc, is supposed to be replaced with JavaScript -
Run celery task everyday at 3:00 am in every timezone? Django
I need to run a task a 3:00 am everyday for multiple timezones, in the app every organization has a timezone. class Organization(models.Model): timezone = models.IntegerField(choices=((i, i) for i in range(-12, 13))) So if two organizations has different timezones the task should be executed a 3:00 am in their respective timezones i.e. not at the same time. How can I accomplish that? -
how to add new entered input value to table django ajax
i'm trying to add a new entered value to a table after success method runs using ajax , i've used ModelForm . i want to add the new entry to the table body row ! , i've tried alot , but still i cant figure it out ! i most appreciate your helps class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) my views.py @login_required def create_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') form = MainGroupForm() if request.is_ajax() and request.method == 'POST': form = MainGroupForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() return JsonResponse({'success':'success'}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) context = { 'form':form,'lists':lists } return render(request,'products/create_maingroup.html',context) const form = document.getElementById('main_form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'products:create-maingroup' %}', data : $('#main_form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { console.log(data.success=='success') if (data.success=='success') { form.reset(); obj = $('#main_form').serialize(); //i have to append new entred values here //but i dont know how to get inputs and set the admin //name who created the post ! alertify.success("added") } else if(data.error_code=='invalid'){ for(var key in data.error_msg){ if(key == 'main_type'){ document.getElementById('main_error').removeAttribute('hidden') document.getElementById('main_error').innerHTML = data.error_msg[key][0] } } } } my html page <div class="col-md-12"> <div class="card card-info"> <div class="card-header"> <div class="card-tools"> <button … -
Django Spam URL blocker form entering into my application
I have a Django application that is working fine. Now after some time, I come across some spam URLs that are getting processed by my application. Is there any way I can block these particular URLs from entering into my application. I don't what these URLs to even reach my urls.py? Thanks in advance -
Django test api code : Got an error creating the test database: database "test_postgres" already exists
I made test code for my APIs(Django web framework). It ran with no errors about 3 hours ago(It is not first time running test codes(more than 1k times)) How should I debug?? Im using macOS. directory is my_project/order_api/tests/test_order1.py I ran the code by clicking arrow in test_order1.py file. This is DATABASE setting DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql"), "NAME": os.environ.get("SQL_DATABASE", "postgres"), "USER": os.environ["SQL_USER"], "PASSWORD": os.environ["SQL_PASSWORD"], "HOST": os.environ["SQL_HOST"], "PORT": os.environ["SQL_PORT"], }, } This is Error Message Creating test database for alias 'default'... Got an error creating the test database: database "test_postgres" already exists Type 'yes' if you would like to try deleting the test database 'test_postgres', or 'no' to cancel: yes Destroying old test database for alias 'default'... Got an error recreating the test database: database "test_postgres" is being accessed by other users DETAIL: There is 1 other session using the database. -
How do i save the info typed and display in another page in html, django
How do i save the info typed in a form and display in the following page which tells me what are the details I type and ssaved in the library -
TemplateDoesNotExsist in Django 3.2.5
I am a 13 year old programmer, new to Django trying to add 2 numbers. But as soon as I give the input it spits out an error. The following are all the details to my project. -
Increase Django logs query time precision
I am currently using the Django shell in debugging mode in order to benchmark my queries. This is an example of what I get: >>> Item.objects.filter(param1=63) (0.001) SELECT `items`.`id`, `items`.`param1`, `items`.`param2`, FROM `items` WHERE `items`.`param1` = 63; args=(63,) Most of the results I am getting lay in the order of a millisecond, so I was wondering: is it possible to increase the query precision say, one or two orders of magnitude in order to tell them apart? I am using MariaDB as a database. mariadb --version mariadb Ver 15.1 Distrib 10.4.11-MariaDB, for Linux (x86_64) using readline 5.1 Thank you in advance. Regards. -
Path does not exist or is inaccessible error when using opencensus-python
I'm getting the following errors when I try to integrate opencensus-python in my dockerized Django project. ERROR: Path /tmp/opencensus-python-<hash-code>/2021-07-26T070705.948749-147e2037.blob@2021-07-26T070828.122386.lock does not exist or is inaccessible. ERROR: Path /tmp/opencensus-python-<hash-code>/2021-07-26T085046.693213-b80f5ca1.blob.tmp does not exist or is inaccessible. I did a bit of searching and found that this error is returned in _check_storage_size but what does it mean and how do I fix it? -
AttributeError: 'CustomUser' object has no attribute 'items' - Unit Test Phase
I am working on a book project. For this project, I have been already created a custom user model and using it. However, today I tried to test this model. When I want to run this code, it returns "AttributeError: 'CustomUser' object has no attribute 'items'" response. I don't understand where am I doing wrong. If I send the data in dictionary type, the test works, but if I want to send in instance type, it returns the error. 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( choices=USER_TYPE_CHOICES, default=1, verbose_name=AccountStrings.CustomUserStrings.user_type_verbose_name) class Meta: verbose_name = AccountStrings.CustomUserStrings.meta_verbose_name verbose_name_plural = AccountStrings.CustomUserStrings.meta_verbose_name_plural def __str__(self): return f"{self.first_name} {self.last_name}" Unit Test from rest_framework.test import APITestCase from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() class CustomUserRegistrationTests(APITestCase): url = reverse("account:register") def setUp(self) -> None: self.user1 = User.objects.create_user(first_name="John", last_name="Doe", email="johndoe@example.com", username="demo", password="Pas12wor21d", identity_number = "12345678910", user_type = "2", gender = 1) def test_user_instance(self): """ Check the … -
Braintree Client token generate method throws an XML error inside Django
I am using the below code to generate Client Token from the braintree gateway inside my payment View in Django. def generate_token(request,id,token): if not validate_user_session(id,token): return JsonResponse({"error":"Invalid session"}) gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id="xxxxxxxxxx", public_key="xxxxxxxxxxxx", private_key="xxxxxxxxxxxxxxxxxxxxxx" ) print(gateway.client_token.generate()) return JsonResponse({"clientToken":gateway.client_token.generate(), "success":True}) This throws an error xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 0 However, the code works fine outside Django and in Python Shell and generates the token successfully. I don't seem to understand what is the issue ? The Ids and tokens are same in both the cases. Any help is appreciated. -
FileNotFoundError: [Errno 2] No such file or directory | FileNotFoundError: [WinError 2] The system cannot find the file specified:
I am trying to Upload Files using Django templates, But on save_project I get this traceback error FileNotFoundError: [WinError 2] The system cannot find the file specified: 'E:\\forefront-v1.0\\media\\uploads\\temp\\10\\Video%20Sensor%20-%2013370_1798858.mp4' -> 'E:\\forefront-v1.0\\media/uploads/project-videos/Video%20Sensor%20-%2013370_1798858.mp4' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\forefront-v1.0\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\forefront-v1.0\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\forefront-v1.0\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\contrib\auth\mixins.py", line 109, in dispatch return super().dispatch(request, *args, **kwargs) File "E:\forefront-v1.0\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "E:\forefront-v1.0\projects\views.py", line 2660, in post project_id = self.save_project( File "E:\forefront-v1.0\projects\views.py", line 2792, in save_project video1 = self.upload_video_locally(video1) if video1 else None File "E:\forefront-v1.0\projects\views.py", line 2872, in upload_video_locally shutil.move(temp_file_path, saved_file_path) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 826, in move copy_function(src, real_dst) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 435, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 264, in copyfile with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: FileNotFoundError: [Errno 2] No such file or directory: 'E:\\forefront-v1.0\\media\\uploads\\temp\\10\\Video%20Sensor%20-%2013370_1798858.mp4' [26/Jul/2021 13:12:27] "POST /upload/ HTTP/1.1" 500 23208 In project settings.py # Upload MEDIA_URL = '/media/' … -
how to get update url in django - ajax
i'm trying to update and delete post with ajax , class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) views.py def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for obj in lists: item = { 'id':obj.id, 'admin':obj.admin.username, 'main_type':obj.main_type, 'date':obj.date } data.append(item) return JsonResponse({'data':data}) @login_required def create_maingroup(request): form = MainGroupForm() if request.is_ajax() and request.method == 'POST': form = MainGroupForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() return JsonResponse({'success':'success'}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) context = { 'form':form } return render(request,'products/create_maingroup.html',context) my update views.py @login_required def update_maingroup(request,id): object = get_object_or_404(MainGroup,id=id) form = MainGroupForm(instance=object) if request.method == 'POST': form = MainGroupForm(request.POST,instance=object) if form.is_valid(): form.save(commit=True) return JsonResponse({'success':'success'}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) context = { 'form':form } return render(request,'products/update_maingroup.html',context) my urls.py app_name = 'products' urlpatterns = [ path('',create_maingroup,name='maingroup'), path('maingroup/update/<int:id>/',update_maingroup,name='update_maingroup'), path('maingroup/delete/<int:id>/',delete_maingroup,name='delete_maingroup'), const form = document.getElementById('main_form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'products:maingroup' %}', data : $('#main_form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { if (data.success) { form.reset(); alertify.success("added") } else if(data.error_code=='invalid'){ for(var key in data.error_msg){ if(key == 'main_type'){ document.getElementById('main_error').removeAttribute('hidden') document.getElementById('main_error').innerHTML = data.error_msg[key][0] } } } } $.ajax({ type:'GET', url:'{% url 'products:list-maingroup' %}', success:function(response){ console.log(response) data = response.data var k = '<tbody>' for(i = 0;i < data.length; i++){ k+= … -
Djngo - How can I change profile view in admin's panel?
Well, I created a model Profile: class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, ) website = models.URLField(blank=True) bio = models.CharField(max_length=240, blank=True) And added it to admin.py: @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): model = Profile So, I have user's panel on mu admin's panel. But every profile in the list of profiles are called 'profile object(1)', 'profile object(2)' and etc, but when I tap on the link, I can see the user's name. So, how can I can change the view of profiles in the list of profiles so they are called there as user is called? How it looks like in admin's panel How it looks like inside the profile -
Django user registration without username
I am making django registration form At first this code works well class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username","email", "password1", "password2"] def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") However now I want to make email as username, so my idea is like this class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["email", "password1", "password2"] #delete username from home. def register(response): if response.method == "POST": if not response.POST._mutable: response.POST._mutable = True response.POST['username'] = random.randrange(1000000) # force change username form = RegisterForm(response.POST) if form.is_valid(): form.save() However after this username is not registered. What is wrong?? -
User customizable Template
So I have a template to render a PDF and I want to be able to customize this PDF. But in this text some dynamic information is added so I want to do the following thing: In a model.TextField I want to set a string like string = 'Text {{ count }} Text text' and than I want to render this string in my template like so: <p> {{ string }} </p> How can I get this so that the template engine renders it like this: <p> Text {{ count }} Text text </p>