Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to loop the query in djagno?
In my views.py file i am saving the form date having different last digit so how to loop them if request.method == "POST" : staff_id = request.POST.get('staff_id1', None) attendances = request.POST.get('attendance1', None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() staff_id = request.POST.get('staff_id2', None) attendances = request.POST.get('attendance2', None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() staff_id = request.POST.get('staff_id3', None) attendances = request.POST.get('attendance3', None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() you can see that the last digit of staff_id and attendance is different and rest is similar. I want to loop it as per date in table. -
Import a local json file and print it's values using views and templates in Django
I have downloaded a .json file and I want to show it's values in a table using Django view and templates. How should I do it? N.B: I do not want to populate any model(table). And one more thing is that pycharm and my laptop gets hung since the json file is large. -
Django - Query for Posts belonging to Goals by Categories?
So I have some models where each Category is comprised of Goals. For example, "Health" is a category and "lose 10lbs by my wedding" is a goal in that category. Then I have posts for that goal. So like post 1 could be about day 1 of the weight loss journey and so on and so forth. I need to be able to query for all posts by category and the response should be a list of dict where it contains: the post body, goal title, create date. How can I query for this quickly? The current method I have I think is less than ideal. I was going to query goals by category than query posts by goal, but then I'd had to iteratively append the goal description to every post then return it. This could be very slow. I think ideally I'd want to filter categories by the category I want then join on goals with that type then join on posts and return the relevant columns. class Goal(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_id") end_date = models.DateField( 'End date', null=True, default=None, blank=True) category = models.ForeignKey(GoalCategory, on_delete=models.CASCADE) description = models.CharField( max_length=255, validators=[MinLengthValidator(5)]) class Post(AbstractBaseModel): creator_id = models.ForeignKey( … -
cannot access file from its url in views django
I cannot access file from its URL in views Django but I can access it from templates in html files I tried a lot of things but it did not work for me code in the views.py error that appears -
Django ckeditor thumbnails are not generating after change the actual image
I'm working on a project using Python(3.9), Django(3) which is deployed on Heroku. My site is images intensive, so I decided to use django-imagekit to generate thumbnail for home page (because we are loading few articles on home page and each article has an image). When I setup imagekit it generate all the thumbnails and load correctly, then I make a change in the site and push new changes to Heroku, after that imagekit thumbnails stop working. I tried to re-upload images but it still doesn't work, even I tried removing the media/CACHE directory but it still not generating thumbnail when update an image. Here's what I tried: From settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'imagekit', 'django.contrib.sites', 'crispy_forms', 'avinit', 'ckeditor', 'ckeditor_uploader', 'storages', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ] MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' From models.py: class PostModel(models.Model): photo = ProcessedImageField(upload_to='blog_images', format='JPEG', options={'quality': 70}) # in your template thumbnails, use this image instead featured_thumbnail = ImageSpecField(source='photo', processors=[ResizeToFit(160, 160)], format='JPEG', options={'quality': 70}) -
Efficiently update same field multiple objects django
I have a model and I want to send increment a field value by 1 for multiple records. I searched for efficient update answers like Efficient way to update multiple fields of Django model object but they assume I have the value whereas I want to increment so the value might be different for different records. My Model looks something like this: class Signal(models.Model): name = models.CharField(max_length=80) version = models.IntegerField() In my view, I want to send a list of names and then update all of their versions by 1. My current method is to look through the names, create objects, update versions, and save manually so like this: signals = Signal.objects.filter(name__in=signal_names) for signal in signals: signal.pk=None signal.version = signal.version+1 signal.save() This results in way too many queries and is very slow because I'll be sending 100s of names at once. Is there a better way to do this? NOTE: This might seem similar to bulk update questions but in this case I want to increment 1 so I dont have the value to update with. That was my struggle with existing answers. Example: signal table name | version n1 | 1 n2 | 2 I send ["n1", "n2"] in … -
post_delete gets a different path than pre_save
I have a post_delete function that deletes an image after a user is deleted @receiver(pre_save, sender=User) def delete_file(sender, instance, *args, **kwargs): """ Deletes image files on `post_delete` """ if instance.image: path = instance.image.path if os.path.isfile(path): os.remove(path) When I change pre_save to post_delete It gets the right path which is /media/images/image.png but in pre_save it gets /media/image.png which is incorrect. -
How to copy android partition and recover deleted data?
I used this command to copy entire internal storage partition sda as sda.img (24.6 GB). adb pull /dev/block/sda sda.img Then I used OSFMount on Windows and mounted as read-only drive, but it shows Location is not available E:\ is not accessible. The parameter is incorrect. I opened it with 7-Zip and Winrar, but it shows that it can't be opened as archive. These are the partitions located on my phone, I assumed sda is internal storage and the size of the img is around the same size of what I see in file managers (23.84 internal, 3.94 GB root). 0 lrwxrwxrwx 1 root root 36 1970-01-06 10:24 bootdevice -> /dev/block/platform/soc/624000.ufshc 0 drwxr-xr-x 2 root root 1420 1970-01-06 10:24 by-name 0 brw------- 1 root root 7, 0 1970-01-06 10:24 loop0 0 brw------- 1 root root 7, 8 1970-01-06 10:24 loop1 0 brw------- 1 root root 7, 16 1970-01-06 10:24 loop2 0 brw------- 1 root root 7, 24 1970-01-06 10:24 loop3 0 brw------- 1 root root 7, 32 1970-01-06 10:24 loop4 0 brw------- 1 root root 7, 40 1970-01-06 10:24 loop5 0 brw------- 1 root root 7, 48 1970-01-06 10:24 loop6 0 brw------- 1 root root 7, 56 1970-01-06 10:24 loop7 0 … -
How to make filter Using multiple data value using Django Rest Framework and Angular 11
I am facing problem with searching and filtering in my project. I am using Django rest framework and PostgreSQL for backend and Angular 11 for frontend. my model class is class Project(models.Model): title = models.CharField(max_length=200) domain = models.ManyToManyField(Domain) environment = models.ManyToManyField(Environment) tools_and_technology = models.ManyToManyField(ToolsAndTechnology) user = models.ManyToManyField(User) photo = models.ImageField(blank=True, null=True,upload_to=uploadPath) def __str__(self): return self.title if a user select tools and technology for a project like C# or Java the result should be filtured and display. A user can filter by tools and technology, domain, environment. Each field can be multiple value. How can I solve this?? TIA -
How to export attendance login-logout data with login Image and logout image in Excel sheet using python django
I am using the python Django framework. I have to export filtered data in an excel sheet, but in that, I have modified some of the fields. Also, have to export login-logout images in that, I have already done it with CSV. but in csv can not format data as well as can not show images. it is showing me only URL strings. I am showing the code to export CSV: def ReportsDowbload(request): employees_attendance = EmployeeAttendance.objects.none() employee = Employee.objects.none() TotalHours=0 if request.GET: EmpId= request.GET["EmployeeId"] start_date= request.GET["start_date"] end_date= request.GET["end_date"] try: employee = Employee.objects.get(EmployeeId=EmpId) except Employee.DoesNotExist: employee = None else: e_id=employee.id employees_attendance = EmployeeAttendance.objects.filter(EmployeeId=e_id, Attendance_Date__range=(start_date,end_date)) mylist = [] for emp in employees_attendance: Logintime=emp.InTime Logouttime=emp.OutTime Date=emp.Attendance_Date InTime = datetime.datetime.fromtimestamp(Logintime) t1 = dt.strptime(str(InTime), '%Y-%m-%d %H:%M:%S') emp.InTime=t1.strftime('%I:%M %p') if Logouttime!=0: OutTime = datetime.datetime.fromtimestamp(Logouttime) t2 = dt.strptime(str(OutTime), '%Y-%m-%d %H:%M:%S') emp.OutTime=t2.strftime('%I:%M %p') WorkHours=t2-t1 emp.WorkHours=WorkHours dailyhours=int(WorkHours.total_seconds()) mylist.append(dailyhours) else: WorkHours=0 emp.WorkHours=0 dailyhours=0 emp.OutTime hours=sum(mylist)/3600 TotalHours=round(hours,2) file_name = "EmployeeReport"+str(date.today())+".csv" response = HttpResponse(content_type = 'text/csv') writer = csv.writer(response) if employee: writer.writerow(['Employee Id', employee.EmployeeId]) writer.writerow(['Employee Name', employee.EmployeeName]) writer.writerow(['Division', employee.Division.DivisionName]) writer.writerow(['Department', employee.Department.DepartmentName]) writer.writerow(['Total WorkHours',TotalHours]) writer.writerow([]) writer.writerow(['Attendance Date','In Time', 'Out Time', 'Daily WorkHours']) for item in employees_attendance: writer.writerow([item.Attendance_Date, item.InTime, item.OutTime,item.WorkHours]) response['Content-Disposition'] = 'attachment; filename = "'+ file_name +'"' return response else: writer.writerow(['Employee does not … -
django-tenants TypeError: argument of type 'TenantQueryset' is not iterable
i've made a system for hotels , i want to give it to several hotels with the same base code , i have used django-tenant-schemas and this is my SHARED_APP and TENANT_APP but when i try python manage.py migrate_schemas --shared it only creates my shared apps list and when i try either manage.py migrate_schemas --tenant or manage.py migrate_schemas it raise this error if public_schema_name in tenants: TypeError: argument of type 'TenantQueryset' is not iterable this is my settings.py SHARED_APPS = [ 'tenant_schemas', 'users', 'rosetta', 'widget_tweaks', 'import_export', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TENANT_APPS = [ 'rooms', 'vistors', 'booking', 'costs', 'payments', 'cancel', ] INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL= "rooms.Hotel" #db engine 'ENGINE': 'tenant_schemas.postgresql_backend', my models.py class Hotel(TenantMixin): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name class Room(models.Model): room_no = models.IntegerField(unique=True) #others and i have more models but all of them inherited from models.Model ,in the public schema it only created tables for SHARED_APP apps , TENANT_APP not created django version 2.2 db : postgresql is there something else i have to change or is'nt there another way to achieve that please -
The carousel cannot slide to the next image when I use forloop in Django
views.py def index(request): books = Book.objects.all()[:4] print(books) context = {'books':books} return render(request,'index.html',context) index.html <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for book in books%} {% if forloop.first %} <li data-target="#myCarousel" data-slide-to="{{forloop.counter0}}" class="active"></li> {% else %} <li data-target="#myCarousel" data-slide-to="{{forloop.counter0}}"></li> {% endif %} {%endfor%} </ol> <div class="carousel-inner"> {% for book in books %} {% if forloop.first %} <div class="carousel-item active"> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ book.image.url}}" alt="{{book.title}}"> <div style="font-size:50px;color:red;" class="carousel-caption">{{ book.title }}</div> </div> {% else %} <div class="carousel-item "> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ book.image.url}}" alt="{{book.title}}"> <div style="font-size:25px;" class="carousel-caption">{{ book.title }}</div> </div> {% endif %} {% endfor %} </div> <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon"></span> </a> <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next"> <span class="carousel-control-next-icon"></span> </a> </div> I am going to create an image carousel slider for the Book first four model objects. However when I put previous and next icons and after clicking the button it only staying at the first image instead of sliding to the next image. May I ask where is the problem that the image carousel could not slide? -
how to automatically rerun your page when you have urlopen error getaddrinfo failed
I would like to know how to automatically refresh or rerun a django view when I have this "urlopen error getaddrinfo failed" error, sometimes suddenly the view works and sometimes we have to update the html page. sometimes it comes from the long loading of the view i want to fix this problem but i dont know how, my code is working fine, everything is normal thank you -
Trouble with using ngix and uwsgi
I am trying to connect django uwsgi and nginx however, I have encountered some problems as below. when I start nginx, I got an error as below nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied) whenever I access 127.0.0.1:8080 which is configured in nginx conf file, I got 504 Gateway Time-out. But I can access 127.0.0.1:80 and can see Welcome to nginx! html page. I share my nginx conf file and please help me to connect uwsgi(127.0.0.1:8000) and nginx(127.0.0.1:8080) upstream django{ server 127.0.0.1:8000; } server{ listen 8080 default_server; server_name 127.0.0.1 default; charset utf-8; location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; root /home/bigdata/Django_Web; } location =/favicon.ico { return 204; access_log off; log_not_found off; } location /static { alias /home/bigdata/Django_Web/staticfiles; } } Appreciate in advance! -
Python Django converting media file
How can I convert video file from .mp4 to other formats (mpg,mpeg,3gp and mp3) with a Django or python libraries? -
Add a custom button/ tag and control its function using a python script in Django web application
I am quite new to web application development (Django). However, I have a bit of experience in working with html, css, and python. I am developing an application where the user will upload documents as input and change the available parameters values and the application will produce a document in excel format. (Text editor: VS Code) (To get an intuition, consider the online pdf resizing applications as an example). I am building the application from scratch. The major issue is modifying the inputs and producing desired output. My approach towards it is: Create python scripts for the different major actions( As per our example, create py scripts for pdf compression, merging two pdfs and so on). Ask the user to upload the required documents. Store the docs uploaded (only temporarily) and use them for further operations (with assumption that default sqlite3 will be sufficient). In the webpage, add a button or a link (e.g. "Compress", "Merge") and embed the python script (paste the script or add a link to its location) created in step1. That will perform the specific task when the button is pressed. I have achieved till the step 2 in my task but am lost on how … -
django-mailbox is not working for outlook
I am using django-mailbox for getting inbox emails From This package, HERE This is working fine for pop3 mailbox type for Gmail account but not working outlook account I am getting following error code b'-ERR Logon failure: unknown user name or bad password.' but when I am using imap mailbox type then I am able to get emails from Gmail and outlook but when I am using imap mailbox type my emails are deleted from my Gmail and outlook servers Here is my URI setting for outlook and gmails POP3 Gmail: pop3+ssl://username:password@imap.gmail.com Outlook: pop3+ssl://username:password@imap.outlook.com IMAP Gmail: imap+ssl://username:password@imap.gmail.com Outlook: imap+ssl://username:password@imap.outlook.com Let me know if someone has any solutions Thanks in advance -
How to access Django app in docker container from another machine?
I am pretty new to Docker and Django. So what i did was, putty to a linux server and created a folder in the root directory and then using django-admin startproject I started a new project. Now, since I am using putty for ssh terminal access, I will not be able to access a browser in the linux machine and then ping 127.0.0.1:8000 to see whether "congratulations!" screen by Django is visible or not. So I assumed that the server might be running after runserver command. Then using docker I prepared a container in the linux machine where I have exposed port 9000. Also I cannot access this container since I cannot access the browser in the linux machine. Now, I have three questions below: 1.) How to access this docker container (inside the linux machine) using my windows machine? By this I mean, if I open up lets say google chrome browser in the windows machine, and enter some url:port, will I be able to see the "congratulations!" screen on my browser on windows? 2.) I am pretty confused with how this container network port and ip works (I mean how does host or any other pc access this … -
DRF with MongoDB getting the object data
I am using DRF with MongoDB. I am inserting the JSON object in MongoDB in the external source. This is my schema _id : ObjectID("") feed: Object sensor_type: Int received_at: datetime.now() My question is how I can get this data using DRF using the serializer. I have one doubt is there any way I can this feed object? -
get_context_data() missing 1 required positional argument: 'request'
i got a problem, when i try to redirect from a class based view without 'redirect' on def get_context_data, i got errors like 'str' object has no attribute 'user'. so i think the best way to solve this is adding request as a parameter on my get_context_data. but i get the title error. Here is my views: class EstandarViews: '''Vistas usuario Estandar''' @staticmethod def estandar_home(request): ''' Vista del home de estandar ''' return render(request, "pages/editor-estandar/home.html") class EditorEstandarView(LoginRequiredMixin, TemplateView): template_name = "pages/editor-estandar/estandar.html" def get_context_data(self, request, **kwargs): user = self.request.user print("usuario: ", user) if not self.request.user.groups.filter(name="Editor-Estandar").exists(): print("no puedes estar aqui") return redirect('/home/') context = super().get_context_data(**kwargs) context["sedes"] = Sede.objects.values("nombre", "id") context["recintos"] = Recinto.objects.values("id", "codigo", "nombre") context["carreras"] = Carrera.objects.values("id", "codigo", "nombre") return context editor_estandar_view = EditorEstandarView.as_view() -
FastAPI vs Django- can't explain "hello world" benchmark results
I was wanted to benchmark FastAPI(0.68.1) and Django(3.2.6) and compare the results of a simple "Hello World" applications. (Python 3.8.5) The code for FastAPI (ran it with uvicorn): from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} The Code For Django: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world") I constantly read online, about FastAPI being asynchronous and I expected FastAPI to perform better than Django since it runs on one thread. And I got the opposite results. With this small application, Django outperformed FastAPI. I benchmarked this using locust, spawning 300 users while each user is making get requests. (though for different parameters I got similar results and Django performed even better) The locustfile.py code is: from locust import HttpUser, task class QuickstartUser(HttpUser): @task def hello_world(self): for i in range(1): print("sending reqeust") self.client.get("/") Attaching here the results Django (port 8000) FastApi (port 3636) Can someone please explain those results? Did I do something wrong with my benchmark? Thanks a lot, would appreciate some guidance here! -
Prefetch_related many to many
I need your help. I have two models with manytomany relationship, I'm using prefetch_related but I'm having some problems trying to render the QuerySet in the template. My question is, how can I show the data in the html file. The models: class Book(models.Model): name = models.CharField(max_length=300) price = models.IntegerField(default=0) class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) class Meta: default_related_name = 'stores' The view: def mtmtest(request): books = Book.objects.prefetch_related('stores').all() return render(request, 'mtm.html', {'books': books}) -
Is there a way to control the formset properly?
I have a web which has the following form as shown in the pic below. Its basically a formset which is control by a button to limit the no. of form created or remove whatever form that is not needed. So whenever i clone the formset. It will appear as form-(number)-(fieldname). I have a '-' button which has the codes to reduce the number by 1. $(document).on('click', '#removerow', function () { let totalForms = $('#id_form-TOTAL_FORMS').val(); let actualformcount = totalForms-2; $('#id_form-TOTAL_FORMS').attr('value', (parseInt (totalForms))-1); $(this).closest('#morerows .row').remove(); if(actualformcount < maxrow){ $('#addrow').attr("disabled", false) $('#addrow').attr("class","btn btn-outline-success btn-rounded") $('#addrow i').attr("class","dripicons-plus") $('#addrow').html("+") } The above codes work for this image: Working as intended for delete of last row More about this 1st image: If i clone to the max limit i set and i delete the last row (circle in red). The ones that are circle in blue get saved to my database. But if i change the way i delete. I delete the 2nd clone (circle in blue this time), the ones that are circle in red this time get saved to database. But the last row does not get saved: Not working as intended for delete of any row other than last row Can anyone … -
Django - Test endpoints with authentication
How do you test endpoints in Django and ensure they have a valid JWT token when making a request? I'm using AWS cognito and amplify. I have these tests below and all these endpoints require user auth. Is there a way to generate a fake user token using AWS cognito or amplify during test then pass it when running these tests? tests.py class PostTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: GoalCategory.objects.create(category='other', emoji_url='url') cls.user = UserFactory() cls.goal = GoalFactory() def test_create(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) def test_improper_goal(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': 'some messed up UUID', 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) all the above requests being tested have token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] print(token) try: res = jwt.decode_cognito_jwt(token) except: return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) -
Linkedin OAuth works for http but not for https, Django app
LinkedIn OAuth works fine with http://example.com but after encrypting the site, it didn't work. It returns 'internal server error'. The stack is Django/Python. avatar_url = None if request.user.social_auth.filter(provider='linkedin-oauth2'): access_token = request.user.social_auth.get(provider='linkedin-oauth2').extra_data['access_token'] response = requests.get( 'https://api.linkedin.com/v2/me?projection=(id,profilePicture(displayImage~:playableStreams))', headers = {'Authorization': 'Bearer {}'.format(access_token)} ) avatar_url = response.json()['profilePicture']['displayImage~']['elements'][1]['identifiers'][0]['identifier'] The snapshot is standard for Django calling the auth. What seems wrong here? Any clue?