Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I cannot access the entity I created in DRF tests
I create a Project in a test (the first method). I'm trying to get it (the second method), but i get 404 error. def test_create_valid(self): response = self.client.post( '/api/projects/', self.valid_payload, format='json' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_retrieve_project(self): response = self.client.get( '/api/projects/1/' ) self.assertEqual(response.status_code, status.HTTP_200_OK) Even when I try to get this with Django ORM I get None. p = Project.objects.first() # returns None -
Django Exporting selected ListView Items To csv file
I have a list View which I want to select certain rows of the records returned and write them out to a csv file (which can later be imported to Excel). The problem is when I call the function to do the export via the button on the list View, I cant seem to get which items (choices) were selected. I am attemting to get them via the request object. Here is a look at the model, views, and templates I am trying to use. See below: class Cd(models.Model): artist_name = models.CharField(max_length=155) cd_title = models.CharField(max_length=155) cd_total_time = models.TimeField(default="00:00:00") cd_total_time_delta = models.DurationField(default=timedelta) cd_run_time = models.TimeField(default="00:00:00",blank=True) cd_run_time_delta = models.DurationField(default=timedelta) cd_remaining_time = models.TimeField(default="00:00:00",blank=True) cd_remaining_time_delta = models.DurationField(default=timedelta) views.py class List_Cds(ListView): model = Cd template_name = 'list_cds.html' def export_to_csv(request): choices = request.GET.getlist('choices') print("In export_to_csv choices selected were: %s" % choices) cd_export = Cd.objects.filter(id__in=choices) response = HttpResponse('text/csv') response['Content-Disposition']= 'attachment; filename=cdlist.csv' writer = csv.writer(response) writer.writerow(['Artist', 'Cd Title', 'CD Run Time']) cd_fields = cd_export.values_list('artist_name','cd_title', 'cd_total_time') for cd in cd_fields: writer.writerow(cd_fields) return response list_cds.html . . . {% block content %} <br> <button type="submit" value="listbatchview" onclick="location.href='{% url 'export_to_csv' %}'">Batch Export CSV</button> <TABLE id="list_table"> <TR BGCOLOR="#B0B0FF"> <TD></TD> <TD></TD> <TD ALIGN="Center">Artist Name</TD> <TD ALIGN="Center">Cd Name</TD> <TD BGCOLOR="99CCFF" ALIGN="Center">Cd Length</TD> <TD BGCOLOR="#CC99CC" … -
I cannot forward the video
I have created a web application using Django and stored videos in the static file. I loaded the static files onto the HTML page and used video.js as the video player. I am playing a video in Chrome and Edge, but it does not allow me to fast-forward. When I try to fast forward, the video restarts from the beginning. However, when playing the video in Firefox and Safari, I can fast forward without any issues. I would like to know why I cannot fast forward in Chrome or Edge and how to fix this issue. -
Debugpy won't attach to anything
I've tried everything except what works. Nothing gets my vscode debugger to attach to any breakpoint. Here is my launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Docker", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ], "connect": { "host": "localhost", "port": 3000 }, "justMyCode": true, "logToFile": true } } And here is my docker-compose.yml: services: web: platform: linux/amd64 build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8800:8000 - 3000:3000 And in my manage.py: if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 3000)) # debugpy.wait_for_client() print('debugpy Attached!') My debugpy Attached! is being printed so I know things are set up to be attached to the debugger, but none of my breakpoints work. -
ValueError: Cannot assign "value" "Order.dish_name" must be a "Dish" instance
I am writing a restaurant app in Django and I have a specific view that catches an Ajax request. From this request I get the name of a dish, which I try to save in a new object Order. I keep getting this error " ValueError: Cannot assign "'pasta'": "Order.dish_name" must be a "Dish" instance." and I have no idea why. I have been trying to fix it for 2 days, so i would like to know what I am doing wrong type here models.py` from django.db import models class Table( models.Model ) : number = models.IntegerField( primary_key= True) def __str__( self ) : return str(self.number) class Dish(models.Model ) : name = models.CharField( primary_key= True, max_length= 50 ) price = models.FloatField() type = models.CharField( max_length= 50 ) gluten = models.BooleanField( null= False) lactose = models.BooleanField( null= False) def __str__( self ) : return self.name class Meal(models.Model ) : start = models.TimeField() end = models.TimeField(blank= True, null= True, default= None) table = models.ForeignKey(Table, on_delete=models.CASCADE) def __str__( self ) : return str(self.table.number) class Order(models.Model): request_time = models.TimeField() kitchen_start_time = models.TimeField(blank= True, null= True, default= None) delivery_time = models.TimeField(blank= True, null= True, default= None) dish_name = models.ForeignKey(Dish, null= True, blank= True, default= None, … -
Nginx Reversed Proxy for Django
I have my Django Server running on a virtual maschine. I got my own domain and want to access the server just with the domain via Nginx. I got to files in the sites-enabled folder. The problem is that if I try to connect to the Server I get a 403 forbidden message. But if I change the servername from the Reversed Proxy to my static ip I can access the server. Does anybody know what the mistake is, that I can access the Djangoserver just with my domain? server{ server_name www.mmjtech.de; root /var/www/html; location / { index index.html index.htm index.html inde.php; try_files $uri $uri/ = 404; } listen 80; listen [::]:80; } And the following is the second file. server{ server_name kenergy.mmjtech.de; root /var/www/html; location / { index index.html index.htm index.html inde.php; try_files $uri $uri/ = 404; } listen 80; listen [::]:80; } -
Django file not uploaded using FileField(upload to=) from admin panel
i have a problem that is i can't upload files from admin panel to my folder document in media , i try to upload but it always failed the server still uploading and the end it say error 500 request time out , so after i tried many solution i thing my problem with mysql db or with django my Django version 3.0.3 and python 3.7 and i am using namecheap shared hosting settings.py : # media dir MEDIA_URL= '/media/' MEDIA_ROOT = os.path.join('/home/traixmua/public_html/media') urls.py : urlpatterns = [ ... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'blog_app.views.handler404' models.py : class Trainer(models.Model): ..... document = models.FileField(upload_to='documents/') note : when i try to upload files using SQLite on local server not in hosting it's work good but with mysql i have this problem , i can choose the file but it won't to upload -
How do I make users to upload image files from a Django model which a React JS frontend to Google Cloud Storage
I have created a model using django and my model allows an authenticated user to upload a profile picture to Google Cloud Storage I have installed both google-auth and google-cloud-storages packages. I have also included storages app to INSTALLED APPS in settings.py I have created my cloud bucket and have have connected it with my application just fine now the issue comes when I test with postman, my API is unable to upload PUT pictures to the Google Cloud but if I manually upload a picture into my bucket, I am able to view GET it with my API in Postman. REMEMBER I WANT TO USE THE ENDPOINT IN THE FRONTEND OF MY APPLICATION OF REACTJS here is a breakdown of my configurations Google Cloud configuration os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "MY-JSON-FILE.json" import google.auth from google.cloud import storage # Use application default credentials credentials, project_id = google.auth.default() GS_PROJECT_ID = os.environ.get("GS_PROJECT_ID") GS_BUCKET_NAME = os.environ.get("GS_BUCKET_NAME") GS_DEFAULT_ACL = os.environ.get("GS_DEFAULT_ACL") MEDIA_ROOT = os.environ.get("MEDIA_ROOT") UPLOAD_ROOT = os.environ.get("UPLOAD_ROOT") GS_FILE_OVERWRITE = os.environ.get("GS_FILE_OVERWRITE") #GS_LOCATION = os.environ.get("GS_LOCATION") #Media files settings MEDIA_URL = os.environ.get("MEDIA_URL") DEFAULT_FILE_STORAGE = os.environ.get("DEFAULT_FILE_STORAGE")type here MY MODEL CONFIG class AppUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default-avatar.png', upload_to='media/', null=True, blank=True, storage=GoogleCloudStorage()) The API CLASS IN MY api.py class UpdateAppUserProPic(UpdateModelMixin, GenericAPIView): … -
Is there an efficient way to recursively query a Django model manytomany field?
Given this model: class Role(models.Model): title = models.CharField(max_length=255, verbose_name='Role Title') parents = models.ManyToManyField("self", symmetrical=False) skills = models.ManyToManyField(Skill) What is the most efficient way to get a list of all the 'Skill' objects related to this 'Role' object, and its parents, recursively? For example, if the Role object in question is 'Manager', it will inherit skills from 'Team Leader', which inherits skills from 'Team Member' etc. -
Is there any method or api method in django rest api to search a list by value instead of key
My list look like this in my model it's a choice list STATUS_CHOICES = [(DELIVERED_STATUS= 'delivered') (FEEDBACK_STATUS='feedback')] DELIVERED_STATUS=1 FEEDBACK_STATUS=2 My endpoint api url is /api/v2/task/list?Status=1 how do i search the content of the list using values of the list instead of their keys for example: /api/v2/task/list?Status=1 to /api/v2/task/list?Status=feedback -
Django Unit Test- How to avoid rollback for each unit test case
I am new to Django framework. I am writing Django unit test cases. The DB transactions are getting roll-backed for each test case. Is it possible to avoid the rollback since I want to use that DB data for other test cases? -
django.db.utils.OperationalError: ERROR: no more connections allowed (max_client_conn)
I have a django app running on kubernetes with postgrsql / pgbouncer I encounter the following error on some requests when I run 2 Django replicas (this doesn't seem to happen if I only set 1 replica) I only have one database Django side django.db.utils.OperationalError: ERROR: no more connections allowed (max_client_conn) PGBouncer side 1 WARNING C-0x55d76aeb6330: (nodb)/(nouser)@xx.xx.xx.xx:37002 pooler error: no more connections allowed (max_client_conn) I have the following settings postgres FROM postgres:12.0 args: - postgres - -c - max_connections=400 SHOW max_connections; max_connections ----------------- 400 (1 row) pgbouncer - name: PGBOUNCER_MAX_CLIENT_CONN value: "800" - name: PGBOUNCER_DEFAULT_POOL_SIZE value: "400" - name: POOL_MODE value: transaction - name: SERVER_RESET_QUERY value: DISCARD ALL I suppose this comes for these settings but cannot figure out what to set. Can someone give me what values would work ? Once fixed and with this architecture (Django + PGBouncer + Postgrsql) could I launch 5/10/15... replicas and the database/bouncer will handle it ? Thanks -
Try to Return dataset as a table with request of postman
I wanna Request with postman and get a table of all books as return but I can't find a way to do this. Thanks a lot This is my model of books: class Book(models.Model): name = models.CharField(max_length=100) username = models.ForeignKey(User, on_delete=models.CASCADE) publication_date = models.DateField() publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.name And This is my View: class AddBookAPIView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'book.html' @method_decorator(login_required(login_url='login/')) def post(self, request): book_serializer = BookSerializer(data=request.data) if book_serializer.is_valid(): book_serializer.save() return redirect('home') return Response({'message': book_serializer.errors}) @method_decorator(login_required(login_url='login/')) def get(self, request): book = Book() serializer = BookSerializer(book) return Response({'serializer': serializer, 'book': book}) -
Django logs are working fine in my Windows local Environment but not getting logs in live ubuntu server. I am using Nginx with Gunicorn
import logging logging.basicConfig(filename=os.path.join(BASE_DIR, 'django.log'), level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') ##################### Here is the Middleware ####################### class RequestResponseLoggingMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) logger.info('Request: {0} {1} {2}'.format(request.method, request.path, get_client_ip())) return response def get_client_ip(): try : hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) ip = IPAddr except : ip = '-' return ip Here is what I am getting in my Windows logs 2023-03-09 19:42:33,972 INFO Request: GET /login 192.185.45.22 -
i can't upload files from django admin panel and just still loading
iam using django 3.0.3 and i want to upload files from admin panel but when i try to upload file it still loading and at least it show error 500 request time out , i deploy my website in namecheap so how to fix it settings.py : # media dir MEDIA_URL= '/media/' MEDIA_ROOT = os.path.join('/home/traixmua/public_html/media') urls.py : urlpatterns = [ path('', views.home, name='home'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'blog_app.views.handler404' models.py : class Trainer(models.Model): document = models.FileField(upload_to='documents/') admin.py : from django.contrib import admin from blog_app.models import Trainer # Register your models here. class TrainerAdmin(admin.ModelAdmin): search_fields = ('name', 'name') admin.site.register(Trainer,TrainerAdmin) what is the problem here i can't find any problem note : when i try to upload files using SQLite on local server not in hosting it's work good but with mysql i have this problem , i can choose the file but it won't to upload -
Filter by time in DRF
I have an api with an end day field (ad end time), in the model, this is a simple datetime field: end_date = DateTimeField(null=True, blank=True) in my view there are several types of filtering for ads, but I need some checkbox that will compare the current date and time with the one written in this field, based on which only relevant ads will be displayed Is there something similar in the DRF, like this(DjangoFilterBackend): class AdAPI(generics.ListAPIView): queryset = Ad.objects.all() serializer_class = AdSerializers filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_class = AdFilterSet I will be grateful for the hint -
how to loop Django SESSION data in Django views.py file
dict_items([('1', {'name': 'Talon Lott', 'image': '/media/images/products/1.png', 'reg_price': '958.0', 'dis_price': '844.0', 'qty': 1}), ('2', {'name': 'Lionel Owens', 'image': '/media/images/products/2.png', 'reg_price': '684.0', 'dis_price': '221.0', 'qty': '1'}), ('3', {'name': 'Brenna Chan', 'image': '/media/images/products/3.png', 'reg_price': '728.0', 'dis_price': '177.0', 'qty': 1}), ('4', {'name': 'Amos Osborne', 'image': '/media/images/products/4.png', 'reg_price': '453.0', 'dis_price': '547.0', 'qty': '1'})]) this data i added to Django session i want to calclute single data: (qty and price ) and i want to claclute my (total amount) But In views.py file when i loop this data i only get id:1 data. {'name': 'Talon Lott', 'image': '/media/images/products/1.png', 'reg_price': '958.0', 'dis_price': '844.0', 'qty': 1} So how may i make a loop for my session data. Here is my views.py file def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) total_amounts = 0 saving = 0 if 'cartdata' in self.request.session: for pro_id, item in self.request.session['cartdata'].items(): total_amounts += int(item['qty']) * float(item['dis_price']) saving += float(item['reg_price']) - float(item['dis_price']) print(item) context={ 'total_amounts': total_amounts, 'saving': saving, 'cart_data': self.request.session['cartdata'], 'totalitems': len(self.request.session['cartdata']) } return context -
Why are path variable keys being read as values in my Django application?
I am using Django Rest Framework to build an api. This is my first time working with DRF, but have experience working with Laravel/NestJs so the concept of routing isn't too unfamiliar. In my DRF application, my url config looks something like this: // urls.py urlpatterns = [ path('api/v1/accounts/<str:account_number>/', accounts.AccountsViewSet.as_view()), url('api/v1/', include(router.urls)), ] In Postman, I am sending a GET request to the following url: {{my_host}}/api/v1/accounts/:account_number/ My view looks like this: // view.py def get(self, request, account_number=None, *args, **kwargs): print(account_number) if account_number is not None: print('account_number was provided') else: print('account_number provided') When sending a GET request to my endpoint, I can provide a value for account_number key. Let's say I use ABC123 as the key value. Given the above view, the first print statement returns ABC123. I will also get into the first if block and see the message account_number was provided All is well! However, if I do not provide an account number (I leave the path variable value empty) I am getting the path variable itself in my logging. For example: // view.py def get(self, request, account_number=None, *args, **kwargs): print(account_number) // :account_number if account_number is not None: print('account_number was provided'). <!-- still getting here else: print('account_number provided') As … -
How do I stop Geolocation from submitting twice?
I am building a crime alert website and I want the user's longitude and latitude to be extracted once the user submits a new alert. Instead, it is submitting twice returing both lat and lng with value and the other without value. I wanted it to return this: lucas posted a crime alert! Alert!!! cv !!! Crime reported from Ogbia, Bayelsa Crime coordinates: Longitude 3.325952 | Latitude 6.599475 Category: c March 9, 2023, 1:53 p.m. Instead, it is submitting twice like this: lucas posted a crime alert! Alert!!! cv !!! Crime reported from Ogbia, Bayelsa Crime coordinates: Longitude 3.325952 | Latitude 6.599475 Category: c March 9, 2023, 1:53 p.m. lucas posted a crime alert! Alert!!! cv !!! Crime reported from Ogbia, Bayelsa Crime coordinates: Longitude None | Latitude None Category: c March 9, 2023, 1:53 p.m. My Views: def new_alert(request): if request.method == "POST": content = request.POST.get("content") state = request.POST.get("state") lga = request.POST.get("lga") category = request.POST.get("category") current_user = request.user lat = request.POST.get("lat") lng = request.POST.get("lng") # Create a new alert new_alert = Alert(content=content, state=state, lga=lga, user=current_user, category=category, latitude=lat, longitude=lng) new_alert.save() return HttpResponseRedirect(reverse("all_alerts")) else: return render(request, "new_alert.html") My Javascript: <script> function getLocation() {`your text` if (navigator.geolocation) { // Display confirmation prompt … -
Configure Django in IIS
How can I configure a Django Project on IIS without wfastcgi.py? I don't found any wfastcgi.py in python's 3.10.10 folder. Anyone could help me? Try to follow some internet tutorials without success. -
axios error in uploading files from react to django rest framework
on react console its showing axios error of bad request i have the tested the backend with postman [working postman test] (https://i.stack.imgur.com/GFMae.png) 1>here is the react axios code const [coloumn, setColoumn] = useState(""); const [selectedFile, setSelectedFile] = useState(null); const handleSubmit = async (event) => { event.preventDefault(); console.log(selectedFile) console.log(coloumn) const response = await axios({ method: "post", url: "http://127.0.0.1:8000/file/upload", file:selectedFile, remark:coloumn, headers: { "Content-Type": "multipart/form-data" }, }); console.log(response) }; 2>here is the django rest framework views code parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have tried using the axios api with formdata but its not working as well -
Best approach to resolve recursive calls of deferred fields especially mentioned on __str__ method on django
Recently i came across two scenarios where i got recursive calls issue due to deffered fields. I've resolved one and have some ideas on how to resolve the second one but need your opinions on what would be the best approach. I'll start with scenario 1's problem and solution to better understand my actual issue(scenario 2). Scenario # 1 Below are snippets of specific part of my models: class Transaction(BaseModel): STATUS_CHOICES = ( ('1', 'PENDING'), ('2', 'PROCESSING'), ('3', 'APPROVED'), ('4', 'FAILED'), ('5', 'DISMISSED') ) # some unimportant fields account = models.ForeignKey('account_management.Account', on_delete=models.RESTRICT, related_name='transactions') name = models.CharField(max_length=255) user_goal_config = models.ForeignKey('UserGoalConfig', on_delete=models.RESTRICT, related_name='transactions') status = models.CharField(max_length = 1, choices = STATUS_CHOICES, default='1') payment_status = models.CharField(max_length = 1, choices = STATUS_CHOICES, default='1') amc_status = models.CharField(max_length = 1, choices = STATUS_CHOICES, default='1') # some unimportant fields class Meta: db_table = 'transaction' ordering = ['-created_at'] _status = '1' _payment_status = '1' _amc_status ='1' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # to keep track of old values self._status = self.status self._payment_status = self.payment_status self._amc_status = self.amc_status self._action = self.action def __str__(self) -> str: return f'{self.name} | {self.id} | {self.account}' class UserGoalConfig(BaseModel): name = models.CharField(max_length=150) # some unimportant fields now let's assume that there is one goal(id=1) … -
Error Running Selenium/Django/Firefox. unable to create file '/var/www/.cache/dconf/user': Permission denied. dconf will not work properly
I am running selenium 4.1 with geckodriver 0.32.2 and firefox 110.0.1. The AWS EC2 is on Ubuntu 22.04. I had to install firefox not using snap. Here is the code to get the driver. options = webdriver.FirefoxOptions() options.headless = True if not driver: driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(), options=options) Here is the error in the geckodriver log. 1678369806282 geckodriver INFO Listening on 127.0.0.1:57825 1678369806786 mozrunner::runner INFO Running command: "/bin/firefox" "--marionette" "-headless" "--remote-debugging-port" "50887" "--remote-allow-hosts" "localhost" "-no-remote" "-profile" "/tmp/rust_mozprofileq2trdx" *** You are running in headless mode. [GFX1-]: glxtest: Unable to open a connection to the X server [GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt (firefox:18279): dconf-CRITICAL **: 13:51:06.828: unable to create file '/var/www/.cache/dconf/user': Permission denied. dconf will not work properly. I have given 777 permission to the folder and everything. It then fails in the code for the following stacktrace. Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.10/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/rest_framework/views.py", line 509, in dispatch response = … -
Django-components - Include all js files of all components every time
I designed some components in Django using django-components library. I noticed when I use the {% component_js_dependencies %} tag in pages I use components, it loads all javascript files of every components. Is there a way to load only the javascript files of the components I use in the page ? Thank you all I tried to specify some option but to no avail -
PostgreSQL returns Copy 0 for a csv file
I have a test database with 2 lines that consists of 7 fields integrated with django. Apart from that, I have another test database with an obvious error in it (random delimiters). The query is the following: COPY public.website_manager_tasks FROM 'C:\upwego_test\csvs\tasks.csv' DELIMITER '|' CSV HEADER; The database is the following: No extra spaces, strings have quotation marks, the delimiter is set properly, data types match, the name of the file doesn't match any columns. In the second database, the delimiters are set improperly: ; | | | | | However, the data from this database copies perfectly. I don't understand the postgre's problem here. I have tried changing the resetting the delimiters in the first database so that they matched the pattern in the second database, and it didn't help. I also tried to copy the text from the first database to the second database and everything worked perfectly. I have no idea why it happens so. I'd be glad if anyone could explain this glitch and am ready to provide additional details.