Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to move an existing django project to pycharm
tutorial --- venv --- lib --- include --- bin --- first --- manage.py my problem is , trying to open in pychrem and when i try to run the manage.py i have this error. in terminal evreything work , but in pychrem not . /usr/local/bin/python3.8 /Users/alekseyzgeria/Desktop/tutorial/manage.py Traceback (most recent call last): File "/Users/alekseyzgeria/Desktop/tutorial/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' **The above exception was the direct cause of the following exception:** File "/Users/alekseyzgeria/Desktop/tutorial/manage.py", line 22, in <module> main() File "/Users/alekseyzgeria/Desktop/tutorial/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Django CreateUpdateView implementation in the django template
I am very new to django Class based views, trying to integrate it with my existing project. My goal is to use same Class based view to Create and Update student application form. I am trying to integrate CreateUpdateView from the @scubabuddha's answer this solution. urls.py path('add/', StudentView.as_view(), name='addview'), path('<int:pk>/edit/', StudentView.as_view(), name='editview'), views.py from createupdateview import CreateUpdateView class StudentView(CreateUpdateView): template_name="admission.html" Model = Student form_class = StudentForm def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) def post(self, request, *args, **kwargs): forms = {"userform": UserForm(request.POST or None), guardian..., contact..., # other 5-6 forms} if request.POST: invalid_forms = [form.is_valid() for form in self.forms.values()] if not all(invalid_forms): messages.error(request,'You must fill up all the valid mandatory form fields!') return render(request, 'admission.html', forms) #-- Logic to validate and save each form ... return render(request, 'admission.html', forms) return render(request, 'admission.html', forms) This is perfectly working for CreateView, but not able to understand how to use this for UpdateView or editview. If user hits editview, admission.html should display all the saved details in the html I want to display, all the student details in the UpdateView forms - <form class="form" name="admissionForm" id="admissionForm" method="post" enctype="multipart/form-data" action="{% url 'addview' %}" > {% csrf_token %} <div class="pages"> <h4 class="mt-2 mb-3">Personal … -
"invalid literal for int() with base 10: '' Error coming while using dynamic field in django update query
user = models.users.objects.filter(token=request.POST['token'],otp=otp).update(Q(**{ column: new_email_or_phone})); -
Respond with Not Found if user is not authorised to view the instance
How can I modify Django behaviour, for some models only, to obscure the existence of an object in that model, if the user is not authorised to view that object? By default, Django will respond to a query for a nonexistent object with 404 Not Found, and to an existing object that the user is not permitted to view, with 403 Forbidden. This is all correct, as a default. What I'd like to do though, is to present some specific models to each user as containing only the records that user may view, and nothing else exists in there to be queried. If they're authorised to view the instance, it is shown; if it exists but they're not authorised, then Django should not reveal even whether that instance exists and should respond only with 404 Not Found. This requirement is only for some models in the database. For example, confidential documents: the visitor should not be able to sniff around and discover which documents exist and which do not. Either they have permission to view that document, or they should not be told there's anything there just as if they queried a nonexistent document. For other models, the normal behaviour … -
How to force event.preventDefault()?
Inside my fetch function, I'm sending a mail variable through a POST request to my server as JSON. In my server I open my database and check if the mail exists, and if it does, I add to my jsoned dict a string {"exists":"exists"} So I know that it exists. Then, still on the server side, I return a JSONResponse of my dict back to the js. I want my javascript to detect if it exists, so i look for the string i added to my dict. I look for result.exists in my script. I only want the form to be prevented from submit if the email doesn't exists, and want the form to be submitted if the email already exists. So I`m doing: document.addEventListener("DOMContentLoaded", function() { document.querySelector('#laform, #elform').addEventListener("submit", function(event) { var content = document.querySelector('#elcontent').value; fetch("", { method: 'POST', body: JSON.stringify({ mail: document.querySelector('#email').value, name: document.querySelector('#name').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { // Print result if (result.exists === undefined) { event.preventDefault(); if (content.length > 700) { popup_content('show'); } } }); }); }) </script> But here is a big problem. Inside the .then() it's too late to add an event.preventDefault() So I … -
Django on wamp apache hijacking all the wampp functionalities?
I am trying to bring my Django project and my other PHP project on the same Wamp instance. However, after bringing the Django to the wamp server, all of the wamp functionalities are hijacked by the Django, including phpMyadmin, and all the projects in the www directory of the wamp refuse to load as those URLs are hijacked by Django. Unfortunately, I am very new to the apache and I need to rapidly set up my hosting environment for my research purposes and I am running short on time, and I need both of my projects e.g. Django and Php to run on the same server and the same port. I have tried many vhost configs, but none have been working for me, I have even tried changing the alias of django and PHP in all possible combinations with subdirectories but it still doesn't work. The following is my current vhost configuration: # Virtual Hosts <VirtualHost *:80> ServerName php.localhost ServerAlias localhost Alias / ${INSTALL_DIR}/www/ DocumentRoot "${INSTALL_DIR}/www" <Directory "${INSTALL_DIR}/www/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require local </Directory> </VirtualHost> # This is for your Django stuff <VirtualHost *:80> ServerName localhost DocumentRoot C:/Users/abdur/PycharmProjects/untitled/discovery/ WSGIDaemonProcess discovery python-path=/C:/Users/abdur/PycharmProjects/untitled python-home=/C:/Users/abdur/PycharmProjects/untitled/discovery WSGIProcessGroup discovery WSGIScriptAlias / … -
Call django task from button click in nuxt application via rest api
I have a python wrapper that updates data from a third party api in my backend. The background task cannot fetch all the data without taking params in order to filter down each call and return filtered batches. I don't want to have these background tasks running periodically because I would like to limit my api calls. What I'm trying to do is use button click to make a post request from my nuxt frontend and trigger a function that will fetch the data and update a model in in the view. When I make the post request from nuxt I get data to the backend and saving to the models. What doesn't happen is events function being called and saving to the events model. I'm not getting any error but I would've expected the rest of the code within the view would be called before being 201 created. How can I get the rest of the code to execute or even pass a parameter each time the button is clicked in nuxt to events = api.market_data.get_events(sport_ids=['my_param']) nuxtapp <template> <div> <button type="button" class="btn btn-dark" v-on:click="get_tennis">get_tennis</button> </div> </template> <script> export default { methods: { get_tennis () { this.$axios.post('api/sportsid/', { sport_id: "9", … -
How to efficiently upload multiple files in django
Have a working app that allows the user to upload multiple files (typically images) at once, but if they upload more than a few files at once, or very large files, it takes very long to go through and they're stuck on the form template waiting while this is happening. I can tell that what I'm doing isn't very efficient but I'm not sure how to make it better/faster. Am new to django/python, thanks for any help. views.py: def add_event(request): form = EventFullForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('images') if request.method == "POST": if form.is_valid(): user = request.user title = form.cleaned_data['title'] description = form.cleaned_data['description'] start_time = form.cleaned_data['start_time'] end_time = form.cleaned_data['end_time'] event_obj = Event.objects.create(user=user, title=title, description=description, start_time=start_time, end_time=end_time) for f in files: Images.objects.create(event=event_obj, image=f) return redirect('calendarapp:calendar') else: form = EventFullForm() context = {'form': form, 'files': files} return render(request, 'calendarapp/test_form.html', context) Please let me know if sharing any additional code would be helpful -
Django search / filter across multiple models
In my Django website, I'm trying to create a search bar on my homepage that returns results that are stored in two different models(Articles, Jobs) Currently, I get an empty result set when I search using this code: In models.py, class Articles(models.Model): objects = None news_title = models.CharField(db_column="title", max_length=400) news_url = models.URLField(db_column="link", max_length=400) image_link = models.CharField(db_column="image", max_length=400) published_date = models.CharField(db_column="published_date", max_length=400) class Meta: managed = False db_table = "articles" def __str__(self): return self.news_title class Jobs(models.Model): objects = None company = models.CharField(db_column='company', max_length=100) job_title = models.CharField(db_column='job_title', max_length=300) experience = models.CharField(db_column='experience', max_length=300) edu_level = models.CharField(db_column='edu_level', max_length=50) class Meta: managed = False db_table = "job_list" def __str__(self): return self.job_title In views.py, class SearchView(ListView): template_name = 'blog/search_results.html' def get_queryset(self): request = self.request query = request.GET.get('q', '') articles_results = Articles.objects.filter(Q(news_title__icontains=query)) jobs_results = Jobs.objects.filter(Q(job_title__icontains=query)) context={ 'articles':articles_results, 'jobs':jobs_results, } return render(request, 'blog/search_results.html', context) In main_view.html, I'm using this code for creating a search bar: <form action="{%url 'search_results' %}" method="get" values="{{request.GET.q}}" class="search-jobs-form"> <div class="row mb-5"> <input name="q" type="text" values="{{request.GET.q}}" placeholder="search"> </div> <button type="submit">Search</button> </form> And in search_results.html, {% block content %} {% for job in jobs %} <h5>{{job.job_title}}</h5> <p>{{job.company}}</p> {% endfor %} {% for article in articles %} <h5>{{article.news_title}}</h5> <p>{{article.published_date}}</p> {% endfor %} {% endblock %} -
How to stack django model saving calls in case an error occurs?
My web app needs massive load from csv files. Files may have reference errors. How can I save "softly" each row and rollback all saved records if an error occurs? I'm using django command. -
Do you know why Django ls might not show up in project directory?
I tried to use django-admin.py from your virtualenv virtual environment but the manage.py and other files do not get created. I tried using the ls command and nothing shows up in the project directory. I am using version 3 of Django and I ran it using powershell in adminstrator mode. Please help! Thank you very much, Josh -
Problem with django 3.1, gunicorn : ModuleNotFoundError: No module named 'debates' - ubuntu 20.04 - digitalocean
I have the following problem following this tutorial, get to: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20 -04 # creating-systemd-socket-and-service-files-for-gunicorn, when checking the status of gunicorn the following error appears when reviewing the journal: Aug 26 02:17:12 web-debates gunicorn[23045]: ModuleNotFoundError: No module named 'debates' Aug 26 02:17:12 web-debates gunicorn[23045]: [2020-08-26 02:17:12 +0000] [23045] [INFO] Worker exiting (pid: 23045) Aug 26 02:17:12 web-debates gunicorn[23032]: Traceback (most recent call last): Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 202, in run Aug 26 02:17:12 web-debates gunicorn[23032]: self.manage_workers() Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 545, in manage_workers Aug 26 02:17:12 web-debates gunicorn[23032]: self.spawn_workers() Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 617, in spawn_workers Aug 26 02:17:12 web-debates gunicorn[23032]: time.sleep(0.1 * random.random()) Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Aug 26 02:17:12 web-debates gunicorn[23032]: self.reap_workers() Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/lib/python3.8/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Aug 26 02:17:12 web-debates gunicorn[23032]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Aug 26 02:17:12 web-debates gunicorn[23032]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Aug 26 02:17:12 web-debates gunicorn[23032]: During handling of the above exception, another exception occurred: Aug 26 02:17:12 web-debates gunicorn[23032]: Traceback (most recent call last): Aug 26 02:17:12 web-debates gunicorn[23032]: File "/root/proyectosDebates/web/bin/gunicorn", line 8, in <module> Aug 26 … -
how do I setup a lesson allow to have more than one permission based on my column membership_id?
I am trying to code a single course platform where each lesson could have more than one permission based on the membership_id, so this field can have 1,2 or any it means free or both(free and paid). my code works fine as it only takes one perm, but as I cannot add another perm or change the permit will strictly use that one. so I want to allow 1 to many status def get(self, request): lesson = get_object_or_404(Lesson, pk=8) user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type print(user_membership_type) lesson_allowed_mem_types = lesson.allowed_memberships.all() allowed_memberships.set(Mebership.objects.all()) context = { 'lesson': None , [..]} if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): # user is member context = { 'lesson': lesson} # not a member return render(request, "xxxxxxxxxxxx.html", context) models class Lesson(models.Model): [..] allowed_memberships = models.ManyToManyField(Membership) def __str__(self): return self.content_title class Meta: ordering = ['pk'] MEMBERSHIP_CHOICES = ( ('Free', 'free'), ('Professional', 'pro'), ) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) [...] def __str__(self): return self.membership_type class UserMembership(models.Model): [..] membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.email database id,lesson_id,membership_id "2" "2" "2" "8" "8" "2" "9" "1" "2" "10" "3" "2" "11" "4" "2" "12" "5" "2" "13" "6" "2" "14" "7" "2" each lesson can have more than one permission example. … -
Anyone django genius here? How to connect excel file in my project?
I spent 2 night to solve this ploblem... My first question in stackoverflow In views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('../../analysis') else: form = UploadFileForm() return render( request, 'blog/upload.html', {'form': form} ) In models.py class UploadFileModel(models.Model): title = models.TextField(default='') file = models.FileField(null=True) I implemented excel,csv file's uploading in my website. And file is saved in '_media' folder. I want to execute machine running code with this excel file. How can i get name of uploaded file? Plz... -
django.db.utils.OperationalError: no such column: tickets_ticket_notes.ticket_id
I am getting this error on when I try to create a note or comment section to a post. I am trying to make kind of a ticketing system and if I remove the section where it looks for existing comments/notes it works fine. I feel as if I am missing a connection to the tickets/post from the notes/comments. I have a the notes linked to the tickets by a foreign key in my models. not sure what else I am missing. django.db.utils.OperationalError: no such column: tickets_ticket_notes.ticket_id Models.py class Tickets(models.Model): STATUS = ( ('Assigned', "Assigned"), ('Traveling', "Travelling"), ('Completed', "Completed"), ('On Hol', "On Hold"), ) assigned_tech = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=False,) ticket_number = models.CharField(max_length=10) SM_number = models.CharField(max_length=14, default="service manager number") slug = models.SlugField() status = models.CharField(max_length= 10, choices=STATUS, default='Assigned') due_date = models.DateTimeField(datetime.date.today()) summary = models.CharField(max_length=60, null=False, default="Must Change") asset_tag = models.CharField(max_length=10) address = models.TextField(max_length=30, default='enter address') city_state = models.CharField(max_length=14, default='enter city/state') description = models.TextField(default='enter ticket description') def get_absolute_url(self): return reverse('ticket_detail', kwargs={'slug': self.slug}) def __str__(self): return self.ticket_number class Ticket_Notes(models.Model): TYPE = ( (0, "On Site"), (1, "Travelling"), ) user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=False) ticket = models.ForeignKey(Tickets, on_delete=models.CASCADE, related_name='notes') note =models.TextField(blank=True) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(auto_now_add=True) entry_type = models.IntegerField(choices=TYPE, default=0) created_on = models.DateTimeField(auto_now_add=True) … -
Django error - __str__ returned non-string (type User)
I have the below 2 models - User and PhoneProfile. I can successfully create records for User. When i browse to PhoneProfile using admin console, i can see the foreign key present. On selection of an entry and completion of the rest of the fields, i get the error below. class User(AbstractBaseUser): phone_regex = RegexValidator(regex = r'^\+?1?\d{2,14}$', message = "Phone number must be in the format: '+xxxxxxxxxx'.") phone = models.CharField(validators = [phone_regex], max_length = 15, unique = True) first_name = models.CharField(max_length = 50, blank = False, null = False) last_name = models.CharField(max_length = 50, blank = False, null = False) email = models.CharField(max_length = 100, blank = True, null = True) first_login = models.BooleanField(default = False) active = models.BooleanField(default = True) staff = models.BooleanField(default = True) admin = models.BooleanField(default = False) timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = UserManager() class PhoneProfile(models.Model): registered_phone = models.ForeignKey(User, on_delete=models.CASCADE, related_name='registered_phone') notify_enable_low_bal = models.BooleanField() notify_amount_low_bal = models.DecimalField(decimal_places=2, max_digits=10000, default='50', null=True) Error message when i attempt to create an entry in PhoneProfile model __str__ returned non-string (type User) Request Method: POST Request URL: http://localhost:8000/admin/smartrecharge/phoneprofile/add/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: __str__ returned non-string (type User) Exception Location: /Users/django-backend/venv/lib/python3.7/site-packages/django/contrib/admin/options.py in log_addition, … -
Blank options in space tag
Hello I have a model in Django where I have a forein key and I am displaying it with a select tag in html. However there are blank options in the selector tag but not in my database. How can I remove them. I want also to ask how I can delete the ------ option. html, only the select tag <select style='width:200px';name="bolum" required="" id="id_bolum"> {% for x in form.bolum %} {% if {{x}} ''%} {%else%} <option value="{{x.id}}">{{x}}</option> {% endif %} {% endfor %} </select> models.py from django.db import models # Create your models here. class Department(models.Model): department=models.CharField(max_length=128) def __str__(self): return self.department class WPGroup(models.Model): bolum = models.ForeignKey('Department', on_delete=models.CASCADE, related_name='department_for_wpgroup',null=False, blank=False) name=models.CharField(max_length=128,blank=False) number=models.PositiveIntegerField(blank=False) mail=models.EmailField(max_length=128,blank=False) def __str__(self): return self.name forms.py from django import forms from .models import WPGroup class WPGroupForm(forms.ModelForm): class Meta: model=WPGroup fields=['name','number','bolum','mail'] def clean_mail(self): email = self.cleaned_data['mail'] if "@itu.edu.tr" not in email: raise forms.ValidationError("You must include @itu.edu.tr") return email here is also a screenshot of the website -
django chart.js - Query to get count of all distinct values for particular column
My goal is to create a query to group together unique 'charges' and count them. Then correctly implementing a for loop, which would in a pie chart showing multiple slices, each individual slice showing the total count per unique charge. My problem is using my current queries I run into the following attribute error 'dict' object has no attribute 'charge'. I have tried a few different ways to write the query and would appreciate feedback in writing a query or in my for loop. # Models.py class Arrest(models.Model): number = models.IntegerField() date = models.DateField() charge = models.CharField(max_length=64) # Views.py def visuals(request): data = [] labels = [] # The two queries I have tried. # queryset = Arrest.objects.values('charge').annotate(the_count=Count('charge')) # queryset = Arrest.objects.values('charge').order_by('charge').annotate(the_count=Count('charge')) for arrest in queryset: data.append(arrest.charge) labels.append(arrest.charge) return render(request, "data/visuals.html", { 'labels': labels, 'data': data, }) # Error AttributeError at /visuals 'dict' object has no attribute 'charge' -
How do I assign instances to models in django?
I'm building a child chore management app, and I've run into a blocker. Here's what I'm trying to do: assign individual kids individual instances of various rules (i.e. having multiple instances of "wash dishes", so that one kid can complete their version without it being marked as complete for each kid), so I will be able to: only display the rules that are assigned to each kid on their own page (i.e. kid 1 can have their instances of rules a, b, c displayed, while kid 2 has their instances of rules b, c, d displayed) end goal is to be able to tally up the points each kid has earned Here's what I have done so far: displaying list of all kids ability to create rules instances displaying all rules instances with every child. Here are my models: class Rule(models.Model): """ Model representing a base class for rules. Weight field is how much you want the rule to be worth. The same rule can be applied to multiple kids, and a single kid can be assigned multiple rules. """ name = models.CharField(max_length=50, help_text='Enter rule', default=None) weight = models.IntegerField(default=0) description = models.TextField(max_length=250, help_text='Enter description of rule') completed = models.BooleanField(default=False, help_text='Is … -
How can I create a model property based on specific model fields?
Let's say I have the following model: class DriverReview(models.Model): driver = models.ForeignKey(Driver, on_delete=models.CASCADE,) driving_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]) communication_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]) professionalism_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]) review_text = models.TextField() created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name="driver_review_created_by", on_delete=models.CASCADE, null=True, blank=True) last_updated = models.DateTimeField(auto_now=True) last_updated_by = models.ForeignKey(User, related_name="driver_review_last_updated_by", on_delete=models.CASCADE, null=True, blank=True) is_deleted = models.BooleanField(default=False) deleted = models.DateTimeField(null=True, blank=True) deleted_by = models.ForeignKey(User, related_name="driver_review_deleted_by", on_delete=models.CASCADE, null=True, blank=True) @property def review_average_score(self): review_average_score = round(np.mean([self.driving_score, self.communication_score, self.professionalism_score]), 2) return review_average_score I have created a property to get the review average score. The issue is that I don't want to hardcode the _score fields. Is there a way to filter the fields that contain _score and use them in the average ? -
Conditionally showing a button with DJANGO template language
I have a page that should show a button if the user is marked as "facturable" (billable), otherwise, the button should not appear. I tried the following code: {% if form_experfil.facturable %} <a href="{% url 'incid:xtodo' %}?pagref=factdatshow" type="button" class="btn btn-primary waves-effect"> Consultar datos de facturación</a> {% endif %} But it keeps showing. This and other fails make me think that the {% if %} tag behaviour isnh't as straightforward as I thought, and it does not just clip the html code down to the endif tag, but something gets rendered first. Is there somewhere where this is formally documented without mystical references?. Is there a way to just show this button when the customer has this data and not show it otherwise?. -
Django w/django_filters lookups by methods or non-model fields
Versions: Django 3.0.6, Python 3.8, MySQL 8.0, django_filters 2.3.0 Please bear with me as I am not sure if I have entitled the question properly. I will start with the relevant code: ========= models.py ========= class Vendor(models.Model): name = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=50) class Product(models.Model): name = models.CharField(max_length=50) vendor = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) class Rating (models.Model): score = models.PositiveIntegerField(default=0, validators=[MaxValueValidator(10)]) product = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True) def category(self): return self.product.category def vendor(self): return self.product.vendor ========== filters.py ========== from .models import Vendor, Category, Product, Rating import django_filters class RatingFilter(django_filters.FilterSet): rating_filter = django_filters.RAngeFilter(field_name='score', lookup_expr='range') class Meta: model = Rating fields = '__all__' ======== views.py ======== from .filters import RatingFilter def RatingSearch(request): rating_list=Rating.objects.all() rating_filter = RatingFilter(request.GET, queryset=rating_list) return render (request, 'inventory/rating_search.html', { 'filter': rating_filter}) From a basic SQL perspective, I know that I can use the models as outline and filter a search of Rating records by a Category or Vendor by establishing the relationships between the tables. My goal is to use django_filters to do the same thing on a web form. Out of the box it is super easy to filter Ratings by Product and/or the Score. What I can't seem to sort out is … -
How can I extend django-admin
I have been looking for a way to extend the default django admin so that it can be showing User KPI's like Total Users any suggestions? Instead would it be proper to just create a separate view for that without tampering the default admin -
Django does not recognize column on annotated queryset when using queryset.values_list
I'm struggling with a very painful problem, regarding the usage of annotated in querysets and the usage of the function values_list. Here is the thing, in one of my core apps, i have a manager.py, that i use to implements some verbosity operation: class ProcedureManager(InheritanceManager): def get_queryset(self): core_models = importlib.import_module('core.models') queryset = super(ProcedureManager, self).get_queryset().select_subclasses() return queryset.annotate( total=Coalesce( Count('images__marks'), 0 ), total_images_count=Coalesce( Count('images'), 0 ), processed_images_count=Coalesce( Count('images', filter=models.Q(images__status=True)), 0 ), status=models.Case( models.When(processed_images_count__gt=0, then=True), default=False, output_field=models.BooleanField() ), positive=Exists( core_models.ImageMark.objects.filter( pattern__positive=True, image__procedure__pk=OuterRef('pk') ) ), suggested=Exists( core_models.ImageMark.objects.filter( suggested_pattern__positive=True, image__procedure__pk=OuterRef('pk') ) ) ) this class is used inside one of my models in models.py class Procedure(models.Model): objects = ProcedureManager() city = models.ForeignKey('accounts.City', on_delete=models.CASCADE) type = models.ForeignKey('core.ProcedureType', on_delete=models.CASCADE) company = models.ForeignKey( 'accounts.Company', related_name='procedures', on_delete=models.CASCADE) ...... def mark_result(self): if self.pk is None: return {} lookup = 'images__marks__pattern__name' queryset = Procedure.objects.filter(pk=1954) data = queryset.values_list(lookup, models.Count(lookup)) return {pattern: count for pattern, count in data if pattern is not None} def get_suggested_patterns(self): if self.pk is None: return {} lookup = 'images__marks__suggested_pattern__name' queryset = Procedure.objects.filter(pk=self.pk) data = queryset.values_list(lookup, models.Count(lookup)) return {suggested: count for suggested, count in data if suggested is not None} I have some template tags that I use in my templates html as follows: @register.simple_tag def build_positive_tooltip(procedure): result = … -
Django REST Upload CSV return Response with All posts
I have a Blog CMS that's working great, but I want to be able to upload a CSV with multiple test posts, and then add them to the database all at once. Right now I can upload the CSV and iterate through the lines, but because my POST functions returns a Response, it quits after one iteration. How can I get it to iterate through all the lines and then return the list of created Blog Posts? Here is my code that works to create one at a time: class PostsImportAPIView(generics.ListCreateAPIView): serializer_class = DashboardPostSerializer permission_classes = [IsOwner] pagination_class = BlogPostPagination def get_queryset(self, *args, **kwargs): return BlogPost.objects.all() def post(self, request, *args, **kwargs): if request.FILES: data = request.data else: data = request.data.copy() csv_file = TextIOWrapper(data['csv'].file, encoding='ascii', errors='replace') import_csv = csv.reader(csv_file) next(import_csv) counter = 0 for line in import_csv: if line: data['title'] = line[0] data['body'] = line[1] date_field = line[2].split('+') data['created_at'] = datetime.datetime.strptime(date_field[0], '%Y-%m-%d %H:%M:%S.%f') data['published'] = line[3] serializer = DashboardPostImportSerializer(data=data, context={'request': request}) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This works greater for one at a time, but what I'd like to do is increment my counter for each completed row, then return a queryset of posts that match the …