Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing generic pandas dataframe to django REST API
I am currently building a REST API with the django and djangorestframework libraries. I want to make a POST that accepts a JSON-ified version of a pandas dataframe, so that I can then call some other library function on the dataframe and return some output. I know that if I know the table structure of the dataframe, there are nice libraries like django-rest-pandas that can serialize and return pandas dataframes as JSON, but I am not sure about how to accept them as parameters to a function. My current thought was to pass the JSON as a string to a function-based view, and from there, extract and parse the JSON as a pandas dataframe. However, I don't know if this is the best way to do this. My biggest complication is that I don't know the structure of the dataframe beforehand, so I am not sure how to incorporate that into a model that perhaps some library is able to interpret (although I am still interested in a way to do this if I did know the structure). Here is my code so far. Sample POST request: { "table": "{\"AAPL\":{\"1420156800000\":103.8639572404,\"1420416000000\":100.9379443592,\"1420502400000\":100.947444401,\"1420588800000\":102.3629506325,\"1420675200000\":106.2959679468},\"AMZN\":{\"1420156800000\":308.52,\"1420416000000\":302.19,\"1420502400000\":295.29,\"1420588800000\":298.42,\"1420675200000\":300.46},\"FB\":{\"1420156800000\":78.45,\"1420416000000\":77.19,\"1420502400000\":76.15,\"1420588800000\":76.15,\"1420675200000\":78.175},\"GOOG\":{\"1420156800000\":524.81,\"1420416000000\":513.87,\"1420502400000\":501.96,\"1420588800000\":501.1,\"1420675200000\":502.68},\"MSFT\":{\"1420156800000\":43.3443122802,\"1420416000000\":42.9410878182,\"1420502400000\":42.3153946875,\"1420588800000\":42.8530273035,\"1420675200000\":44.1136830927}}", "num_samples": 10 } models.py: class EFObject(models.Model): table = models.TextField() num_samples … -
Django keeps throwing 404 errors for static files
Before I begin, let me say that I have read and tried all the other solutions, but none have worked. I am trying to get a Django site running (if any are interested, here is the source code.), and I have everything set up, but the console keeps throwing 404 errors at me for the static files. Here is the console output: output I am running it on a DigitalOcean droplet, and here is the URL. -
Django display specific values for username in form
First of all my apologies for mistakes in my English. I have two models and two forms in which user can create a personal project names and tasks. After the user logs in, he/she can create Tasks and I want to display in field 'project' from TaskForm only projects which were created by this User. By default it displays all Project which were created by all users. models.py class Project(models.Model): title = models.CharField(max_length = 150) color = models.CharField(max_length = 20) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, related_name = 'user', blank = True) def __str__(self): return self.title class Task(models.Model): project = models.ForeignKey(Project, on_delete = models.CASCADE, related_name = 'project') title = models.CharField(max_length = 150) def __str__(self): return f'{self.title}' views.py class TaskCreateView(LoginRequiredMixin, View): def get(self, request): form = Task.form return render(request, 'task/create.html', context = {'form':form}) def post(self, request): form = TagForm(request.POST of None) # form = TagForm(request.POST of None, user = request.user) if form.is_valid(): new_task = bound_form.save() return redirect('/task/') return render(request, 'task/create.html', context = {'form':form}) forms.py class TaskForm(forms.ModelForm): def __init__(self, *args, **kwargs): # user = kwargs.pop('user','') super(TaskForm, self).__init__(*args, **kwargs) # self.fields['project'] = forms.ModelChoiceField(queryset=Project.objects.filter(user = user)) self.fields['project'].queryset = Project.objects.all() self.fields['project'].label = '' self.fields['priority'].label = '' title = forms.CharField(label = '', widget = forms.TextInput(attrs = … -
supervisor gunicorn HUP signal does not reload properly
I am running my django server with gunicorn and supervisor. Here is my supervisor conf, [program:api] process_name=api command=command-to-run user=api directory=/opt/api/api redirect_stderr=true stderr_logfile=/var/log/api/stderr.log stdout_logfile=/var/log/api/stdout.log autostart=true autorestart=true logfile_maxbytes = 50MB logfile_backups = 10 stopsignal=HUP When I run sudo supervisorctl, :/var/log/consumer_api$ sudo supervisorctl api RUNNING pid 1674, uptime 3:13:29 > Here are the gunicorn logs when I restart my api application in supervisor, sudo supervisorctl restart api [2019-02-14 16:09:02 +0000] [25740] [INFO] Handling signal: hup [2019-02-14 16:09:02 +0000] [25740] [INFO] Hang up: Master [2019-02-14 16:09:02 +0000] [1593] [INFO] Booting worker with pid: 1593 [2019-02-14 16:09:02 +0000] [1594] [INFO] Booting worker with pid: 1594 [2019-02-14 16:09:02 +0000] [1597] [INFO] Booting worker with pid: 1597 [2019-02-14 16:09:02 +0000] [1595] [INFO] Booting worker with pid: 1595 [2019-02-14 16:09:02 +0000] [1596] [INFO] Booting worker with pid: 1596 [2019-02-14 16:09:02 +0000] [1598] [INFO] Booting worker with pid: 1598 [2019-02-14 21:39:02 +0530] [25756] [INFO] Worker exiting (pid: 25756) [2019-02-14 21:39:02 +0530] [25758] [INFO] Worker exiting (pid: 25758) [2019-02-14 21:39:02 +0530] [25759] [INFO] Worker exiting (pid: 25759) [2019-02-14 21:39:02 +0530] [25760] [INFO] Worker exiting (pid: 25760) [2019-02-14 21:39:02 +0530] [25769] [INFO] Worker exiting (pid: 25769) [2019-02-14 21:39:02 +0530] [25773] [INFO] Worker exiting (pid: 25773) [2019-02-14 21:39:02 +0530] [7029] [INFO] Worker … -
How do I refresh static datatables?
Please don't mark as duplicate. I have gone through several SO questions and DT docs before posting here. I'm using django for my serverside and I need to refresh datatables with new products when the user clicks a radio button. I'm already initializing datatables on page load and waiting for the user to click the radio button. When the button is clicked, I make ajax call to my views.py to send a render_to_string of the table template and return a JSONResponse. The whole ajax thing works perfect, except, I can't reinitialize datatables. I've tried: 1..clear().destroy() and re initializing the table 2. empty() the tbody div and then repeating #1 3. .clear().draw() instead of destroy Neither of those worked. This is what I have: views.py def get_products(request): data = {} cat_name = request.GET.get('cat_name') brand_name = request.GET.get('brand_name') list_of_prods = Product.objects.filter(category__name=cat_name).filter(brandname=brand_name) data['html_products_table'] = render_to_string('templates/products/partials/products_table.html', {'list_of_prods': list_of_prods}) return (JsonResponse(data)) partials/products_table.html {% for product in list_of_prods %} <tr> <td><button class="btn btn-primary btn-circle" type="button"><i class="fa fa-plus"></i></button></td> <td>{{product.stock}}</td> <td>{{product.code}}<br><small>{{product.description}}</small></td> <td>{{product.price}} <br><small>{{product.manufacturer}}</small></td> </tr> {% endfor %} products_home.html <div class="table-responsive"> <table class="table table-striped table-bordered table-hover" id="products_table" cellspacing="0" width="100%"> <thead style="display: none"> <tr> <th>Add Button</th> <th>Stock count</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody class=""> {% comment %} {% include 'templates/products/partials/products_table.html' %} … -
Display Choices Dictonary in Template [duplicate]
This question already has an answer here: Django templates: verbose version of a choice 7 answers i trying the Choices Example from the Django Site to access and use choices. https://docs.djangoproject.com/en/2.1/ref/models/fields/#choices models.py from django.db import models class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) def is_upperclass(self): return self.year_in_school in (self.JUNIOR, self.SENIOR) So far everything is displayed in my template for instance "JR" or "SR". But how can access the Dictonary or "Junior" / "Senior"? When i try to access the Choices in my Template via {{ Student.year_in_school }} it only shows "JR" or "SR". Do i have do make to make some adjustments in my view to re-interpreter "JR" to "Junior" and "SR" to "Senior"? Or are there some tricks do let make Django the magic in template {{ Student.year_in_school_Some Trick > }}? Thank You. -
How to put Django query filter in ON clause instead of WHERE clause?
In SQL, the placement of a condition, whether in the ON clause or the WHERE clause, can affect the results. filter() in Django seems to put conditions in the WHERE clause. Say I have these models: class Nations(models.Model): deleted = models.BooleanField(default=False) class People(models.Model): nation = models.ForeignKey(Nations, on_delete=models.CASCADE) deleted = models.BooleanField(default=False) And I want to find the nations with no people in them, I could do: SELECT nations.id, nations.deleted FROM nations LEFT JOIN people ON people.nation_id = nations.id WHERE people.id IS NULL; But let's say people can be soft deleted, and I want to find nations with no undeleted people in them. I would do: SELECT nations.id, nations.deleted FROM nations LEFT JOIN people ON people.nation_id = nations.id AND people.deleted IS FALSE WHERE people.id IS NULL; However, in Django, if I do: Nations.objects.filter(people__id__isnull=True, people__deleted=False) This is equaivalent to the query: SELECT nations.id, nations.deleted FROM nations LEFT JOIN people ON people.nation_id = nations.id WHERE people.id IS NULL AND people.deleted IS FALSE; Unlike the desired query, this will not include nations that have deleted people only! How can I get Django to move the soft delete check into the ON clause? -
Django template. API request causes page to navigate to query url
I have a django template that includes a button: <button type="submit" class="btn btn-primary" onclick="getRota()">Make Rota</button> The getRota() function is defined below, in a script: <script> function getRota() { var startDate = $("input[name='rota_start']").val(); var endDate = $("input[name='rota_end']").val(); fetch(`{{ rota_url }}start=${startDate}&end=${endDate}`, { method: "GET", headers: { "X-CSRFToken": getCookie("csrftoken"), Accept: "application/json", "Content-Type": "application/json" } }) .then(response => response.json()) .then(data => { $("#rota_form").append(`<a href=${data.url} target="_blank">Text Rota</a>`); }); } </script> The weird bit, is that pressing the button causes the page to make the API request, append the link (all good so far), and then shortly afterwards, navigate to the URL of the original page (not the api), with the start=${startDate}&end=${endDate} (from the api url) appended to it... I really don't even know where to start with this one... -
Django csrf token is modifying expected output and causing unit test to fail
I'm currently going through Harry Percival's Test Driven Development with Python and am having an issue with a response as soon as I add the {% csrf_token %} to my html template. As this is test driven development, there are a couple of unit tests that are failing. When I remove the {% csrf_token %} I get a passing test. When it exists in the code it modifies the response to include an unexpected line <input type="hidden" name="csrfmiddlewaretoken" value="WaPf57..."> which appears below the original line " <body> <h1>Your To-Do List</h1> <form method="POST"> <input name="item_text" id="id_new_item" placeholder="Enter a to-do item" /> {% csrf_token %} </form> <table id="id_list_table"> <tr><td>{{ new_item_text }}</td></tr> </table> </body> In the unit test below, I have printed out to my console the actual and expected and I received another line with the csrfmiddleware token. def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string('home.html') print('response: ', response.content.decode()) print('expected: ', expected_html) self.assertEqual(response.content.decode(), expected_html) Is there a way to remove that from the response or should I modify the test so that it includes all of the expected HTML and ignores the "hidden" csrfmiddlewaretoken? -
I can't display posts only with a boolean field set to true in my template
In short - I have a bootstrap carousel and it works nicely, however I can't get it to display only fields with 'featured' set to 'true' I have tried doing for post in posts.objects.featured (the carousel literally does not show up at all then) and variations like posts.objects.filter(featured=True) (it says it can't parse the remainder). Here's the code from the template where I am trying to display the carousel image only with items with featured=True {% for post in posts.object.featured %} <div class="carousel-item {% if forloop.first %}active{% endif %} "> {% image post.image fill-1920x500 %} <div class="carousel-caption d-none d-md-block"> <h2 id="inner-carousel-title">{{post.title}}</h2> <h4><a href="{% pageurl post %}" style="color:white;text-shadow:2px 2px 4px #000000" >something</a></h4> </div> </div> {% endfor %} Again, I just want the carousel to show up only with featured posts As a side note- it'd be awesome if it only showed 3 posts. -
How to implement sets of preferences / flags for all fields in a Django model?
I have an Asset model with several dozen characteristics about an Asset: class Asset(models.Model): manufacturer = models.CharField(max_length=20) model = models.CharField(max_length=20) serial = models.CharField(max_length=20) ... For each field in the Asset model, I want to be able to add preferences. For instance, should the serial number be displayed to end users? Should serial number be included in barcodes? etc. I want to be able to store this information in a DRY manner, and be able to add additional sets of preferences in the future. I don't want to use bitfields, since they're not great for querying. Here are the two ways I've thought of to implement this. Option One is to user JSON field to store preference sets. For each preference name (e.g.: 'include_in_barcode' or 'include_in_reports'), the associated JSONField would have a dictionary of all the fields in the Asset model and the value of the preference for that field: class Preference(models.Model): name = models.Charfield(max_length=20) # e.g.: 'include_in_barcode' or 'include_in_reports' prefs = models.JSONField() # list each field in the 'model' model, along with preference for that field An example instance might look like: <name: 'include_in_barcode', prefs: '{"manufacturer": "True","model": "True","serial": "False"}'> This approach might even potentially be expanded to account for various … -
How to fix django model viewset with template error
I'm setting up django modelviewset(django rest framework) with simple html template. for this i wrote a class which include create, list, destroy method. as i am using simple html template to show the response of these request. for me create and list is working fine and i am able to show data on templates but when i am trying to show retrieve data, bot list and retrieve method are running. with the help of list method i am showing product list to template now i want to show particular product detail in a modal pop up on clicking the edit button in front of each product,when i am trying to do it, my website home page is displaying in modal instead of modal data(product detail). my code- class Inventory_ViewSet(viewsets.ModelViewSet): queryset = Inventory.objects.all() serializer_class = InventorySerializer renderer_classes = (TemplateHTMLRenderer,) template_name = 'login/dashboard.html' def create(self, request): try: print "in create" product_id = request.POST.get('productId') product_name = request.POST.get('productName') vendor = request.POST.get('vendor') mrp = request.POST.get('mrp') batchNum = request.POST.get('batchNum') batchDate = request.POST.get('batchDate') quantity = request.POST.get('quantity') vendor = Vendor.objects.get(vendor_name=vendor) inventoryObj=Inventory.objects.create( product_id=product_id,product_name=product_name, vendor=vendor, mrp=mrp,batch_num=batchNum,batch_date=batchDate, quantity_in_stock=quantity ) inventoryObj.save() return Response(status = status.HTTP_201_CREATED) except Exception as e: print e, "excepion" return Response(status=status.HTTP_400_BAD_REQUEST) def retrieve(self, request, pk=None): try: inventory_obj = Inventory.objects.get(id=pk) … -
How do I switch css file between templates?
Im trying to switch css files between my html templates. This is in my base_generic html file: {% block ccs %} <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> {% endblock %} And this is how I'm trying to overwrite it in my template: {% extends "base_generic.html" %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/detail.css' %}"> {% endblock %} I want it to load the detail.css file in my template but it loads the base.css on every page. I've tried different browsers (one with a completely empty cache) so it isn't a browser problem. What am I missing? -
How to redirect to a form after uploading a csv file if items don't exist in database?
I am having an issue that i have been trying to solve for a few days and feel like I have hit a roadblock and can't find the answers I need. What I am trying to do is: Upload a csv file (this file basically contains details about stock trades) which will be saved in a table and stored in media directory, the content is then parsed and passed to a dictionary (this step is working) -- the contents of this file will be used to update various tables in my database later. As I loop through the key, value pairs in the dictionary check to see if certain values exist in various models which are used as foreign keys (this part also works) -- So for example, if a trade is tagged with Fund X and fund X doesn't exist in my Fund table, it will take me to a form to fill in all the required fields to create fund X in my database If a value is missing I want to be sent to a form that will then allow me to create this value in the database so that I can populate the required fields (this … -
Django Save Wiping out New One to One Relationship?
I'm trying to save a one to one relationship in Django, but after I save the Address object, it deletes the relationship on the object that I'm trying to create a relationship to. In this case, I'm trying to create a relationship between a 'Person' object that already exists in my database and an 'Address' object that I'm creating. I can assign the Person's address attribute to the new address, and it shows up before the save. However, after the save of the person, the Person's address object disappears. I checked to make sure I have the right MySQL permissions in the settings file, and I can do everything i need to do to save a new object. In the database, there is a new address entry, but there is no address associated with the person entry in the Person table. What am I doing wrong? address = managerModels.Addresses() # create a new address address.zipCode = newAttributeValue # set up zip code person.address = address print("Address pre-save {}".format(tutor.address)) address.save() print("Address post-address save: {}".format(person.address)) person.save() print("Address post person-save: {} ".format(person.address)) The output on the terminal is Address pre-save None None None None 94536 Address post-address save: None None None None 94536 … -
Filter queryset not working in Django views.py
ProfileFilter allows a user to filter through other users by age, location, etc. It worked fine when it was a separate page with a unique URL with class FilterView(View)but I am having problems with it when trying to combine it with the main homepage. The filtering form is showing up and filtering as can be seen from the URL, (?interests__icontains=&age=&gender=M) but it is not rendering out the results. This is obviously because the ProfileFilter has been assigned to the variable f and the page is populated using a {% for user in users %} forloop. I need to assign f to users and have tried making a separate def filter function where I add context = {'users': f} but then the form doesn't show up on the page anymore. I'm a beginner so if there is something critical I am missing please inform me...many thanks as usual, I really appreciate it. views.py class ConnectView(View): template_name = 'connect/home.html' def get(self, request, *args, **kwargs): f = ProfileFilter(request.GET, queryset=Profile.objects.exclude(user=request.user)) context = { 'users': User.objects.exclude(username=request.user), 'filter': f, } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() return JsonResponse({'message': 'success'}) def location(request): if request.POST: radius_km = … -
Heroku - Set Procfile to run a Django Command to create DB
I'm deploying my DjangoApp to Heroku. I'm following all the documentation but not sure how to set the Procfile to run my command, as I do locally to create my shop_peru DB: This is what I do locally to create the Peru DB: python manage.py ubigeo_peru This is my Procfile: release: python manage.py makemigrations release: python manage.py migrate release: python manage.py ubigeo_peru web: gunicorn stickers_gallito.wsgi --log-file - ubigeo_peru.py: import pandas as pd import csv from shop.models import Peru from django.core.management.base import BaseCommand tmp_data=pd.read_csv('static/data/ubigeo-peru-2018-12-25.csv',sep=',', encoding="utf-8") class Command(BaseCommand): def handle(self, **options): products = [ Peru( departamento=row['departamento'], provincia=row['provincia'], distrito=row['distrito'], ) for idx, row in tmp_data.iterrows() ] Peru.objects.bulk_create(products) When deplying to heroku I get this error: (stickers_gallito_env) ogonzales@ogonzales:~/Desktop/web_proyects/stickers_gallito$ git push heroku master Counting objects: 3, done. Delta compression using up to 8 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 312 bytes | 312.00 KiB/s, done. Total 3 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.6.8 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: 167 static … -
Django LOGIN_REDIRECT_URL does not work with "next" request parameter
Django 1.11.3 The documentation about LOGIN_REDIRECT_URL says that: The URL where requests are redirected after login when the contrib.auth.login view gets no next parameter. I have LOGIN_REDIRECT_URL="some_url" in setting.py I see "next=" (no value, just the key) in the request url when I login, so I suspect that makes Django to ignore LOGIN_REDIRECT_URL and I end up on Admin default page. I use default login Django functionality, no custom template or anything. How do I get rid of "next=" in my request when I login (completely, no key) to see if LOGIN_REDIRECT_URL will be actually used (hopefully) ? -
How to upload file into wamp directory using django admin panel?
I'm developing a django-admin panel that requires to upload files to WAMP www directory . I have a mysql database and i have a django admin panel that successfully manages the database and uploading files . when i upload images with django admin panel , uploaded files goes to directory like this : http://127.0.0.1/media/pic.jpg i want to upload images to WAMP www directory using django-admin panel . How can i do this ? I SEARCHED ALOT BUT THERE WAS NO ANSWER FOR THIS QUESTION . Any suggestion will be helpfull . Thanks . -
Django: Giving validation error feedback on a form after a post redirect get
I have a good bit of experience in non-Django web development, but I am struggling to find a good practice for handling what to do when the user enters invalid data in their form and I want to re-display the form with their submitted data and the form errors displayed as well. I have a simple form with three fields and this is how I finally made it work. def get(self, request) : # Check if we have been redirected... redirect_html = request.session.pop('form_error_html', False) if redirect_html : return HttpResponse(redirect_html) old_data = {'title': 'SakaiCar', 'mileage' : 42, 'purchase_date': '2018-08-14' } form = BasicForm(initial=old_data) ctx = {'form' : form} return render(request, 'form.html', ctx) def post(self, request) : form = BasicForm(request.POST) if not form.is_valid() : ctx = {'form' : form} html = render_to_string('form.html', ctx, request=request) request.session['form_error_html'] = html return redirect(request.path) # Do something with the valid data.. return redirect('/') My template is really basic (I like this simplicity): <p> <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> </p> Now this approach kind of weirds me out because I am sending the entire rendered HTML page through the session from the post() to the get(). But I … -
tumblr "Grant this application access" implementation in angular 6 front end and django rest api
I have searched this question on different platforms but failed to get a sufficient answer. I am working on an where i made front end on angular 6 and backend on django rest framework (API). I have to do tumblr "Grant this application access" implementation in angular 6 front end and django rest api. I have gone through the api documentation of tumblr, they mentioned that use oAuth 1.0a. I do not know how it will be implemented in my case. if i use "app key/id" and "app secret" on front end in requests, will not it be visible to the user/client? I also want to store the details of the user details who have granted access to our app in database on backend (Django Rest frame work). -
Do something after object and all it's related objects are saved
There are Invoice and InvoiceItem classes in my project class Invoice(Model): ... pdf = FileField(... def save(...): super().save(...) self.generate_pdf() def generate_pdf(self): generate_pdf_from_self_and_invoiceitemset() save_pdf() class InvoiceItem(...): item = ForeignKey('Invoice'...) ... Simple - I want PDF file to be generated after invoice is created or modified. The problem is that this PDF depends not only on invoice but on it's invoice_items too. So as you can see, the generate_pdf() method after super().save() generates pdf BEFORE InvoiceItems are created or modified. I want it to call the method right after last InvoiceItem was saved (or if not modified, when Invoice was saved). How to do that? I can put generate_pdf() into InvoiceItem.save method too but it would be time and resource consuming to generate pdf multiple times after any save. I prefer to call method on model layer if possible so there is no chance somebody forget to put it inside new form or admin form. -
How to filter same column on each intermediate table in Django join
I'd like to join many tables and filter each one on the same column. My example is for checking for soft deletion, but I could imagine other applications, like filtering by a specific date. For example, if my models are: from django.db import models class Members(models.Model): name = models.CharField(max_length=255) deleted = models.BooleanField(default=False) class Purchases(models.Model): member = models.ForeignKey(Members, on_delete=models.CASCADE) item = models.ForeignKey('Items', on_delete=models.CASCADE) deleted = models.BooleanField(default=False) class Items(models.Model): company = models.ForeignKey('Companies', on_delete=models.CASCADE) deleted = models.BooleanField(default=False) class Companies(models.Model): deleted = models.BooleanField(default=False) Members make purchases, purchases contain items, items are made by companies. Say I want to count the number of unique companies a member has purchased from, but I want to check each table to see if it's deleted. I can do this: Members.objects.filter( deleted=True, purchases__deleted=True, purchases__item__deleted=True, purchases__item__companies__deleted=True ).annotate(num_companies=Count('purchases__item__companies', distinct=True)) But it seems silly to repeat the __deleted==True for every column. Is there a more efficient way filter the same column in the same way on each intermediate table in a large join? -
Django: How to Properly Use ManyToManyField with Factory Boy Factories & Serializers?
The Problem I am using a model class Event that contains a ManyToManyField to another model class, User (different events can have different users), with a factory class EventFactory (using the Factory Boy library) with a serializer EventSerializer. I believe I have followed the docs for factory-making and serializing, but am receiving the error: ValueError: "< Event: Test Event >" needs to have a value for field "id" before this many-to-many relationship can be used. I know that both model instances must be created in a ManyToMany before linking them, but I do not see where the adding is even happening! The Question Can someone clarify how to properly use a ManyToManyField using models, factory boy, and serializers in a way I am not doing now? The Set-Up Here is my code: models.py @python_2_unicode_compatible class Event(CommonInfoModel): users = models.ManyToManyField(User, blank=True, related_name='events') # other basic fields... factories.py class EventFactory(factory.django.DjangoModelFactory): class Meta: model = models.Event @factory.post_generation def users(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A list of users were passed in, use them # NOTE: This does not seem to be the problem. Setting a breakpoint # here, this part never even fires … -
Download file from POST request
I would like to download a file when user submits a button. It's a POST request. I don't overcome to return the HttpResponse in my code. This is my view : class ExportDownloadView(View): """ Create name authentification to download export file with expiration time """ template_name = 'export_download.html' def get(self, request, **kwargs): export_name = kwargs.pop('name', None) ExportFile.objects.get(name__iexact=export_name) if 'resp' in request.POST: resp = self.downloadFile(export_name) return resp context = { 'name': export_name } return render(request, self.template_name, context) def downloadFile(self, export_name): fs = FileSystemStorage() filename = export_name if fs.exists(filename): with fs.open(filename) as xls: response = HttpResponse(xls, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=' + export_name return response else: return HttpResponseNotFound(_('The requested xls file was not found in our server.')) And this is the HTML file : <form action="" method="POST"> {% csrf_token %} <input type="submit" class="btn btn-default" value="Download Export File : {{ name }}" name="resp" /> <a href="{% url 'home' %}" class="btn btn-default">{% trans 'Back' %}</a> </form> When user clicks on submit button, he should be able to download the linked file. But, I don't know why the if 'resp' in request.POST is never called. I miss something ? Thank you !