Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
inserting a lot of data via create_bulk
hello I have a table named Exercise data where I pass data from form and save them in the db, my problem is that I have more same objects to save inside the db but I don't know how to do it. I left you my views.py file where you can find the code I created. I read around that I should use the create_bulk but I don't understand how I can pass it some data from my form, could someone help me please? =) views.py @login_required def creaScheda(request): if request.method == "POST": form = CreaSchedaForm(request.POST) if form.is_valid(): schedaName = form.cleaned_data['nome_scheda'] scheda = form.save(commit = False) scheda.utente = request.user scheda.save() gruppi = DatiGruppi( giorni_settimana = form.cleaned_data['giorni_settimana'], dati_gruppo = form.cleaned_data['dati_gruppo'], gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) ) gruppi.save() esercizi = DatiEsercizi( serie = form.cleaned_data['serie'], ripetizione = form.cleaned_data['ripetizione'], peso = form.cleaned_data['peso'], gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id), dati_esercizio = form.cleaned_data['dati_esercizio'] ) #esercizi.save() print(esercizi) return redirect('/backoffice') else: form = CreaSchedaForm() context = {"form": form} return render(request, "crea_scheda.html", context) -
how ro solve error TypeError: 'RelatedManager' object is not iterable
I have to models (Meeting and Meetingmemeber) to save information of a meeting and invited people and i use seriliazer like this : class MeetingSerializer(serializers.ModelSerializer): location = MeetingLocationSerializer( required = False) host = serializers.PrimaryKeyRelatedField(read_only=True) members = serializers.ListField(child=serializers.EmailField()) class Meta: model = Meeting fields = ['id','title','description','date_time','time_zone','host','is_private','is_virtual','url','location','host','members'] extra_kwargs = {'location': {'required': False}} and this is create() : def create(self, validated_data): location_data = validated_data.pop('location') members = validated_data.pop('members') meeting = Meeting.objects.create( host=self.context['request'].user, **validated_data) if location_data: MeetingLocation.objects.create(meeting=meeting,**location_data) if members : for member in members: if member == self.context['request'].user.email: MeetingMember.objects.create(meeting=meeting, email = member, status="H") else : MeetingMember.objects.create(meeting=meeting, email = member, status="I") return meeting i sent this json and meeting information was saved in meeting models\ and invited emails were saved in Meetingmember model : { "location": { "lat": "0.0000000000000003", "lng": "0.0000000000000002" }, "title": "bynas1006", "description": "lets go removed2", "date_time": "2021-06-30T06:14:00Z", "time_zone": "Africa/Abidjan", "is_private": true, "is_virtual": true, "url": "www.google.com", "members":[ "me@me.com", "admin@admin.com" ] } but i got this error in terminal : TypeError: 'RelatedManager' object is not iterable I have no idea why i got this error -
How to reuse Django's admin foreign key widget in admin intermediate pages
I haven't been able to find the answer anywhere on Django's documentation. Though, I'm not surprised given the question is a bit too complex to ask to a search engine. I'm in a situation where I need to be able reassign a ForeignKey field for one or more entries of a model on Django's admin site. So far, what I tried to do so using a custom action so that I can select the records I'm interested in and modify them all at once. But, then, I need to select the new related object I want their fk to be reassigned to. So, what I thought to do is an intermediate page where I'd display the fk widget I see all around the admin pages: But it turns out this widget is really not designed to be publicly used. It's not documented and it's heavily complex to use. So far, I lost several hours digging into Django's code trying to figure how to use it. I feel like I'm trying to do something really really exotic here so, if there's another solution, I'm all hears. -
Error when using "through" intermediate model with django-sortedm2m
Is it possible to define my own intermediate model with sortedm2m using through? In my case I have this model: class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) indexes = SortedManyToManyField(Index, through='SamplePoolIndexCand', blank=True) pools = SortedManyToManyField(Index, through='SamplePoolIndexCand', blank=True) gene_lists = SortedManyToManyField(Index, through='SamplePoolIndexCand', blank=True) My intermediate table: class SamplePoolIndexCand(models.Model): sample_id = models.ForeignKey(Sample, null=True, blank=True, on_delete=models.CASCADE) pool_id = models.ForeignKey(Pool, null=True, blank=True, on_delete=models.CASCADE) index_id = models.ForeignKey(Index, null=True, blank=True, on_delete=models.CASCADE, gene_cand_list_id = models.ForeignKey(GeneCandList, null=True, blank=True, on_delete=models.CASCADE) class Meta: unique_together = (("sample_id", "pool_id", "index_id", "gene_cand_list_id"),) I got this error message: AssertionError: The model is used as an intermediate model by '<class 'myproject.models.SamplePoolIndexCand'>' but has no defined '_sort_field_name' attribute How can I solve this? I tried to add an ordering field in the intermediate table but I got the same error: class SamplePoolIndexCand(models.Model): sample_id = models.ForeignKey(Sample, null=True, blank=True, on_delete=models.CASCADE) pool_id = models.ForeignKey(Pool, null=True, blank=True, on_delete=models.CASCADE) index_id = models.ForeignKey(Index, null=True, blank=True, on_delete=models.CASCADE, gene_cand_list_id = models.ForeignKey(GeneCandList, null=True, blank=True, on_delete=models.CASCADE) sort_value = models.IntegerField() class Meta: ordering = ["sort_value"] unique_together = (("sample_id", "pool_id", "index_id", "gene_cand_list_id"),) I'm using Django version 3.1.7 and Python 3.8.10. -
Used Django Filters and exporting data using CSV
I made a filter search form to filter through some items based on the name and category. It is working but I want to be to export items using CSV but it fails. It keeps showing me this page [![error django page][1]][1] [1]: https://i.stack.imgur.com/H8BYK.png and think this is the error but please scroll down to see views, URLs, models and template context {'filter_form': <inventory_app.filter.ProductFilter object at 0x00000268BD07A940>, 'products': <QuerySet [<Product: HP laptop-10>, <Product: HP computer-40>]>} filter_form <inventory_app.filter.ProductFilter object at 0x00000268BD07A940> products <QuerySet [<Product: HP laptop-10>, <Product: HP computer-40>]> request <WSGIRequest: GET '/'> The Views def item_list(request): products = Product.objects.all() filter_form = ProductFilter(request.GET, queryset= products) products = filter_form.qs context = { "filter_form": filter_form, "products": products, } *This is the CSV export function where it fails* if filter_form['export_to_CSV'].value() == True: response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="my_inventory.csv"' writer = csv.writer(response) writer.writerow(['CATEGORY', 'ITEM NAME', 'QUANTITY']) instance = products for product in instance: Writer.writerow([product.category, product.item_name, product.quantity]) return response return render(request, 'item_list.html', context) The Filter Search form import django_filters from .models import Product from django import forms class ProductFilter(django_filters.FilterSet): export_to_csv = django_filters.filters.BooleanFilter(widget=forms.CheckboxInput) class Meta: model = Product fields = ['item_name', 'category', 'export_to_csv'] URLs path('', item_list, name='item_list'), The template <form method='get' action=''>{% csrf_token %} {{ filter_form.form|crispy … -
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.