Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to annotate with count of related model items
I have these models: class Gym(models.Model): name = models.CharField() class Employee(models.Model): name = models.CharField() gym = models.ForeignKey(Gym) class Appointment(models.Model): time = models.DateTimeField() gym = models.ForeignKey(Gym) class AppointmentItem: name = models.CharField() employee = models.ForeignKey(Employee) appointment = models.ForeignKey(Appointment) I want to get a list of salon employees by appointment item count. How can I do this? -
How can i store the Django view class response into other function and execute it into next one function?
Info: I want to make app like upload file before submit the form. I am upload the files using uppy which is a front-end library. TusUpload will receive the file data and store in Library model. I want to get the uploaded files into the another view function for attach these uploaded files with other Model object. I mean, i want to store the TusUpload response in anther function and then create_page will take these uploaded files before submit the form and then submit it with the Post model object. I know the ajax will store the TusUpload response and then we pass these files ID's in 'create_pagebut i don't want to use this method. I want to pass these filesID's` in backend Not with javascript. I hope you will be able to provide the information. class TusUpload(View): def post(self, request, *args, **kwargs): metadata = self.get_metadata(request) metadata["filename"] = self.validate_filename(metadata) message_id = request.META.get("HTTP_MESSAGE_ID") if message_id: metadata["message_id"] = base64.b64decode(message_id) file_size = int(request.META.get("HTTP_UPLOAD_LENGTH", "0")) tus_file = TusFile.create_initial_file(metadata, file_size) return TusResponse( status=201, extra_headers={'Location': '{}{}'.format(request.build_absolute_uri(), tus_file.resource_id)}) def head(self, request, resource_id): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) return TusResponse( status=200, extra_headers={ 'Upload-Offset': tus_file.offset, 'Upload-Length': tus_file.file_size, }) def patch(self, request, resource_id, *args, **kwargs): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) chunk = TusChunk(request) if … -
Django File upload looping
How would I best loop a form like this (there is other code in the form but this is an example for image uploading) <form action="{% url "upload" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image_file"> <input type="file" name="image_file2"> <input type="file" name="image_file3"> <input type="file" name="image_file4"> <input type="file" name="image_file5"> <input type="submit" value="submit" /> </form> for single file uploading but need it multifile uploading: def image_upload(request): if request.method == "POST" and request.FILES["image_file"]: image_file = request.FILES["image_file"] fs = FileSystemStorage() filename = fs.save(image_file.name, image_file) image_url = fs.url(filename) print(image_url) return render(request, "upload.html", { "image_url": image_url }) return render(request, "upload.html") Just not sure how to loop it so images are stored along with filename in a var for the db (at a later point) also just a thought, might not always be uploading all five files could be three or none -
Filter the data based on best time to visit the place using Django
Hey guys I am working on a Django project! I have a bootstrap form where the users can fill out the starting and ending dates of their travel. I need to filter the data if the dates fall under the specified month's range in my Django model. I tried to simulate one but it's not filtering the data.. can someone help me out with this? The code for the same is pasted below. The following is the code for my models.py, views.py, and tourform.html respectively! For example, the best time to visit an Amusement park is during the summer so I'll be storing the starting_month in a Django field of the tour model and the ending month in the end_month field of the model. Whenever a user tries to submit the form I'll slice the month from the starting and ending dates entered by the user and I need to filter all those places which are best to visit during those specified months based on the start and end month field present in the database. models.py start_month_choices=[('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'),('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December')] end_month_choices=[('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'),('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December')] start_month=models.CharField(max_length=2,choices=start_month_choices,default='1') end_month=models.CharField(max_length=2,choices=end_month_choices,default='1') views.py if request.method=='POST': contents=Tour.objects.all() category1= request.POST['category'] category2=request.POST['place'] start_date=request.POST['startdate'] end_date=request.POST['enddate'] datem_start = datetime.datetime.strptime(start_date, "%Y-%m-%d") start_month1=datem_start.month datem_end = datetime.datetime.strptime(end_date, "%Y-%m-%d") end_month1=datem_end.month tour_data … -
How to mail a pdf file stored in the database in the media folder to a user -Django
I have a model that stores some pdf files. I want to mail a pdf file as an attachment when a user requests to do so. I tried a way to do it like this @api_view(['POST']) def send_pdf_to_user(request): id = request.data.get('id') try: query = Civil.objects.get(id=id) file = query.pdf_file email = EmailMessage( 'Subject here', 'Here is the message.', 'from@me.com', ['user@gmail.com']) email.attach_file(file) email.send() return Response(status=200) except Exception as e: print(e) return Response({str(e)}, status=400) but received this error expected str, bytes or os.PathLike object, not FieldFile The file when printed gives this which is the path where the file is being stored civil/random.pdf Please suggest to me the way to mail pdfs which are pre stored in the database. -
How would I pass request.user into my form?
I'm trying to create a posts form that lets the user create posts on my site. I've been stuck on how to pass request.user into the fields "author" and "participants". Could anybody help? Here is my view: def home(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('') My model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) participants = models.ManyToManyField(User, related_name="participants", blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-created"] def __str__(self): return self.body And my form: from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = '__all__' -
How can I override the Django DurationField model to input minutes instead of seconds?
I'm trying to create a custom Duration Model, I'm just not sure about how this is done, the documentation is slightly confusing when it is explaining how to create custom model fields, and I am new to Django. https://docs.djangoproject.com/en/4.0/howto/custom-model-fields/ -
How Can I get Sum Total of Django Model Column through a Queryset
I am working on an Event App where I want to get the Total Amount of Pin Tickets that has been activated and I don't know how to do it. Below is what I have tried and I am getting this error: 'QuerySet' object has no attribute 'ticket' Here are my Models class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) Here is my Views.py from django.db.models import Count, Sum def profile(request): amount_sold_pins = Pin.objects.filter(status='Activated') total_sold_tickets = amount_sold_pins.ticket.price total = total_sold_tickets.aggregate(total = Sum('price')).get('total') or 0 context = { 'guest':reservations, 'total':total, } return render(request, 'user/profile.html', context) Someone should please help with the best way of … -
How to make a python script to work with Django
so I have a python script I'd like to integrate to work with python. No matter what I do I don't seem to get it right. Below are what I've managed to do successfully which is getting Django to accept picture upload and display them to the user. https://replit.com/@Eddyah5/ImageConverterwithHTML#main.py I'm now trying to get my python script in the link above to work in Django to let users upload pictures out of the list of supported formats, convert the picture to .ico of different sizes, and zip them for download by users. Please pardon me I'm very new to python/Django. What to do with the views.py, models.py as pertaining my code is in the link below? https://replit.com/@Eddyah5/ImageConverterwithHTML#main.py I'm very new to python and Django, so any help I will deeply appreciate. -
TemplateDoesNotExist at / pythonanywhere
I am using Django 4.0.6 and I'm trying to host my web app at pythonanywhere.com but I get this error. I don't understand why it's happening, I looked at the settings.py and I didn't see anything wrong, all of the requirements are installed, the settings are looking alright , the WSGI file is good I don't get why this error keeps popping up. Here's my settings file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'frontend/build') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Here is where the error is occurring. def select_template(template_name_list, using=None): """ Load and return a template for one of the given names. Try names in order and return the first template found. Raise TemplateDoesNotExist if no such template exists. """ if isinstance(template_name_list, str): raise TypeError( "select_template() takes an iterable of template names but got a " "string: %r. Use get_template() if you want to load a single " "template by name." % template_name_list ) chain = [] engines = _engine_list(using) for template_name in template_name_list: for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) if template_name_list: raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain) else: raise TemplateDoesNotExist("No template names provided") It's … -
Jupyter lab not loading user settings file in docker container
Here's my setup: Docker app with django, loading jupyterlab via django-extensions shell_plus --notebook invocation. I have a directory of JSON files with the desired settings, e.g. user-settings/@jupyterlab/*-extensions/. These are directly copied from a local jupyter server set up the way I like. Jupyterlab runs just fine from the container, and when I connect to the server, I can open the Advanced Settings Editor, open the JSON files, copy-paste the contents into the settings editor pane, and everything works great. After copy-paste and save, the settings files are generated in ~/.jupyter/lab/user-settings/@jupyterlab/*-extensions/. So far so good. What I want to do is, as part of the Docker image setup (or even via a simple bash script), copy the settings from where they're stored to the proper location and have jupyter lab read them and have my settings loaded. However, even when the same files with same contents are pre-copied to the eventual destination (~/.jupyter/lab/user-settings/@jupyterlab/*-extensions/), none of the settings are loaded when the server starts. Even when I open jupyter, invoke a terminal, and copy the files to the proper location, the settings don't load. As I understood it, the presence of properly-formatted files in the proper location is all jupyter needs to … -
window.location.href only gets the host name and not the whole path of the current page
Every time I try to copy link, it only copies the host name and not the full path of the page where I'm at. JS Code: document.getElementById('copyLink').onclick = function() { navigator.clipboard.writeText(window.location.href); } -
Stop updating Django query
query = Movimentacao.objects.all() for m in movimentacoes: # this query couldn't be update everytime an item is added to database q = query.filter(entrada_saida=m[0], data=m[1], movimentacao=m[2], produto=m[3], instituicao=m[4], quantidade=m[5], preco_unitario=m[6], valor_da_operacao=m[7]) # check if the object exist if q.exists(): pass else: # new object is going to be created because it does NOT exist yet line = Movimentacao(entrada_saida=m[0], data=m[1], movimentacao=m[2], produto=m[3], instituicao=m[4], quantidade=m[5], preco_unitario=m[6], valor_da_operacao=m[7]) counter += 1 line.save() How can I prevent this 'q' query from being update everytime the looping is repeated? What I'd like is get the original objects from the database. -
Error message in installing PostgreSQL extensions in Django project
Following a tutorial (which is over a year old), the instructions for creating an empty migration in an app named "accounts", in order to install PostgreSQL extensions, is as follows: python manage.py makemigrations accounts --empty --name="postgres_extensions" But when I enter this line in my Terminal, I get the following error: ModuleNotFoundError: No module named 'settings' Looking at the documentation in djangoproject.com, it seems the correct way to enter this in the Terminal would be this: python manage.py makemigrations --empty accounts --name postgres_extensions But when I enter that in my Terminal, I get the same error as above. -
How to display conditional form field that is dependent on an attribute of a selected foreign key on django model form
I want to conditionally display either frequency_input or duration_input fields based on the behavior.recording attribute of the selected behavior. I have a Trial form that currently displays 3 fields: behavior_name (foreign Key) dropdown frequency_input duration_input Im not sure if i should the best method to solve this (Javascript or solve in the View)? Trial Model class Trial(models.Model): behavior_name = models.ForeignKey(Behavior, on_delete=models.CASCADE) client_session = models.ForeignKey(Client_Session, on_delete=models.CASCADE) frequency_input = models.PositiveIntegerField(default=0, blank=True) duration_input = models.DurationField(blank=True, default=timedelta(minutes=0)) class Meta: verbose_name_plural = 'trials' def __str__(self): return str(self.id) Behavior Model RECORDING_CHOICES = ( ('Rate','RATE'), ('Duration','DURATION'), ('Frequency','FREQUENCY') ) class Behavior(models.Model): name = models.CharField(max_length=200) goal = models.CharField(max_length=200) recording = models.CharField(max_length=10, choices=RECORDING_CHOICES, null=False) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Active') def __str__(self): return self.name Trial Form class TrialForm(forms.ModelForm): class Meta: model = Trial fields = ('behavior_name','frequency_input', 'duration_input') Add Trial View def add_trial(request, clientsession_id): client_session = Client_Session.objects.get(id=clientsession_id) if request.method != 'POST': form = TrialForm() else: form = TrialForm(data=request.POST) if form.is_valid(): add_trial = form.save(commit=False) add_trial.client_session = client_session add_trial.save() return HttpResponse(status=204, headers={'HX-Trigger': 'trialupdated'}) context = {'client_session': client_session, 'form': form} return render(request, 'sessions/add_trial.html', context) -
Avoid hard coding template variables in django context dictionary
From the documentation, the context dictionary needs to have the same variable name as the template variable. Is there a way to avoid duplicating the variable names and hard coding them when creating the context dictionary? Example: Template : <h1>{{ title }}</h1> <h4> {{ date }}</h4> <p> {{ write_up }}</p> The keys in the context dictionary needs to have the same names as the template as follows: { 'title': 'some_value', 'date': 'some_date', 'write_up': 'some_other_value' } Is there a way to prevent hard coding the values in both places, or to share the values via a constants file? So that the template and context dictionary would look something like this. <h1>{{ CONST.title }}</h1> <h4> {{ CONST.date }}</h4> <p> {{ CONST.write_up }}</p> { CONST.title: 'some_value', CONST.date: 'some_date', CONST.write_up: 'some_other_value' } This way, we prevent duplicating the variable names. -
Css intellisense doesn't work after django extension
after i install django extension on VScode css intellisense stop works in .html but in .css it's fine this is .html and css intellisense doesnt' but in the .css all work fine how can i fix this problem? -
request.body not giving the desired json in django
i have started exploring api stuffs in django i want some JsonResponse in Django but i am not getting it views.py from django.shortcuts import render from django.http import JsonResponse import json # Create your views here. def api_home(request, *args, **kwargs): body = request.body print(body) data = {} try: data = json.loads(body) except: pass # print(data) data['headers'] = dict(request.headers) data['content_type'] = request.content_type return JsonResponse(data) Output in terminal b'' expected OUTPUT b'{"query":"Hello World!"}' Python file import requests endpoint = "http://127.0.0.1:8000/api" get_response = requests.get(endpoint, json={"query":"Hello World!"}) print(get_response.json()) Output of this file {'headers': {'Content-Length': '', 'Content-Type': 'text/plain', 'Host': '127.0.0.1:8000', 'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'content_type': 'text/plain'} Expected OUTPUT {'query':'Hello World!','headers': {'Content-Length': '', 'Content-Type': 'text/plain', 'Host':'127.0.0.1:8000', 'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip,deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'content_type': 'text/plain'} I am not getting that why i am getting different output here -
Group queryset by field
I am working with Django and Django REST framework. I have a model called Selection that contains field called category, when i query the model to send the result to the frontend i get it with the following structure: [ { "id": 1, "category": "SHOES", "products": 122, "created_at": "2021-09-11", }, { "id": 2, "category": "SHOES", "products": 4, "created_at": "2021-10-07", }, { "id": 3, "category": "CLOTHES", "products": 0, "created_at": "2021-10-08", }, ] I need to put the selections of the same category in an array and remove the grouped-by category, like this: { "SHOES": [ { "id": 1, "products": 122, "created_at": "2021-09-11", }, { "id": 2, "products": 4, "created_at": "2021-10-07", } ], "CLOTHES": [ { "id": 3, "category": "CLOTHES", "products": 0, "created_at": "2021-10-08", } ] } I considered to making it with Javascript in the frontend, but before i wanted to know if there's a way to do this from Django. -
Error: 'User' object has no attribute 'exists' on Heroku url, but works on local host url
So I am trying to request the logged in user, from the Heroku url, but gives me the error 'User' object has no attribute 'exists'. Whenever I try to do the exact same task, but on my local host url, I get the user and everything works perfectly. I think the issue roots from my database being out of synce, but I ran python3 manage.py makemigrations and migrate, but that didn't change anything. Also on a related note, when I try to sign into the admin with my super user, it works on the local host but not on Heroku. I know it's because it also doesn't think the superuser exist. I was going to change my Database, to mysqlite to postgresql, with the hopes of that fixing it, because that was already on the todo list for my full stack, but I want to figure out why this is happening before moving forward. If anyone could help that would be fantastic. -
nginx cannot find files in /home/ubuntu/
I don't understand why nginx cannot find files when the root is under home directory, e.g. /home/ubuntu/tabs. It will give 404 error. It works fine when the root is /var/www/tabs. server{ listen 80; #root /var/www/tabs; root /home/ubuntu/tabs; server_name 18.191.229.199; index main.html ; location / { try_files $uri $uri/ =404; } location /folder { try_files /folder/main1.html /folder/main2.html =404; } } -
how to save foreign key from django html template
I want to save data from html template select field in django. html example code: <label for="type" style="color:red;">Short Name *</label> <input type="text" name="short_name" class="form-control" required placeholder=""> <br> <br> <select style='bakground-color:red' name="category" required class="form-control show-tick"> <option value="" selected="selected">---------</option> {% for cat in category %} <option value="{{ cat }}">{{ cat }}</option> {% endfor %} </select> Django code: Views.py def addBooks(request): template = 'admin_panel/add_books.html' category = Category.objects.all() book_details = BookDetails.objects.all() context = { "page_title": "Add Book", "category": category, "book_details" :book_details, } if request.method == "POST": short_name = request.POST.get('short_name', None) category = request.POST.get('category',None) book_details = BookDetails.objects.create(short_name=short_name, category=category) return render(request, template,context) models.py class BookDetails(models.Model): id = models.AutoField(primary_key=True) short_name = models.CharField(max_length=50, unique=True, db_index=True) category = models.ForeignKey( Category, on_delete=models.CASCADE ) Error Showing: ValueError at /superadmin/add_books/ Cannot assign "'Story'": "BookDetails.category" must be a "Category" instance. How to solve this problem? -
Accessing dataclass properties by name in Django template
In Django, I have created a dataclass to help me move data around in a standardized way: # models.py class Person(models.Model): name = CharField(max_length=50) #utils.py @dataclass class Performance: person: Person last_year: int five_years: int The idea here is that I can access the properties by name when transferring them to the template: #views.py class IndexView(View): def get(self, request): persons = Person.objects.filter(name="pam") perfs_array = [] for person in persons: p = Performance() p.last_year = #some math p.five_years = #more math perfs_array.append(p) context = {"perfs": perfs_array} return render(...) The goal is to be able to do this: <!--index.html--> {% for perf in perfs %} <h1>{{ perf.person.name }}</h1> <p>last year's performance: {{ p.last_year }}</p> {% endfor %} However, I can only access the data using numbered indices: <!--index.html--> {% for perf in perfs %} <h1>{{ perf.0.name }}</h1> <p>last year's performance: {{ p.1 }}</p> {% endfor %} This made it very hard to write correct code and to debug the templates when things go inevitably south. Is there a way to access the data with named indices? Thanks! -
serializer showing name of model
I want to serialize data from nested queryset: I have working code but output from serializer showing too many data. I want hide this for security reason. example output: (...) "gallery": "[{"model": "mainapp.imagesforgallery", "pk": 1, "fields": {"user": 1, "image": "uploads/2022/8/6/drw/Adapta-KDE-theme_JOgL4kO.webp", "thumbnail": ""}}]" (...) this is models.py class ImagesForGallery(models.Model): user = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return 'User: {} || Image: {}'.format(self.user, self.image) class Gallery(models.Model): project = models.ForeignKey(Projects, null=True, blank=True, on_delete=models.CASCADE) project_gallery = models.ManyToManyField(ImagesForGallery, blank=True, related_name='project_gallery') def __str__(self): return '{}'.format(self.project) This is my view class HomeView(viewsets.ModelViewSet): serializer_class = ProjSerializer queryset = Proj.objects.all() def list(self, request, *args, **kwargs): response = super(HomeView, self).list(request, args, kwargs) gal = Gallery.objects.all() for d in response.data: for g in gal: if d['uuid'] == str(g.project.uuid): qs = g.project_gallery.get_queryset() serialized_obj = serializers.serialize('json', qs) d['gallery'] = serialized_obj return response This code compares the project model to the photo gallery model. If uuid is correct, include this gallery in the project and send json. I'm not sure the code is efficient and safe. The question is how to modify the code so that it does not show the model name. -
Using Below Code i m able to find states present in a country, is There any method to find cities within the given states using python
Using this code i am able to find states of country i want to find all cities within given state, suppose i enter the state name i get all cities within that state from countryinfo import CountryInfo name = "India" country = CountryInfo(name) data = country.info() print(data["provinces"])