Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React App as a Django App in a Docker Container - connection refused when trying to access APIs on localhost:8000 urls
hope you might have some guidance for me on this. Right now I have a React app that is part of a Django app (for the sake of ease of passing auth login tokens), which is now containerised in a single Dockerfile. Everything works as intended when it is run as a Docker instance locally, but the Docker Image is having issues, despite the fact that the webpages are visible when the Image is deployed on server. Specifically, when the Docker image is accessed, the home page renders as expected, but then a number of fetch requests which usually go to localhost:8000/<path>/<to>/<url> return the following error: GET http://localhost:8000/<path>/<to>/<url> net::ERR_CONNECTION_REFUSED On a colleague's suggestion, I have tried changing localhost:8000 to the public IP address of the server the Docker Image is hosted on (eg 172.XX.XX.XXX:8000) but when I rebuild the React app, it defaults back to localhost. Here are my questions: Is this something I change from within the React application itself? Do I need manually assign an IP address? (This seems unlikely to me) Or is this something to do with either the Django port settings, or the Dockerfile itself? Here is the Dockerfile FROM ubuntu:18.04 # ... RUN apt-get … -
django-autocomplete-light ModelSelect2Multiple not rendering values
So this is the situation: I am using django-autocomplete-light and I got it working on a few forms, however, when tying to implement it on a M2M field it just doesn't render the values in the select field. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=11, blank=True) customer = models.ManyToManyField("customers.Customer") def __str__(self): return self.user.username class CustomerAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Customer.objects.none() qs = Customer.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class UserProfileForm(autocomplete.FutureModelForm): class Meta: model = UserProfile fields =('__all__') widgets = { 'customer': autocomplete.ModelSelect2Multiple(url='customer-autocomplete'), } in urls.py i got" url(r'^customer-autocomplete/$', CustomerAutocomplete.as_view(),name='customer-autocomplete',), when i got to the autocomplete url: customer-autocomplete/ i got: {"results": [{"id": "2", "text": "Oozz", "selected_text": "Oozz"}, {"id": "1", "text": "Voolia", "selected_text": "Voolia"}, {"id": "3", "text": "Feedspan", "selected_text": "Feedspan"}, {"id": "4", "text": "Layo", "selected_text": "Layo"}, {"id": "5", "text": "Babbleblab", "selected_text": "Babbleblab"}, {"id": "6", "text": "Digitube", "selected_text": "Digitube"}, {"id": "7", "text": "Feednation", "selected_text": "Feednation"}, {"id": "8", "text": "Dabjam", "selected_text": "Dabjam"}, {"id": "9", "text": "Zoomlounge", "selected_text": "Zoomlounge"}, {"id": "10", "text": "Zoomzone", "selected_text": "Zoomzone"}], "pagination": {"more": true}} it renders no customers: However if i remove the widget on my form.py: widgets = { 'customer': autocomplete.ModelSelect2Multiple(url='customer-autocomplete'), } It renders all customers: I guess this issue is not related to … -
I want To get all the categoy 1 level
class categories(models.Model): name = models.CharField(max_length=40) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') I want To get all the categoy 1 level categories2 = categories.objects.get(name=sub-categoy 1 ) categories2.children.all() -
how can I fixs the bug "The client noticed that the server is not a supported distribution of Elasticsearch" [closed]
when I start the django project ,the new error print in the controll ,and there is nothing I changed,what make this happened? -
How can I do to filter zero values using Django?
I am using Django and I have this query : a = User.objects.all() And I would like to remove the entries such as the field a et b are equals to 0. But the problem is that in my field I have either 0 either {"total": 0} but also {"total": 0, "2": 0} And I want that when all the values are 0 I remove that from a. Could you help me please ? Thank you very much ! -
Django web app mail using Sendgrid or Amazon SES - Not receiving emails
Thank you very much for helping people with software issues. I'm developing a simple web application using Django, and I wanted to have a contact form so users can contact me for feedback and other topics. That mail would arrive in my Gmail for simpler communication. I have followed many tutorials and update settings.py, forms.py, and views.py many times and I still have not received any email unless I send it via cmd like this: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'validated email', ['validated email'] ) I have of course created accounts in both SendGrid and Amazon SES, validate the emails, and used the keys. for views.py I have used these two contact views, one or the other, and I have modified any part of them many times trying to get the receive the email, don't pay attention if there is any indentation issue, with Visual Studio is easily fixed, also validated email is the email I used with SES or Sendgrid from django.shortcuts import render, redirect from .forms import ContactForm from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if … -
Django get url variables within get_context data?
Say I have a url likes this path( 'foo/<int:foo_id>/edit/', views.FooView.as_view(), name='foo', ), and a view likes this: def get(self, request, foo_id): I find a common idiom is getting the URL variable foo_id into the context. The only thing context has access to be default is request. I tried checking request and request.GET and could not see anything. Is there a better way than: Manually adding url variables to the context_data after get_context_data() or passing it into get_context_data from a custom call from get? (ugly because class based views expect the same get_context_data signature) -
How do I add a header to a Django RequestFactory request?
I am creating an API in Django and my API has few custom views for authenticating with JWTs (getting a token, refreshing a token, etc.). To manually send a GET request to an endpoint that requires authentication, I do this with curl: curl http://example.com/endpoint -H "Authorization: Bearer [ACCESS_TOKEN]" To test the authentication views, I want to write a unit test that makes an authenticated request (using django.test.RequestFactory) with a JWT. How can I add a header to the request? For clarity, below is an example of what I'd like to be able to do, though what I have written below is not valid code because RequestFactory.get() does not have a headers parameter: from django.test import TestCase, RequestFactory class TestClassForAPI(TestCase): def test_an_api_test(self): factory = RequestFactory() token = '...' auth_header = f'Authorization: Bearer {token}' factory.get('/endpoint/', headers=auth_header) -
Capitalization not displayed in Django site after modifying Django models.py [closed]
you see, in the str method, the upper() method is applied, though no result this is the view i get, with no capitalization, even after modifying the code -
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!