Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate Min and Max of Sum of an annotated field over a grouped by query in Django ORM?
To keep it simple I have four tables(A,B,Category and Relation), Relation table stores the intensity of A in B and Category stores the type of B. I need to query A, group by the query by Category and calculate Sum of Intensity of A in each category (which is possible using Django ORM), then I want to annotate Min and Max of calculated Sum in each category. My code is something like: A.objects.all().values('B_id').annotate(AcSum=Sum(Intensity)).annotate(Max(AcSum)) Which throws the error: django.core.exceptions.FieldError: Cannot compute Min('AcRiskIntensity'): 'AcRiskIntensity' is an aggregate Django-group-by package with the same error. For further information please also see this stackoverflow question. I am using Django 1.11 and PostgreSQL. Is there a way to achieve this using ORM, if there is not, what would be the solution using raw SQL expression? -
Django Signals and celery , is Sync
I am using celery to scrap some URLs , and pushing the scrap data to an API but because of quick calls on this API i need to use Django Signals if it Sync -
How to Add Image to PDF using WeasyPrint in Django? (Not static images but user uploaded images!)
I'm working on a Django project named 'cDoctorAssistant'. Here, a doctor can upload an image(say a patient's image). The images are in 'cDoctorAssistant/media/profile_pic' directory. Now, I need to create a pdf file about patient report. The report contains images. I an using WeasyPrint to create pdfs. But I can't add images to the pdf. Does any one know how to solve it? I only found how to add static images in google. But these images aren't saved in static directory. So I really need some help! Thanks in advance! :) -
CategoryView is not shown
CategoryView is not shown.I wrote in views.py like class CategoryView(ListView): model = Category def get_object(self): category_name = self.kwargs['category'] return Category.objects.get(name=category_name) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentCreateForm() return context in detail.html <div> <p>{{ object.text }}</p> </div> <div> <a href="#" class="list-group-item active"> Category </a> <div> {% for category in get_object.comment_set.all %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> But now in detail.html no category data is shown.I really cannot understand why this happens.I think I can get data by using get_object.comment_set.all in template but it is wrong.How should I fix this?What is wrong in my code? -
Django: How to write a mock/patch test for object creation?
I gave it a go, but I got the error message AttributeError: Mock object has no attribute '_state' for the code below. Not sure what I am doing wrong. Do note at the end of the question I mention that I have tried using patches, without much more luck. Model.py class Sale(models.Model): from_product = models.ForeignKey(Product) from_til = models.ForeignKey(Til) price = models.DecimalField(max_digits=8, decimal_places=2) create_date = models.DateTimeField('sale_date', editable=False) def __str__(self): return "%s %s %s" % (self.from_product, self.price, self.create_date) def save(self, *args, **kwargs): if not self.id: self.create_date = timezone.now() super(Sale, self).save(*args, **kwargs) test_models.py class SaleModelTestCase(TestCase): @classmethod def setUpClass(cls): super(SaleModelTestCase, cls).setUpClass() cls.product = MagicMock(spec=Product) cls.til = MagicMock(spec=Til) cls.price = 2.34 def test_create_sale(self): now = datetime.now() with mock.patch('django.utils.datetime_safe.datetime') as dt_mock: dt_mock.now().return_value = now new_sale = Sale.objects.create(from_product=self.product, from_til = self.til, price=self.price) self.assertTrue(isinstance(new_sale, Sale)) self.assertEqual(new_sale.create_date, now) I have been reading around and getting quite confused. If I understood correctly I can replace Sale.objects with @patch('app.models.Sale.objects'), which is placed above class SaleModelTestCase(TestCase): and include an extra mock_sale parameter. I gave that a go too, but self.assertTrue(isinstance(new_sale, Sale)) returns False is not true. If anyone is about to show me where I am going wrong, I would be very grateful. -
Override Django widgets default templates
I want to override the Django (2.01) widget templates, because I need to add classes for each input, label, and position them differently app - templates - app - django - forms - widgets - input.html or app - templates - django - forms - widgets - input.html or template project directory: - templates - django - forms - widgets - input.html None of them works, (even if I this is how is recommended in docs, and from an answer that I saw on stackoverflow), it still loads from default. Being general widgets templates, I'm preferring to put them in the template project directory, but from what I reed by default for widgets search only in installed apps. -
why does `Model.objects.get(id=model.ForeignKeyField).IntegerField` not return an integer?
I'm trying to get the value of an IntegerField from a queryset object based on the value of a ForeignKeyField so I can 1 to it like this. all = Comment.objects.filter(video=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] for comment in all: comment.indent = Comment.objects.get(id=comment.replyto).indent + 1; However it seems to cause an error saying: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Comment' Why is this? What am I doing wrong? comment model: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username') video = models.ForeignKey(Video, on_delete=models.CASCADE) description = models.TextField(default="none") replyto = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # maybe add ability to update comments... indent = models.IntegerField(default=0) -
How to create an Inline through a chain of foreign keys in Django admin?
Supposing I have these Django models: class Genre(models.Model): name = models.CharField(max_length=255) class Author(models.Model): name = models.CharField(max_length=255) genre = models.ForeignKey('Genre') class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey('Author') I want to define inlines in Django Admin for a Genre instance showing all related books. How can I do it? I tried this way: class BookInline(admin.TabularInline): model = Book extra = 0 class GenreAdmin(admin.ModelAdmin): inlines = [BookInline] admin.site.register(Genre, GenreAdmin) that brought me the error: ValueError: 'Book' has no ForeignKey to 'Genre' How can I define the inline correctly? -
How do I not let the pdf file to download, instead email it to me in django?
I have this function html_to_pdf_view that generates pdf file. But whenever I open the url linked to that view, it downloads the pdf file. I don't want the file to be downloaded, instead the file should be sent to my email. def html_to_pdf_view(request): paragraphs = ['first paragraph', 'second paragraph', 'third paragraph'] html_string = render_to_string('blog/pdf_template.html', {'paragraphs': paragraphs}) html = HTML(string=html_string) html.write_pdf(target='/tmp/mypdf.pdf'); fs = FileSystemStorage('/tmp') with fs.open('mypdf.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response return response -
FileNotFoundError: [Errno 2] No such file or directory: 'media/GeoLite2-City.mmdb'
I have a file in the media/ directory: When I in a test.py file to get it by GeoIP(): from pygeoip import GeoIP def getLatLon(ip): gi = GeoIP('media/GeoLite2-City.mmdb') data = gi.record_by_addr(ip) return data getLatLon("113.210.32.76") There comes issue: File "/Users/luowensheng/Desktop/TestIOS/TestPython/testDemo02/ipaddr/tests.py", line 16, in <module> getLatLon("103.200.32.76") File "/Users/luowensheng/Desktop/TestIOS/TestPython/testDemo02/ipaddr/tests.py", line 10, in getLatLon gi = GeoIP('media/GeoLite2-City.mmdb') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pygeoip/__init__.py", line 118, in __init__ self._fp = codecs.open(filename, 'rb', ENCODING) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py", line 895, in open file = builtins.open(filename, mode, buffering) FileNotFoundError: [Errno 2] No such file or directory: 'media/GeoLite2-City.mmdb' It says the FileNotFoundError. why there comes this error? -
Where I can add hook after restarting Django server?
I want to add extra hook to cleanup some data but for that I need Django server running or some other services running that I added in Django restart commands. -
Django: Remember url parameters in django-tables2 with django-filter
Hello this is my view: class FilteredReclamationListView(FilterView, SingleTableView): table_class = ReclamationTable model = ReclamationMainModel template_name = 'reclamation_table/index.html' filterset_class = ReclamationFilter table_pagination = { 'per_page': 50 } def get_table_data(self): return self.object_list def get_queryset(self): return self.model.objects.filter(archive=False).order_by('-id') Is this any possible to remember the url parameter in this case? I would like to have situation that user go to another view and when he is back he will see his last query/filter. I reading about sessions and request.GET.urlencode() but I can't apply that in my view. -
Render subtemplate inside a template in Django [duplicate]
This question already has an answer here: Django use a variable within a template tag 2 answers I have a bootstrap modal element that changes it's contents depending on different application states and user preferences. I have a view rendering the 'main' template and passing essential data and a form to it, but I want to populate the contents of modal dynamically. Contents of this modal should sometimes be other forms and sometimes just plain data representation. It is possible to do bunch of conditional statements inside a template and do something like: <div class="modal-content"> {% if something %} {% include 'foo.html' %} {% elif something_else %} {% include 'bar.html' %} {% else %} ... {% endif %} </div> But such approach obviously is very much hard-coded and only solves a problem of rendering plain html templates, so I tried to pass template as a parameter to 'main' template: class Homepage(View): def get(self, request): ... sub_template = 'foo.html' return render(..., {...,'sub_template': sub_template}) And then render the inside of modal element like you normally access argument passed to template: <div class="modal-content"> {% include {{sub_template}} %} </div> But this approach didn't work. Is there a way to pass template as argument to … -
Using django autocomplete light with form tools preview
I try to use django autocomplete light outside the admin panel in combination with form tools. I accomplished to use autocomplete inside the admin panel and to use regular forms in the django form tools. But the last step, to use autocomplete inside outside the admin panel will not work. This is from my forms.py: class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('user',) widgets = { 'user': autocomplete.ModelSelect2(url='autocomplete-person') } [...] class MessageForm(forms.Form): user = PersonForm() I guess the error must be here, but I am not sure. What I think, what this should do: * Inherits from ModelForm * changes the widgets to the fitting aoutocomplete widget * Uses correct model and fields * In MessageForm this should be used. Instead nothing shoes on the screen. Can someone help? I can provide other parts of my code if necessary. -
Django & React Application on AWS Lambda
I am building a project with Django at the back and React at the front. I will be prepackaging the react files and serving them as plane static files without a NodeJS server (plain django static files from S3 and Cloudfront). The root url renders a blank template and pulls in the necessary JS files and react handles the rest of it. I also have APIs written using DRF which is accessed by React. I am basically following this architecture style - https://github.com/Seedstars/django-react-redux-base So I would like to know if and how this can be implemented in AWS Lambda? -
how to use signal in thread
I want to run a function in background. so I use Threading in my code. but return error ValueError: signal only works in main thread and don't know about two things: what is the main thread how to solve this problem :) views.py def callback(update): print('I received', update) def message_poll_start(): try: client = TelegramClient('phone', api_id, api_hash, update_workers=1, spawn_read_thread=False) client.connect() client.add_update_handler(callback) client.idle() except TypeNotFoundError: pass def message_poll_start_thread(request): t = threading.Thread(target=message_poll_start, args=(), kwargs={}) t.setDaemon(True) t.start() return HttpResponse("message polling started") urls.py urlpatterns = [ path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"), ] -
Multiple Objects Returned
I'm beginner in python and Django rest And I stuck when I fetch data. Here is my API :- http://127.0.0.1:8000/subjects/course/23/ I want a all subject data according to course which I select..When I hit this api if single data present working awesome but when inside course_id multiple subject present then gives me error such as : Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Subject -- it returned 2! Here is my model.py class Subject(models.Model): course = models.CharField(max_length=255, blank=False, unique=False) subject = models.CharField(max_length=255, blank=False, unique=False) description = models.CharField(max_length=255, blank=False, unique=False) amount = models.CharField(max_length=255, blank=False) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.title) Here is my serializer.py class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = ('id', 'course', 'subject', 'description', 'amount', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified') lookup_field = 'course' Here is my views.py class ViewSubjectAccordingCourse(generics.RetrieveUpdateDestroyAPIView): """This class handles the GET and POSt requests of our rest api.""" queryset = Subject.objects.all() serializer_class = SubjectSerializer lookup_field = 'course' Here is my urls.py url(r'^subjects/course/(?P<course>[0-9]+)/$', ViewSubjectAccordingCourse.as_view(), name="details"), -
Django dynamic multiple form
I have form for adding Company: class Company(models.Model): name = models.CharField(max_length=50, ) profile = models.ForeignKey("Profile", blank=True, null=True) sector = models.ForeignKey("Sector", blank=True, null=True) I want to dynamically add another form on same site when proper button is clicked. For example after clicking "Add Address" button, form should be extended with: city = models.ForeignKey("City", blank=True, null=True) street_name = models.CharField(max_length=50, blank=True) and submiting this form will create new Customer, Address and CustomerAddress records. I already have worked out solution which isn't perfect, cause I added "blank=True", to fields in additional forms and show/hide form in JS. This soultion is causing another problem, because now I don't have any validation for form. I don't want to create custom validation for every template, in which I add multiple forms. -
Compare an object type with string in jinja
I am making a project in djnago. I am having a condition in jinja html template where a comparision is not running correctly.Even through there values are same . part of code which is not working:- {%if user_obj.status =='Online'%} <p>Working</p> {%endif%} i think they are of different type that's why they are not working.But how can i make them working. -
html template using django,
` Total No. of User {{total_user}} <td width="30%">Total No. of New User(Today)</td> <td>{{new_user}}</td> </tr> <tr> <td>Total No. of Transaction</td> <td>{{total_trans}}</td> <td>Total No. of Transaction (Today)</td> <td>{{total_trans_today}}</td> </tr> <tr> <td>Total No. of Refer a Friend</td> <td>{{total_refer}}</td> <td>Total No. of Vehicle</td> <td>{{total_vehicle}}</td> </tr> <tr> <td>Total No. of Suggest </td> <td>{{suggest_pump}}</td> <td>Total No. of Suggest (Today)</td> <td>{{suggest_today}}</td> </tr> <tr> <td>Total No. of Reported </td> <td>{{reported_price}}</td> <td >Total No. of Reported (Today)</td> <td>{{reported_today}}</td> </tr> <tr> <td>Total No. of review</td> <td>{{total_review}}</td> <td>Total No. of station reviewed</td> <td>{{total_station_review}}</td> </tr> </tbody> </table> </div>`<td width="20%">Total No. of User</td> <td>{{total_user}}</td> How do i add link to the outcome in Django? like the outcome is in integer but it should redirect to the list, which i have made in views. Just a hint for including a link to numbers -
FATAL: password authentication failed for user "ubuntu"
I'm using djanog version 1.11 and postgressql 9.5###, I'm facing below error. but my django databases settings different. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':'test_db', 'USERNAME':'rails', 'PASSWORD':'rails', 'HOST':'localhost', 'PORT':'5432', } } I think django pass user as ubuntu user, it's system logged in user. System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f39fbfe5488> Traceback (most recent call last): File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) … -
Djaongo: ModelChoiceField and Widget - Could not display non-foreign key field
I want to create a select field that displays a list of record from a column that is not a foreign key. I am able to do it using widget=ForeignKeyRawIdWidget(rel=Slum._meta.get_field('electoral_ward').rel where 'electoral_ward' is a foreign key in 'Slum' model. I wish to have the same behavior for a field ('name') which is just a char field in 'Slum' model. Thank you! -
How to make a queryset also contain a PK in django
I've got this model: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username') video = models.ForeignKey(Video, on_delete=models.CASCADE) description = models.TextField(default="none") replyto = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # maybe add ability to update comments... indent = models.IntegerField(default=0) On which i've got to return a queryset like this: Comment.objects.filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] I get this as a response (after having serialized it to json and send it as response to a Ajax request. ): Object { user: "TestUser", video: 7, description: "test new video comment lol", replyto: 5, uploaded: "2018-01-12T09:14:24.281Z", updated: "2018-01-12T09:14:24.281Z", indent: 0 } Object { user: "admin", video: 7, description: "testing the new comment system per …", replyto: null, uploaded: "2018-01-12T09:14:05.740Z", updated: "2018-01-12T09:14:05.740Z", indent: 0 } However i'd like to include the PK of each object in the list of values. So I tried: Comment.objects.value_list('pk','user','video','description','replyto','uploaded','updated','indent').filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] which caused the error: AttributeError: 'Manager' object has no attribute 'value_list' why is this? how can I get a queryset which also includes the PK? EDIT as requested: here is the code for serializing the object: def obtain_comments(request, *args, **kwargs): begin = int(request.GET['begin']) end = int(request.GET['end']) # check if end is less than number of comments and begin is more or equal than 0 … -
Visualising Django Models
We have some legacy code for a Django REST Framework which is connected to a Postgresql database. I would like to visualise all the tables in such a way that I know which fields are there in each column and how they are connected to each other (What my research tells me is an ER diagram). I tried using Dvisualiser and MySQL workbench, but owing to lack of familiarity was not able to extract the required data. Query: Is there a quick and dirty way to visualise this so we can understand how th data and relatonships are structured? If yes, which tool will offer the shortest learning curve, as this is an one off requirement. -
Django Templates - block inside an include, the block displays above or below, not in the block
I have inserted a block inside an include in hopes that I could references that block and add extra links to it if needed. site_page.html: {% extends 'home/sbadmin_base.html' %} {% load extras %} {% load static %} {% block content %} {% include 'sites/site_tabs.html' %} {% block extratabs %} <li {{ active_sims|safe }}> <a href="{% url 'sites:site_overview' SiteID %}">Edit Site</a> </li> {% endblock %} site_tabs.html {% load extras %} <!-- Nav tabs --> <ul class="nav nav-tabs"> <li {{ active_ip|safe }}><a href="{% url 'sites:site_overview' SiteID %}">Overview</a> </li> <li {{ active_files|safe }}><a href="{% url 'sites:site_detail_files' SiteID %}">Files and Photos</a> </li> {% block extratabs %} {% endblock %} </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane fade in active" id="ip"> <div class="row"> When my page is rendered, the "extratabs" just appear below the include and outside the list as per the below: <!-- Nav tabs --> <ul class="nav nav-tabs"> <li class="active"><a href="/sites/site/7">Overview</a> </li> <li ><a href="/sites/site/files/7">Files and Photos</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane fade in active" id="ip"> <div class="row"> <li > <a href="/sites/site/7">Edit Site</a> </li>