Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with serving all files from a user related media path in Django
I am trying to figure out how to serve all the pdf files from a specific media path thats related to a user, but cant seem to find anything specifically addressing my problem. I can pull the latest file, which shows up in the admin dashboard, but it ignores the rest of the files even though all the files are uploaded to the same folder. My models.py showing how I create the user directory path: def user_directory_path(instance, filename): return 'object_{0}/{1}'.format(instance.user.id, filename) files = models.FileField(null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=['pdf', 'doc', 'xlsx'])], upload_to=user_directory_path) My view: @login_required(login_url='reservation-login') @allowed_reservations(allowed_roles=['reservation', 'admin']) def home_documents_page(request): file_list = Reservation.objects.get(user=request.user) print(file_list) context = {'reservations': file_list} return render(request, 'MY_app/reservation-documents.html', context) My HTML {% if reservations %} <div class="reservation-docs"> <embed type="application/pdf" class="doc-item" src="{{ reservation.files.url }}"> </div> {% else %} <div class="not-found"> <h3>No Documents For This Reservation Available.</h3> </div> {% endif %} Like I said it pulls the latest file uploaded just fine but it wont pull all the files from the unique user path. My MEDIA_ROOT and MEDIA_URL are standard. Any help is greatly appreciated. -
Django timeuntil ignores timezone
I am trying to render some meetings in Django. When I display them, they show for example Aug. 10, 2021, 3 p.m, when it is 2pm. However, timeuntil returns 3 hours, likely because my timezone is UTC+2. How do I get it to display 30 minutes? USE_TZ = True already. <h3 id="calltime">The call is scheduled to start at {{ call.date_time }}</h3> <h3 id="calltime">The call is scheduled to start in {{ call.date_time|timeuntil }}</h3> This is what the website displays at 4:02pm: -
can't close message in django
I'm new to Django and I tried to integrate message alerts in my code using a tutorial. These are showed fine but I can't close them using the 'x' button. This is the code for the message section: {% for message in messages %} <div class="container-fluid p-0"> <div class="alert {{ message.tags }} alert-dismissible" role="alert" > <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> </div> {% endfor %} -
How do I change this name in the admin panel of Django?
As you can see, one thing is called "Productss" but I want it to not have that additional "s". I searched through all my files in VSCode with Ctrl+Shift+F but it didn't show up so it has to be something different. How can I change this? Thanks in advance! -
How to instantiate one form field from previous details page in Django?
I have the following view which displays the details of specific plan: def planodet(request, id): plan = Plan.objects.get(id=id) exercise = Exercise.objects.filter(plan=plan) context= {'plan': plan, 'exercise': exercise} return render(request, "web/exercise.html", context) In this template, I want to add a button that will take the user to a form that will let him add new Exercise to the plan, but I want the form to already have filled the Plan filled taking into consideration the plan detail page where he came from. The form is the following: class NewExercise(forms.ModelForm): class Meta: model = Exercise fields = ['exercise', 'series', 'reps', 'machine', 'plan'] widgets = { 'exercise': TextInput(attrs={'class': 'form-control form-control-lg'}), 'series': TextInput(attrs={'class': 'form-control form-control-lg'}), 'reps': TextInput(attrs={'class': 'form-control form-control-lg'}), 'machine': Select(attrs={'class': 'form-control form-control-lg'}), 'plan': Select(attrs={'class': 'form-control form-control-lg'}), } How should I instantiate this form so that it already has filled the Plan, so that it's the plan from the detail page where the user clicked on Add button. -
Does Paginator from django.core.paginator reduces the load on server?
I am using Django.core.paginator for splitting the data into pages in the Django web framework. data = emodel.objects.filter(Id=e_id, Date__range=(start_date,end_date)) and in paginator: page = request.GET.get('page', 1) paginator = Paginator(data, settings.PAGE_LIMIT) try: data_list = paginator.page(page) except PageNotAnInteger: data_list = paginator.page(1) except EmptyPage: data_list = paginator.page(paginator.num_pages) context = {"data_list":data_list} return render(request, 'my_app/data.html', context) Does the result fetch all queries first and then split it? or only PAGE_SIZE get fetched from a database? if "Yes" then, Is there any method to reduce the server load along with model.objects.filter(....) -
Kill All Celery workers on file change Django kill: illegal process id: $(ps
I have a Celery restart script setup in Django management - commands in my project. The script works fine up to the point where it is supposed to kill the existing Celery Process upon which OSX throws an error "illegal process id: $(ps". I have the following kill script (courtesy of Harshith): kill -9 $(ps aux | grep celery | grep -v grep | awk '{print $2}' | tr '\n' ' ') > /dev/null 2>&1 This script only works if I enter it manually into Terminal. Here is the full script in command: celery_worker.py import shlex import sys import subprocess from django.core.management.base import BaseCommand from django.utils import autoreload def restart_celery(): cmd = "kill -9 $(ps aux | grep celery | grep -v grep | awk '{print $2}' | tr '\n' ' ') > /dev/null 2>&1" subprocess.call(shlex.split(cmd)) subprocess.call(shlex.split('celery -A backoffice worker -B -l DEBUG')) class Command(BaseCommand): def handle(self, *args, **options): print('Starting celery worker with autoreload...') autoreload.run_with_reloader(restart_celery) What am I doing wrong? -
Django query create __mycondition same __startswish
I have 2 shorts questions related with query in Django: What's the name of that ('__startswith' '__lt' ...) How I can create '__mycondition' for query data.exclude(name__startswith="example") if you have examples I would like Thanks you :) -
How to extract title from uploaded user file Django
I am building a django web application where user upload a file (.docx), But before saving it I want a function that open the file that is being uploaded on runtime, Grab the title of that file and save that in title field in model. my models.py file is: class FileUpload(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') Remember that I want to do this when user upload the file but that file save with the title inside of that .docx -
Python json.loads does not convert + to space from the url
The url passes this json object in the url: filter_set = { 'filter_value': 'test filter' } 'test filter' in the url gets converted into 'test+filter' as you can't include a space in the url. This is done with the following code: filter_set = request_data.get('filter_set', None) filter_set = json.loads(filter_set) Everything gets parsed correctly except that the value of filter_value stays as 'test+filter' from the url encoding. Is there a better way to load the json that will first convert the + to a space? the framework I use is Django, and the request_data is set by for k, v in request.GET.items(): if k not in request_data: request_data[k] = v -
How to query using a field from the first related object in Django?
I have the following models: class User(models.Model): username = models.CharField(max_length=255, unique=True) display_name = models.CharField(max_length=255) ... class Profile(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=255) In a view, I have the a parameter called keyword. What I'm trying to do is query the User table for any users that contain the keyword in either the username field OR display_name field, AND also the first related profile's name field. Hopefully that makes sense. Is there a way to do this in one single query? Some users may not have any profiles, so that also needs to be accounted for. So far, I've got this: from django.db.models import Q def get_queryset(keyword): qs = User.objects.all() qs = qs.filter(Q(username__icontains=keyword), Q(display_name__icontains=keyword)) return qs Thanks for any help! -
Can I use celery like this?
Let's suppose I have a Django application which takes posts from users and uploads them to a third party storage using an API call. Now, these users hit the server only in a particular period of time every day, let's suppose it is at 11:00 clock and upto 11:20 only. Maximum requests can be upto 3000 (min 2500) i.e in a 20 mins span 3000 POST requests will be made to the server. And with each request 5-10 mb file is getting posted to the server and the server POST this file to third party storage using an API. I calculated the average time taken for this POST to API which is 5 seconds(Average). Now if I set celery in such a way that when a user does a POST on server I validate that post and hand over the uploading part to celery meanwhile my Django continues with the other requests in order keep a fluid operation for user while Celery takes care of uploading all the files one by one. Can I do something like that? If I can , what could be the drawbacks in it? Will there be a situation where I may lost some file … -
Reverse for 'my_views_name' with no arguments not found. django - jquery , connect server side with client side js
i want to make a button to update url , i called data from database using jquery-ajax , this is my views.py def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: item = { 'id':i.id, 'admin':i.admin.username, 'main_type':i.main_type, 'date':i.date } data.append(item) return JsonResponse({'data':data}) def update_maingroup(request,id): obj = get_object_or_404(MainGroup,id=id) form = MainGroupForm(instance=obj) if request.is_ajax() and request.method == 'POST' and request.user.is_superuser: if form.is_valid(): form = MainGroupForm(request.POST,instance=object) form.save() return JsonResponse({'success':'success'}) else: return JsonResponse({'success':False,'error_msg':form.errors,'error_code':'invalid'}) context = {'form':form,'obj':obj} return render(request,'update_maingroup.html',context) my form + my model 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) class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] but it raise this error: Reverse for 'update_maingroup' with no arguments not found. 1 pattern(s) tried: ['maingroup/update/(?P[0-9]+)$'] my templates $.ajax({ type:'GET', url:'/list-main-group', success:function(data){ data = data.data spinnerBox.classList.add('non-visible') var k = '<tbody>' for(i = 0;i < data.length; i++){ const date = new Date(data[i]["date"]).toLocaleString(); const id = parseInt(data[i]['id']) // const url = '{% url "products:update_maingroup" %}' // const my_url = url + "/"+id k+= '<tr>'; k+= '<td>' + data[i]['id'] + '</td>'; k+= '<td>' + data[i]["admin"] + '</td>'; k+= '<td>' + data[i]["main_type"] + '</td>'; k+= '<td>' + date + '</td>'; k+= '<td align="center">'+ '<button class="btn btn-info bg-info" id="update" data-url='+{% url … -
How do i make update function in Django
My project is discussion forum using Django and here are my create and update functions but update_post it should provide update functionality but Everytime i try to update a post it adds a new post? @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n its valid") author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() form.save_m2m() return redirect("home") context.update({ "form": form, "title": "Create New Post" }) return render(request, "create_post.html", context) @login_required def update_post(request): context = {} author = Author.objects.get(user=request.user) form = PostForm(request.POST , instance=author) if request.method == "POST": if form.is_valid(): print("\n\n its valid") new_post = form.save(commit=False) # new_post.user = author new_post.save() form.save_m2m() return redirect("home") context.update({ "form": form, "title": "UpdatePost", }) return render(request, "update_post.html", context) -
How to get the title of a file that we upload Django
I am working on a plagiarism-detection web app using Django , Where users upload the file . I want a function that open that file and get the title of that file and put that into the title field of the File Upload model and then save it . I do not know how to do this . my models.py is : class FileUpload(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') Thank you. -
Django redirect to a specifc place on the page with fstring
I am trying to redirect someone after completion of the form but keep getting errors self.success_url = redirect(reverse('circles') + '#circle' + str(circle.id)) it gives me this error: 'HttpResponseRedirect' object has no attribute 'format' I've tried: self.success_url = redirect(reverse('circles') + f'#circle{circle.id}') -
Django timeuntil doesn't respect timezone
I am rendering some meetings in Django. When I display they show for example 2pm. However, at 1:30pm, timeuntil returns 2 hours, 30 minutes, likely because my timezone is UTC+2. How do I get it to display 30 minutes? USE_TZ = True already. -
Django long polling request timed-out
Django 3.2 DRF run using ./mange runserver when deploying planing to use 'nginx, uwsgi' here is my backend code class ChatHandler(APIView): queryset = Chat.objects.all() serialzier_class = MessageSerializer def get_queryset(self): return self.queryset.filter(name=self.kwargs['room']).get() def get(self, request, room): optionail_last_message_time = request.data.get('at') new_messages = self.get_queryset().messages.filter(is_viewed=False) while not new_messages.exists(): print(timezone.localtime().time(), 'no new messages') sleep(3) print(dir(self)) print(dir(self.request)) print('oh here it is') last_time = new_messages.last().created_at.timestamp() serializered_new_messages = self.serialzier_class(instance=new_messages, many=True).data new_messages.update(is_viewed=True) return Response( { 'messages': serializered_new_messages, 'last_time': last_time, 'initial': False }, status=200 ) and here is the front-end code function textRequest(last_time) { $.ajax({ method:'GET', url:long_url, data: {'at': last_time}, timeout:2000, success : (data, status, xqhr) => { console.log(last_time) let messages = data['messages'] console.log(messages) if (messages) { for (let message of messages) { console.log(message) inject_message(message) } } setTimeout(()=>{ textRequest(data['last_time']) }, 5000) }, error: (error, status_text, xqhr)=> { if ((error.readyState == 0) && (status_text =='timeout')) { console.log(status_text) textRequest() console.log('sent') } }, }) } window.addEventListener('load', ()=>{ textRequest() }) issues: when i make refresh to the page it sends a new request to the back-end, and will continue in its recreation sending the requests, and back-end server receives a hundreds of requests question: How to limit the received number of request? when the server finds the data, and processes it back to the … -
How can i get next element assigned to ForeignKey?
How can i get next element assigned to ForeignKey? Example: To ForeignKey "Water" are assigned two models "Hot Water" and "Cold Water" so i want to make something like "next" and "previous" but only items that are assigned to ForeignKey. I made big research about that and i found nothing. -
Getting a list from URL with a regular expression django
I have the following view for filter Order objects based on a list of ids: class GetOrdersByIDs(generics.ListAPIView): serializer_class = OrderSerializer def get_queryset(self): print(self) ids = self.kwargs.get('ids') return Order.objects.filter(id__in=ids) I want to receive a list of ids from URL like this: myurl/ids/1,2,3,4, but I think I have to use a regular expression like this \d+(,\d+)*$, but I don't know how to get a list from this. -
Getting 404 not found when trying to update data using a query in Django
I'm trying to add a status in one of the DB table field where first I'm checking whether the passed ID is present in the table if yes then add. The ID is basically coming from the API path variable which I'm fetching and passing to the query. Below is the API which I'm using to call the class view. "/notify/<int:pk>/mark_as_seen/" "/notify/1/mark_as_seen/" # where 1 is the record Id in the DB table Below is the code which is querying the DB table and checks whether the passed Id is available. class MarkAsSeenView(BaseAuthenticationMixin, generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = SeenSerializer queryset = Seen.objects.all() def filter_queryset(self, queryset): qs = super().filter_queryset(queryset=queryset) qs = qs.exclude(seen_by_user=self.request.user).exclude(user=self.request.user) return qs def retrieve(self, request, *args, **kwargs): obj = self.get_object() obj.seen_by_user.add(self.request.user) return super().get(request, *args, **kwargs) Now when I'm calling this View via the above API it works perfectly in the first place where it will add one entry in the table as seen with the user id. Now the issue is after performing all the expected things it again going into the filter_queryset method and trying to search the same ID again which was already excluded in the previous iteration due to which it didn't get the same … -
Django Selenium on FreeBSD Exec format error geckodriver / chromedriver
I am trying to use selenium on django server (hosting with ssh, user permission). Os: FreeBSD 12.2-RELEASE amd64 display = Display(visible=False, size=(1325, 744)) display.start() opts = Options() opts.add_argument('--headless') import os path = os.path.abspath(os.getcwd()) driver = webdriver.Firefox(executable_path =path+"/geckodriver", options=opts) The "geckodriver" is set as 777 using ftp. I have tried: geckodriver-v0.29.1-linux32 geckodriver-v0.22.0-linux64 also with last Chromedriver x64 and Chrome Error: [Errno 8] Exec format error: '/usr/home/vitz/domains/xxx/public_python/geckodriver' Do you have any suggestion? :) -
Exclude is not excluding if searched users are in the list
I am building a small BlogApp and I build a feature of adding favorite users. I am now building a feature if searched user is already in another's users favorite user list then exclude the user from the list. For example :- If user_1 added user_50 in his favorite user's list. and then if user_2 searched user_50 then it will not show in the list. BUT when i try to exclude then it is not excluding. models.py class FavouriteUsers(models.Model): adder = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) favouriteUser = models.ManyToManyField(User, related_name='favouriteUser', blank=True) views.py def search_parent_cont(request): q = request.GET.get('q') exclude_this = ParentCont.objects.filter(childrens=request.user) results = Profile.objects.filter(user__username__icontains=q).exclude(exclude_this) serialized_results = [] for result in results: invite = True result_avatar = result.file.url serialized_results.append({ 'id': result.id, 'username': result.user.username, 'avatar': result_avatar, # 'email': result.email, 'about': result.about, # 'phone': result.phone, 'is_allowed_group_invite': invite, }) return JsonResponse({'results': serialized_results}) BUT this is showing :- TypeError: Cannot filter against a non-conditional expression. I have tried many times but it is still that error. Any help would be Appreciated. Thank You in Advance. -
Django upload image from form
I got this weird problem. I work with a PostgreSQL database. I made a model and form and migrated it, registered it in admin.py. When I am in the admin panel, I can add data to the form. One of the fields is an image, that is copied to media/images in the process. (MEDIA is declared in settings.py). This works like a charm. All the data (including the image) is saved in the database and can be displayed in html. But working from the admin-panel was not my first choice, so I made a html page with a form to input the data to the database. I fill in the fields, add the image and submit it. It tells me that the data is successfully added to the database. When I look in the admin panel, the record is indeed added, all the info is filled in, BUT the image is not. (it says no file is chosen). Also the image itself is not stored in media/images. If I add the image again in the admin panel, and save it, it works. So something goes wrong from the form to the database with saving the image. I googled a lot, … -
Python/Django 'ImportError: cannot import name 'python_2_unicode_compatible' in Django Rest Framework
I recently updated my DRF app from Django 2.1 to Django 3.1. But I keep receiving the error below when running the app. Before the upgrade the app was working fine. I'm using python version 3.9.0. Thanks in advance! ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' Here's the requirements.txt code: Django==3.1.2 djangorestframework==3.7.7 django-rest-swagger coreapi