Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why aren't my messages showing up in HTML using Django?
For some reason I'm not getting any error messages showing up when the bid is too low. Anyone see why? views.py: def bid(request, username): price = request.POST.get("price") itemID = request.POST.get("itemID") newBid = request.POST.get("newBid") title = request.POST.get("title") query = Bid.objects.filter(itemID = itemID).first() if(newBid > price): query2 = NewPost.objects.filter(title = title).update(price = newBid) new = Bid.objects.create(itemID = itemID, newBid = newBid, highestBidder = username) new.save() return render(request, "auctions/index.html") else: messages.add_message(request, messages.INFO, 'Bid Too Low') return render(request, "auctions/index.html", { "messages": messages }) index.html: {% for message in messages %} <li>{{ message }}</li> {% endfor %} -
Django middleware - get view_args
I'm implementing a new middleware using a standard implementation: def my_middleware(get_response): def middleware(request): return get_response(request) return middleware I want to get the view_args. I can change to a class-based middleware and implement the method process_view(request, view_func, view_args, view_kwargs) Is there any other way to get these view_args, view_kwargs in my middleware without changing to class-based middleware? -
jQuery form submit not triggering
I have 2 forms in my html file(Not nested). Each do their own thing in terms of their input fields and do not rely on each other. The problem i'm currently facing is that $(form).submit((event)=>{code}) only works on: <form id="mainForm" action='' method="POST" enctype="multipart/form-data"> {% csrf_token %} <!--Cover image--> <ul class="error" id="coverImageLink_errors"></ul> <div class="cover-img"> {{ mainForm.coverImageLink|add_class:'actual-img' }} <img src="#" id="cover" alt="Your image" style="color: black;"> </div> <!--Music data part--> <div class="music-data"> <ul class="error" id="albumName_errors"></ul> <label for="{ mainForm.albumName.id_for_label }">title</label><br> {{ mainForm.albumName }} <br><br> </div> <input id='albumSubmit' type="submit" value="Next" class="main-form-upload"> </form> <script> $('#mainForm').submit((event)=>{ event.preventDefault(); console.log('AJAX CALLED FOR MAIN FORM'); }); </script> But not on: <form id="AdvancedForm" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <ul class="last-step-error" id="advancedForm.non_field_errors"></ul> <section id="main-section"> <!-- compresso page --> <div id="compresso-page"> <div class="parent"> <div class="name">0. Hello world</div> <ul class="pre-errors"> <li>Video file is not supported</li> <li>+2 more</li> </ul> </div> </div> </section> <div style="height: 20px;"></div> <!-- prevents collision with button --> <input type="submit" value="Release" onclick="alert('Advanced form submit pressed')"> </form> <script> $('#AdvancedForm').submit((event)=>{ event.preventDefault(); console.log('AJAX CALLED FOR ADVANCED FORM') const url = '{% url "validate-upload-collection" %}' }) </script> I see AJAX CALLED FOR MAIN FORM but not AJAX CALLED FOR ADVANCED FORM If you are confused with {{ something }}, it's just some django(Web framework) variable … -
Does the order of import modules important in django?
I just need to know, either it is important or not? For example in models.py we usually import modules and libraries like reverse or get_user_model; This kinds of importing will grow larger in views.py as we all know. So my question is concerning to the order of these importing, whether is is important or not? -
Service to send email with Django
I'm trying to create a service for send e-mail if the expiration_datetime its less then a week. What i want to do is send just once and not repeat. i'm not sure what should i do Models: class License(models.Model): PACKAGE_CHOISES = ( ('Production', 'Production'), ('Evaluation', 'Evaluation'), ) LICENSE_CHOISES = ( ('js', 'Javascript_sdk'), ('ios', 'Ios_sdk'), ('android', 'Android_sdk'), ) client = models.ForeignKey('Client', on_delete=models.CASCADE) package = models.CharField(max_length=15, choices=PACKAGE_CHOISES, blank=True, null=True) license_type = models.CharField(max_length=15, choices=LICENSE_CHOISES, blank=True, null=True) created_datetime = models.DateTimeField(auto_now=True) expiration_datetime = models.DateTimeField(default=get_default_license_expiration) And here is the service i'm trying to build: def process_licenses(): client = Client.objects.all() licesens = License.objects.all() clients_name = [] hoje = datetime.today() - timedelta(days=7) for date in licesens: if hoje >= date.expiration_datetime: clients_name.append(date.client) for name in clients_name: if name in client: email = EmailMessage( 'Test', 'hi', settings.EMAIL_HOST_USER, [name.admin_poc], ) email.fail_silently=False email.send() time.sleep(30) -
Predict API in Django
I have a Tensorflow model which I saved using TensorFlow serving. I now wish to retrieve results from the database and make predictions using API in DJANGO. The model is callable from UBUNTU using curl and gives correct predictions: curl -d '{"instances": [[ 1.18730158, -0.70909592, 1.21082918, -0.15897608, -0.87693017], [-0.36190136, 0.14893573, 0.40094705, 0.09658912, 1.13982729]]}' -X POST http://localhost:8501/v1/models/model:predict Results: { "predictions": [[0.111961663], [-0.0357596762]] ] } I have tried to call the API from DJANGO. For this my views.py file looks like this: normed_data = normed_data.to_dict() # normed_data is a dataframe with header values as well response = normed_data.get('http://localhost:8501/v1/models/model:predict') context = { 'df2' : response } return render(request, "view.html", context) But the result is None Any help in pointing my errors out would be really wonderful. Thanks -
Openging a Django File with Pandas
This may have been asked before...however, I believe there may be a few gotchas or caveats someone may be able to add to for my particular use case. I have the following snippet: file = default_storage.open(instance.file.path).read() dataframe = pd.read_csv(?, delimiter=',') How best would I go about determining '?' in the above from potentially the file object or instance.file.path? Caveat: I believe I need to use the default_storage.open method as I'm using the django-storages backend to store files external to the application server... -
How can I get an option selected by default in a forms.ChoiceField in Django?
I have something like this: class MyForm(forms.Form): CHOICES = ( ('opt1', 'Opt1'), ('group',( ('opt2', 'Opt2'), ('opt3', 'Opt3'), ) ), ) myfield = forms.ChoiceField(choices=CHOICES, required=False) when i render this form, opt1 is selected by default, But I need opt3 to be the selected one. i tried something like: myfield = forms.ChoiceField(choices=CHOICES, required=False, initial="opt3") but it didnt work. what i get: <select name="myfield" id="id_myfield"> <option value="opt1">Opt1</option> <optgroup label="group"> <option value="opt2">Opt2</option> <option value="opt3">Opt3</option> </optgroup> </select> what im trying to get: <select name="myfield" id="id_myfield"> <option value="opt1">Opt1</option> <optgroup label="group"> <option value="opt2">Opt2</option> <option value="opt3" selected>Opt3</option> </optgroup> </select> How can i get opt3 selected by default? -
Django e-mail errors silenced even with fail_silently=False
I've been trying to capture any exception raised while sending e-mails, but even explicitly using fail_silently=False doesn't do the trick. I'll explain my use-case in detail below. I'm using Django 2.2.16 (upgrading to 3 is not an option for the moment, because of some external libraries). Python 3.8. The code sending e-mails is as follows (it comes from a class extending EmailMultiAlternatives): try: logger = logging.getLogger(__name__) logger.info("Timeout: %i", settings.EMAIL_TIMEOUT) # Ignore fail_silently and always show errors count_sent = super().send(fail_silently=False) logger.info("Mail sent: %i.", count_sent) return count_sent except (smtplib.SMTPException, socket.error, Exception): logger = logging.getLogger(__name__) logger.exception("An error occured while trying to send an e-mail.") return 0 If I, for e.g., explicitly configure a wrong host name or username for the SMTP server, the code above won't capture such exceptions (e.g. a socket error in the first example, an authentication error in the second). The logged information will be: Timeout: 10 Mail sent: 0. Note: The class doesn't modify any connection method from the parent class. The code above appears in the send method of my custom class. If I replace the line calling send and use: try: logger = logging.getLogger(__name__) logger.info("Timeout: %i", settings.EMAIL_TIMEOUT) from django.core.mail import get_connection conn = get_connection(fail_silently=False) count_sent = conn.send_messages([self]) … -
Django Pagination with data needing call external API
I ran into a problem where my page was taking a long time to load because I need to make lots of external calls to a third party API. I found out about Django pagination, but wanted to know how to do pagination when I need to make an external call to get the data first before passing it onto the template. This is how I am currently loading that data: events = Event.objects.filter(contact=contact).order_by('created_at') events_list = [] for event in events: event_json = model_to_dict(event) if event.event_type in [EventType.EMAIL_INCOMING, EventType.EMAIL_OUTGOING]: event_json['message'] = call_external_api_to_get_message(event.message.id) elif event.event_type == EventType.NOTE_CREATED: event_json['note'] = event.note.text events_list.append(event_json) context = { "events": events_list } With pagination, how would I make the external API call before passing on the paginated list? -
How to get value for each element in model?
I have quite easy thing to do, but I've been wondering how to do this for a quite some time. In my database I have models like this: class Model1(models.Model): name = models.CharField(max_length=50, unique=True) ... class Model2(models.Model): model1_lst = models.ManyToManyField(Model1) ... And now in my view I would like to do the form, where I can get an integer value for each model1 element in model1_lst, something like this: Can you help me and gice a hint how to achieve it please? -
ModuleNotFoundError: No module named 'django_markdown2'
I'm currently doing Harvard Course about Web Programming. I need to convert my html page on website to markdown, so I installed into my conda virtual environment markdown2 and I added it to INSTALLED_APPS in settings.py. But I have a problem when I try to runserver or migrate i am getting an error ModuleNotFoundError. I tried to create another virtual environment but that doesn't work as well. Thank you in advance. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\petrk\anaconda3\envs\henv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\petrk\anaconda3\envs\henv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\petrk\anaconda3\envs\henv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\petrk\anaconda3\envs\henv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\petrk\anaconda3\envs\henv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\petrk\anaconda3\envs\henv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_markdown2' -
get foreign key queryset django
i need to access my OderItem in model in reference with customer here is my model.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(null=True) class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=False) date_ordered = models.DateField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=False) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=False) quantity = models.IntegerField(default=0, null=True, blank=False) date_added = models.DateField(auto_now_add=True) here is my views.py def customers(request, pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() context={'customer':customer, 'orders': orders} return render(request, 'crm/customers.html', context) here i can only access my Order using "orders = customer.order_set.all()" how i can access my OrderItem in same manner i tried following method and failed def customers(request, pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() items = orders.orderitem_set.all() context={'customer':customer, 'orders': orders} return render(request, 'crm/customers.html', context) i am getting following error AttributeError at /dashboard/customers/1 'QuerySet' object has no attribute 'orderitem_set' Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/customers/1 Django Version: 3.1.1 Exception … -
prevent bootstrap modal from closing when submitting django signin form when email or password is incorrect
In my django website i have the signin and the signup forms in a bootstrap modal but bootstrap modals are made that when u submit it automatically closes i want to prevent that when the user enters a wrong email or password NB: i'm using Vuejs as a frontend framework in my views.py def home(request): user = request.user # for creating posts form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): obj = form.save(commit=False) author = User.objects.filter(email=user.email).first() obj.author = author form.save() form = TextForm() texts = Text.objects.all().order_by('-id') # for signing in if request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) else: messages.info(request, 'Email or password is incorrect') else: signin_form = SigninForm() context = {'signin_form':signin_form,'form': form, 'texts': texts} return render(request, 'main/home.html', context) the modal template <!-- The Modal --> <div class="modal fade " id="joinus"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content custom"> <!-- Modal body --> <div class="modal-body"> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item w-50"> <a class="nav-link active btn btn-outline-success p-3 " data-toggle="tab" href="#signin">Sign in</a> </li> <li class="nav-item w-50"> <a class="nav-link btn btn-outline-success p-3" data-toggle="tab" href="#signup">Sign up</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div id="signin" … -
how to print data using javascript fron the json?
function sent(){ const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; console.log(recipients); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body}) }) .then(response => response.json()) .then(result => { const b = result.body; document.querySelector('#sentmsg').innerHTML = b; load_mailbox('sent'); }) return false; } can anybody tell me how to print the body part of json string? I am getting undefined on the page. instead of the body message i passed through the form. -
Auto-populate django model field with value if None
I'm attempting to auto-populate my Comment model's commenter field when not filled out with a string value consisting of "Anon" and the comments primary key(should be autogenerated in django I believe). I'm attempting to do so by overriding the save() function. This is my code for the model. from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField from imagekit.models import ProcessedImageField, ImageSpecField from imagekit.processors import ResizeToFill # Create your models here. STATUS = ( (0, "Draft"), (1, "Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) cover_image = ProcessedImageField(upload_to='images/%Y/%m/%d/', blank=True, null=True, processors=[ResizeToFill(250, 250)], format='JPEG', options={'quality': 90}) author = models.ForeignKey(User, on_delete= models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = RichTextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") created_on = models.DateTimeField(auto_now_add=True) commenter = models.CharField(max_length=20, blank=True, help_text="Fill this out, or don't") comment_content = models.TextField(max_length=300) active = models.BooleanField(default=False) class Meta: ordering = ['-created_on'] def __str__(self): return f"Comment by {self.commenter} on {self.post}" def save(self, *args, **kwargs): if self.commenter == None: self.commenter = "Anon" + str(self.pk) return self.commenter else: super().save(*args, **kwargs) As seen in the code I'm attempting to populate the commenter field with the … -
Stop caching in Django
I am using Django with Bootstrap 4 in project with my own custom css for design. Every time when I make new design change in css file I have to clear my browser cache and reload the page to view changes or if I rename the custom css file then my design changes are visible. Is there any way I can disable caching just for development and I can enable while it is in live environment. I am new to this and Django is huge. Please share what is best practice to do this. -
Django: Template does not exist at...error
I am trying to complete an encyclopedia project that allows a user to click on an entry on the homepage that directs them to the entry page. However, I am constantly getting the following error: TemplateDoesNotExist at /wiki/CSS/ CSS Request Method: GET Request URL: http://127.0.0.1:8000/wiki/CSS/ Django Version: 3.1.1 Exception Type: TemplateDoesNotExist However, when I manually enter the URL: http://127.0.0.1:8000/wiki/CSS/ the page seems to load fine although it is not displaying anything but at least no error message. The problem I am having is I am trying to render the HTML pages from Markdown templates but the folder the templates are in is not labelled 'templates' it is labelled 'entries'. So I'm guessing when I click on the link from the homepage, Django looks for a templates directory but is not able to find any matching filename so is thrown off? I've tried renaming the folder 'templates' but that just throws everything off. I've tried going into settings.py and adding 'entries' under [INSTALLED_APPS] and under TEMPLATES as 'DIRS': [os.path.join(BASE_DIR, 'entires')] but nothing is working! Could it be something to do with the fact that they are .md files and not .html? I have installed markdown2 already. -
How to access Select Options from Django Template Language
In my code, I have a dropdown menu of states. I want to make it so that when the user chooses one of the states in the drop down menu, without submitting, the code switches the second field (counties) to only the counties in that state. I have a state/county list, but I cannot find a way to access the currently selected option from template language without submitting. var curr_state = document.getElementById('state').value; var county_select = document.getElementById('county'); while (county_select.options.length > 0) { selectBox.remove(0); } var val = {{form.state.value}}; {% for c in counties_per_state.val %} var newOption = new Option({{c.name}},{{c.id}}); {% endfor %} -
i want to update only one field in django using model Forms
*views.py * def update_order(request,pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == 'POST': form = OrderForm(request.POST,instance=order) if form.is_valid(): form.save() return redirect('admin') *midels,py* class Order(models.Model): STATUS = ( ('Return', 'Return'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ('new order', 'new order'), ('hold', 'hold'), ) order_id= models.CharField(max_length=120, blank= True) user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True , choices=STATUS, default='new order',blank=True) note = models.CharField(max_length=1000, null=True,blank=True) receiver_name= models.CharField(max_length=100) receiver_address= models.CharField(max_length=200) receiver_phone = models.CharField(max_length=50) order_number = models.CharField(max_length=50) condition= models.IntegerField(blank=True,default=0,null=True) order_date1 = models.DateField(auto_now_add=True,null=True) delivery_cost = models.IntegerField(default=60,null=True,blank=True) html page {{form.status}} *i have tried {{form.status}} this but it not working but if i user all {{form}} is showing me the all fields and its working but i don't want to show all fields in html page * -
Best way to send item indices to the server?
I have a list of items and their IDs. I want to send this list to the server. How to do it more correctly and better? They are whole numbers. I have an option, but I don't think it is correct: site.com / someaction / 1,2,3,4,5,6 Which is more correct? -
Django AWS S3 Signature Does Not Match
I just set up django-storages and boto3 to have some media files served for my django app. I currently cannot view any images from my s3 bucket or upload them to my bucket via admin. I am getting a Signature does not match error. I don't have any special characters in my access/secret key so I'm at a loss as to why I'm receiving this error. I've tried custom domain, changing the signature version, neither of them worked. I have my bucket set to block public access(turning this off didn't work either) and I included the bucket policy from django-storages. settings.py AWS_ACCESS_KEY_ID=config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY =config('AWS_ACCESS_KEY_ID') AWS_STORAGE_BUCKET_NAME=config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'us-east-2' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_DEFAULT_ACL = None Error recieved <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>(My Access Key)</AWSAccessKeyId> <StringToSign>AWS4-HMAC-SHA256 20200917T150735Z 20200917/us-east-2/s3/aws4_request 074a1a316ba0fae02469760556a2f0bbc5d30d4fdddfefbd7a66279f85d9eaf2</StringToSign> <SignatureProvided>e0f12a24e0935ec8b0d6a3be2513a40f557a6a9b643f286877e13663f165468a</SignatureProvided> <StringToSignBytes>41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 32 30 30 39 31 37 54 31 35 30 37 33 35 5a 0a 32 30 32 30 30 39 31 37 2f 75 73 2d 65 61 73 74 2d 32 2f 73 33 2f … -
how can i update two forms relation values in django?
i want to generate patient report! patient has many vitals. i want to update patient status and patient vitals result_values attributes which is relational with patient. i am getting this error 'ManyRelatedManager' object has no attribute '_meta' when i click on this url path('genrate/<int:pk>/', patient_report_generate, name='genrate-report'), class Patient(models.Model): name = models.CharField(max_length=50) father = models.CharField(max_length=50) age = models.CharField(max_length=2) vitals = models.ManyToManyField(Vital) doctor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) created_date = models.DateField(auto_now_add=True) status = models.BooleanField(default=False) class Vital(models.Model): name = models.CharField(max_length=100, help_text='Test name') result_values = models.CharField(max_length=10, blank=True) expected_values = models.CharField(max_length=20, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) forms.py from vital.models import Vital from patient.models import Patient class PatientReportForm(forms.ModelForm): class Meta: model = Patient fields = [ 'status', ] class VitalReportForm(forms.ModelForm): class Meta: model = Vital fields = [ 'result_values' ] views.py def patient_report_generate(request, pk): patient = get_object_or_404(Patient, pk=pk) if request.method == 'POST': p_form = PatientReportForm(request.POST, instance=patient) v_form = VitalReportForm(request.POST, instance=patient.vitals) if p_form.is_valid() and v_form.is_valid(): p_form.save() v_form.save() return redirect('dashboard') else: p_form = PatientReportForm(instance=patient) v_form = VitalReportForm(instance=patient.vitals) context = { 'p_form': p_form, 'v_form': v_form } return render(request, 'report.html', context) -
Trying to do a particular grouping in Django
So let's say I have a model, Fruit, with some fields: class Fruit(): color: models.CharField(blank=True, null=True, default='', max_length='250') sweet: models.BooleanField(default=False) date_dropped_from_tree: models.DateField(blank=True, null=True) baking: models.BooleanField(default=False) I want to take my fruit queryset: class FruitViewSet(viewsets.ModelViewSet): queryset= Fruit.objects.all() serializer_class = FruitSerializer def get_queryset(self): self.queryset = self.queryset.filter(sweet=F('sweet'), date_dropped_from_tree=F('date_dropped_from_tree'), baking=F('baking')).values('sweet', 'date_dropped_from_tree', 'baking').annotate(count=Count('sweet', 'date_dropped_from_tree', 'baking')) return self.queryset I want this to return a list something like: [{ sweet: True, date_dropped_from_tree: '10-25-18', baking: False, count=5}, { sweet: False, date_dropped_from_tree: '10-16-15', baking: True, count=3}, ... ] Looking as I write it out, I realize my code is a bit off base, but I can't quite conceive of how to return results like I want. Assistance appreciated. -
Storing files in a Django Rest Framework API
I am building a Web API with Django Rest Framework in the backend and PostgreSQL as a DB. I also want to store Documents (mostly PDFs and JPGs), which Users will upload to the system. I was thinking storing the files using the Django File Storage (MEDIA folder) so in the same server as the API. Do you think that will be OK for a number of files which I think might be in the range of 1000 - 10,000 files (each 1 - 10 MB) so let's say 100 GB at max.