Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Did you forget to register or load this tag? - Django
I know this error is thrown usually when there's a syntax error, but I can't figure it out. Here's my error: Invalid block tag on line 3: 'reddit_tag_test', expected 'endautoescape'. Did you forget to register or load this tag? Here's my code: {% block content %}{% load reddit_tag_test %} {% for id in id_list %} <div class="mdl-card__media"> {% autoescape off %} {% reddit_tag_test id %}{% endautoescape %} {% endfor %} </div> {% endblock %} <script async src="//embed.redditmedia.com/widgets/platform.js" charset="UTF-8" ></script> I'm basically trying to embed reddit posts on my page. So I think this line {% reddit_tag_test id %} is causing the error, but can't figure out why. I'm passing a post id to the reddit_tag_test function in the reddit_tag_test.py template tag file. It should be spitting out raw html which appears on the page. Any help is much appreciated! :) -
Procfile declares types -> (none)
I have used Django for Beginners book and I am having an Application error with Heroku. I’m on Windows 10 and I’m using Python and Django. When I run the following code on the command line: heroku ps:scale web=1 It returns the following: Scaling dynos... ! ! Couldn't find that process type (web). I looked at some of the solutions for this error message and added a requirments.txt file with contents copied from pip freeze. I also have the heroku/python buildpack. In my .Procfile I have: web: gunicorn config.wsgi “config” is the name of the folder which contains my settings.py. After executing git push heroku master on the command line it tells me: Procfile declares types -> (none) It should say: Procfile declares types -> web When I checked heroku logs –tail on the command line, it returns an error: at=error code=H14 desc="No web processes running" Any assistance would be helpful. -
Filter objects between two dates in django with MongoDB
I am building RestApi using django and mongoDB, so I am trying to filter the objects that I have in the DB by two dates. Assume that the user inserted two dates, one is (from) second is (to), I want to return all the objects in my DB that is between these two dates. Here is my models: class BsfCall(models.Model): CallID = models.IntegerField(unique=True, null=True) deadlineDate = models.CharField(max_length=200, blank=True, null=True) organizationName = models.CharField(max_length=200, blank=True, null=True) information = models.CharField(max_length=200, blank=True, null=True) areaOfResearch = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.organizationName deadlineDate is storing the date in this format (day/month/year) How can I return the objects between these dates, for example I made this method but I was not able to complete it: def get_bsf_call_by_dates(first_date, second_date): from_date = datetime.strptime(first_date, "%d/%m/%y") to_date = datetime.strptime(second_date, "%d/%m/%y") Thanks A lot... -
django.db.utils.ProgrammingError: type "hstore" does not exist
Hi guys so I know this question has been asked many times but the solution that have been provided doesn't seem to fix the source of my problem. Based on what I've seen the solution is to run create extension hstore. However, I get the error django.db.utils.ProgrammingError: type "hstore" does not exist when I'm trying to run a django test, ie python manage.py test test_function I'm not familiar with django tests but from what I'm seeing with the codebase I am working with is that the django test is creating a test database when I run the django test command. When I checkout what extensions are available with the test database with \dx I see that it does not have hstore. If I run create extension hstore then the hstore extension gets created. Problem is that whenever I rerun the django test, python manage.py test test_function it tells me the test database already exists and I need to delete it first otherwise the command exits. By deleting the database the extension that just got added also gets removed thus when I run python manage.py test test_function again I end up with the same error. How do I get rid of … -
Running Gunicorn and Django
I don't know how to use gunicorn with django. Could you give me some help? This is how I run the server with django. It is https python3 manage.py runsslserver xx.8x.x3.x4:443 --certificate /etc/letsencrypt/live/callservicesvps.online/fullchain.pem --key /etc/letsencrypt/live/callserv.com/privkey.pem And in the gunicorn documentation it is mentioned that it must be executed as follows: gunicorn myproject.wsgi And here I have 2 questions. What is myproject.wsgi? Where Can I find it? Because if I look in the directory where the django project is, the only thing I find with wsgi is a file called wsgi.py Running the server as follows gives me an error gunicorn /home/proyectdirectory/wsgi.py It also gives me an error if I put: gunicorn /home/proyectdirectory/wsgi:Some_directory_where_the_proyec_is -
Can't upload file in Django
Created UpdateView and can't update the model with the file upload using forms. Provided the code below. print(form.cleaned_data) returns file None in the traceback models.py `from django.db import models # Create your models here. class DashModel(models.Model): name = models.CharField(max_length=220) file = models.FileField(null=True, blank=True)` forms.py `from django import forms from .models import * class AddModel(forms.ModelForm): class Meta: model = DashModel fields = ('name','file') widgets = { 'name' : forms.TextInput(attrs={'class':'form-control'}), 'file' : forms.FileInput, }` views.py `class DashModelUpdateView(UpdateView): template_name = 'dashboard/update_model.html' form_class = AddModel success_url = '/dashboard/search-models/' queryset = DashModel.objects.all() def form_valid(self,form): print(form.cleaned_data) form.save() return super().form_valid(form)` Traceback `[14/Apr/2021 01:00:00] "GET /dashboard/1/update/ HTTP/1.1" 200 16091 {'name': 'Some Name', 'file': None}` -
In Django, how do you create a foreign key to a table in a different schema (Oracle DB)
Using the models below, Django creates a migration file that specifies that primary app schema for the Supplier tables schema instead of the one specified on the Supplier Model. Any idea how to tell it to create the relationship to the correct schema? Can I just modify the migration file or with this cause problems with my queries later? Models class Supplier(models.Model): name = models.CharField(max_length=2000, null=False, blank=False) class Meta: db_table = '"SUPPLIER"."SUPPLIERS"' managed = False class Ticket(models.Model): justification = models.CharField(max_length=2000, null=False, blank=False) supplier = models.ForeignKey(Supplier, null=True, blank=True, related_name='tickets') class Meta: db_table = 'TICKET' It creates a migration file like this: class Migration(migrations.Migration): dependencies = [ ('app_schema', '0002_supplier'), ] operations = [ migrations.AddField( model_name='ticket', name='supplier', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='app_schema.Supplier'), ), ] -
Django Serialization With Normalized Models
I am having trouble Serializing my following Django models using DRF. This is my following modal code: class Project(models.Model): project_number = models.CharField(unique=True, null=False, max_length=25) date_created = models.DateField(auto_now_add=True) created_by = models.CharField(default="N/A", blank=False, max_length=10) date_updated = models.DateField(auto_now=True) updated_by = models.CharField(default="N/A", blank=False, max_length=10) project_closed = models.BooleanField(default=False) class Network(models.Model): network_number = models.CharField(unique=True, null=False, max_length=25) date_created = models.DateField(auto_now_add=True) created_by = models.CharField(default="N/A", blank=False, max_length=10) date_updated = models.DateField(auto_now=True) updated_by = models.CharField(default="N/A", blank=False, max_length=10) estimated_completion_date = models.DateField(null=True) network_completion = models.BooleanField(default=False) class Project_Network(models.Model): project_id = models.ForeignKey(Project, related_name="project", on_delete=models.CASCADE) network_id = models.OneToOneField(Network, related_name="networks", on_delete=models.CASCADE) class Part(models.Model): part_number = models.AutoField(primary_key=True) part_category = models.CharField( null=False, blank=False, max_length=9, choices=[ ('A', 'A'), ('B', 'B'), ('C', 'C'), ] ) class Network_Part(models.Model): network_id = models.ForeignKey(Network, related_name="parts", on_delete=models.CASCADE) part_number = models.ForeignKey(Part, on_delete=models.CASCADE) part_quantity = models.IntegerField(default=0) equipment_code = models.CharField(max_length=50) This is the way these modals fit together: Project Model - holds project information (highest level of info) Network Model - a Project can have multiple networks associated with it (think of Networks as sub projects) Project_Network Model - the relationship between Projects and Networks. A Project can have multiple networks associated with it, however a Network can only be associated with One Project (hence the One-To-One Field) Part Model - a set list of parts which can be … -
How to access JavaScript element style from styles.CSS, Django
I have this JavaScript code that does createElement, but how can I style it from my separate CSS file? JavaScript emails.forEach(function(email) { const element = document.createElement('div'); element.innerHTML = email.sender + ' ' + email.subject + ' ' + email.timestamp document.querySelector('#email-container').append(element); }); HTML <div id="email-container"> </div> CSS #email-container .element{ border-width:2px; border-style:solid; border-color:black; } -
Search Nested Fields on Elasticsearch DSL DRF
This is document.py @chapter_index.doc_type class ChapterDocument(Document): subject = fields.ObjectField(properties={ 'name': fields.TextField(), 'description': fields.TextField() }) topics = fields.NestedField(properties={ 'name': fields.TextField(), 'description': fields.TextField(analyzer=html_strip), 'duration': fields.IntegerField() }) class Django: model = Chapter fields = [ 'name', 'description', 'order_no' ] related_models = [Subject, Topic] def get_queryset(self): return super(ChapterDocument, self).get_queryset().select_related( 'subject' ) def get_instances_from_related(self, related_instance): if isinstance(related_instance, Subject): return related_instance.chapters.all() if isinstance(related_instance, Topic): return related_instance.chapter This is DocumentViewSet class ChapterSearchViewSet(DocumentViewSet): document = ChapterDocument serializer_class = ChapterDocumentSerializer filter_backends = [ SearchFilterBackend, ] search_fields = ( 'subject.name', 'subject.description', 'name', 'description', ) search_nested_fields = { 'topics': ['description'] } search_fields is working. When I want to search on NestedField, search_nested_fields is not working. I'm getting errors like this. This is coming from 'topics': ['description'] in search_nested_fields. Indexing is working. I want to search chapter by topic description. Maybe I'm using the wrong format in the search_nested_fields. I followed elasticsearch-dsl-drf documentation. But getting this error! -
how to add custom placeholder into widgets in form builder in wagtail
I'm trying to add a custom placeholder to each Input elements in the form to be as the element name for example, if the element name is last name the placeholder should be : placeholder: last name my question here is how to get each element name by itself from the function get_form() I tried to get each element name by accessing django forms self.field from inside get_forms() This is my form model: from django.db import models from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel ) from wagtail.core.fields import RichTextField from wagtail.contrib.forms.models import ( AbstractEmailForm, AbstractFormField ) from wagtail.images.edit_handlers import ImageChooserPanel from django.forms import widgets class FormField(AbstractFormField): page = ParentalKey( 'ContactPage', on_delete=models.CASCADE, related_name='form_fields', ) class ContactPage(AbstractEmailForm): template = "contact/contact_us.html" # This is the default path. # If ignored, Wagtail adds _landing.html to your template name landing_page_template = "contact/contact_us_landing.html" banner_image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, blank=True, null=True, related_name='+', ) description = models.TextField(blank=True, null=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ ImageChooserPanel('banner_image'), FieldPanel('description'), InlinePanel('form_fields', label='Form Fields'), FieldPanel('thank_you_text'), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel("subject"), ], heading="Email Settings"), ] def get_form(self, *args, **kwargs): form = super().get_form(*args, **kwargs) # iterate through the fields in the generated form for name, … -
Django, unit test not working: reverse for xxx is not found. xxx is not a valid view function or pattern name
I understand there are a few questions like this on stack overflow, but none of them seem to answer my issue. I am trying to run a unit test on my pages in the project, but I keep getting this issue: "Reverse for 'page1' not found. 'page1' is not a valid view function or pattern name." 'page1' works fine when I run it with python manage.py runserver, but when I run python manage.py test it fails. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.displaylol), path('page1', views.page1), path('empty', views.empty), ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Tag # Create your views here. def displaylol(request): return HttpResponse("Home page") def page1(request): tags = Tag.objects.all() return render(request, 'ecommerce/page1.html', {'tags': tags}) def empty(request): return HttpResponse("empty") ecommerce/page1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Product 1</title> </head> <body> <h1>Tags</h1> <table border="1"> <thead> <tr> <th>Tag</th> <th>Connections</th> <th>No. of products attached to</th> <th>Idk</th> </tr> </thead> <tbody> {% for tag in tags %} <tr> <td> {{ tag.name }}<br> <small style="color: #888">ID: {{ tag.ID }}</small> </td> <td>0</td> <td>0</td> <td></td> </tr> {% endfor %} </tbody> </table> </body> </html> tests.py from django.urls import reverse from django.test import TestCase # Create … -
Elasticsearch's ip_range field is not available in django-elasticsearch-dsl. Is there any way to subclass elasticsearch-dsl's IpRange?
How can one use the ip_range field type for CIDR notated IP addresses with django-elasticsearch-dsl? https://www.elastic.co/guide/en/elasticsearch/reference/current/range.html#ip-range I tried making a subclass but it results in a field mapping of "type": "text" ... from django_elasticsearch_dsl.fields import DEDField from elasticsearch_dsl.field import IpRange ... class IpRangeField(DEDField, IpRange): """Subclass based on DedField and IpRange.""" @registry.register_document class FeedDataDocument(Document): """FeedData elasticsearch.""" ... ipaddress = IpRangeField() ... Results in: "mappings": { "_doc": { "properties": { "ipaddress": { "type": "text" ... -
display dynamic Heatmap using FLASK in the browser
I'm trying to display the Heatmap in the browser I have basic knowledge about Django , Flask , Brython. I have 4 wireless node connected to 4 infrared grid eye sensors. I tried to make it as JPG/PNG and update it still not working either Mqtt.py ( publish-subscribe network protocol that transports messages between devices.) import time import paho.mqtt.client as paho class mqttsub(): def __init__(self, topic):#client broker="192.168.0.192" self.topic = topic self.client = paho.Client("client-05") #self.client.username_pw_set(username='priveat',password='Pv_2020@19') self.client.on_message=self.on_message self.data = None #self.client.tls_set() self.client.connect(broker)#connect self.client.loop_start() #start loop to process received messages self.client.subscribe(topic)#subscribe to a topic time.sleep(0.001) self.client.loop_stop() #stop loop def get_data(self): return self.data def on_message(self, client, userdata, message): data=message.payload.decode("utf-8") self.data = data Live.py from mqttsub import mqttsub # to subscribe import seaborn as sb import matplotlib.pyplot as plt # to show and plot the visualization import matplotlib.animation as animation # to animate the visualization import numpy as np list=[["0,0","0,1","0,2","0,3","0,4","0,5","0,6","0,7"], ["1,0","1,1","1,2","1,3","1,4","1,5","1,6","1,7"], ["2,0","2,1","2,2","2,3","2,4","2,5","2,6","2,7"], ["3,0","3,1","3,2","3,3","3,4","3,5","3,6","3,7"], ["4,0","4,1","4,2","4,3","4,4","4,5","4,6","4,7"], ["5,0","5,1","5,2","5,3","5,4","5,5","5,6","5,7"], ["6,0","6,1","6,2","6,3","6,4","6,5","6,6","6,7"], ["7,0","7,1","7,2","7,3","7,4","7,5","7,6","7,7"]] def animate(i): try: subs1 = mqttsub("/node1/grideye/matrix") data1= eval(subs1.get_data()) #normalize the data norm = np.linalg.norm(data1[0]) normal_array = data1[0]/norm data1[0]=normal_array norm = np.linalg.norm(data1[1]) normal_array = data1[1]/norm data1[1]=normal_array norm = np.linalg.norm(data1[2]) normal_array = data1[2]/norm data1[2]=normal_array norm = np.linalg.norm(data1[3]) normal_array = data1[3]/norm data1[3]=normal_array norm = np.linalg.norm(data1[4]) normal_array = data1[4]/norm data1[4]=normal_array norm = … -
Issue with Pyinstaller when try create executable from django app
I am trying to create an executable from django rest framework app with pyinstaller. But when I run pyinstaller I get this errors: Traceback (most recent call last): File "<string>", line 21, in walk_packages File "c:\users\sebac\envs\myapp\lib\site-packages\rest_framework\schemas\__init__.py", line 25, in <module> from . import coreapi, openapi File "c:\users\sebac\envs\myapp\lib\site-packages\rest_framework\schemas\openapi.py", line 15, in <module> from rest_framework import ( File "c:\users\sebac\envs\myapp\lib\site-packages\rest_framework\renderers.py", line 53, in <module> class JSONRenderer(BaseRenderer): File "c:\users\sebac\envs\myapp\lib\site-packages\rest_framework\renderers.py", line 60, in JSONRenderer ensure_ascii = not api_settings.UNICODE_JSON File "c:\users\sebac\envs\myapp\lib\site-packages\rest_framework\settings.py", line 218, in __getattr__ val = self.user_settings[attr] File "c:\users\sebac\envs\myapp\lib\site-packages\rest_framework\settings.py", line 209, in user_settings self._user_settings = getattr(settings, 'REST_FRAMEWORK', {}) File "c:\users\sebac\envs\myapp\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "c:\users\sebac\envs\myapp\lib\site-packages\django\conf\__init__.py", line 60, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. collect_submodules: failed to import 'rest_framework.schemas'! -
Cannot dynamically save user.is_active in Django UpdateView form_valid, or signal
I have two models, User(extends Abstract User and inherits is_active field) and Supervision connected to User with Generic Foreign Key. When we save an instance of Supervision, the code must check the suspended field on the Supervision instance and update user.is_active to contrary. I am failing to save save the user instance, as it reverts back to True and saves twice. Here is my code from form_valid(): suspension, created = Suspension.objects.get_or_create( content_type = ContentType.objects.get(app_label="myapp", model="suspension"), object_id = self.kwargs['pk'], ) suspension.reason = form.cleaned_data['reason'] suspension.suspended = form.cleaned_data['suspended'] suspension.save() user = suspension.content_object user.is_active = False if suspension.suspended else True user.save() Here is my signal: @receiver(post_save, sender=Suspension, weak=False, dispatch_uid=uuid.uuid4()) def suspend_unsuspend_user(sender, instance, **kwargs): from userprofile.models import User if isinstance(instance.content_object, User): user = instance.content_object user.is_active = instance.suspended user.save() While implementing them separately, I get the user instance saved twice and every time user.is_active reverted back to True and saved (i.e. a post_save signal on User instance prints it twice, always True in the end). I have checked my code, I do not touch user.is_active anywhere else. Also I can can change is_active from admin or shell. What is wrong? -
Problem with i18n urls where I'm redirected to the right url but the template is not found
I read on the documentation page of i18n the following: Warning Ensure that you don’t have non-prefixed URL patterns that might collide with an automatically-dded language prefix. I don't get this warning at all, what's the meaning of it?? I'm actually having a problem where I'm directed to my en/sitepages/news-events-listing or ar/sitepages/news-events-listing by a url defined like this in the root urls.py: urlpatterns += i18n_patterns( path("sitepages/", include("sitepages.urls")), ) but the template returned by the view inside sitepages/views.py: def sitepages_view(request): template = loader.get_template('sitepages/news_events_page_listing.html') context = { 'news_pages': NewsDetails.objects.all(), 'events_pages': EventsDetails.objects.all(), 'listing_page': NewsEventsListing.objects.first(), } return HttpResponse(template.render(context, request)) and the sitepages/urls.py: app_name = "sitepages" urlpatterns = [ path("news-events-listing/", sitepages_view, name='listing'), ] I can't think of anything but this warning, and that I might need to understand it to solve the problem, although I know that the order of urls in the root urls.py matter, so I might include it if anyone's think it might cause the problem but I don't want to make the question too long Note: if I replace the HttpResponse with a simple one like this HttpResponse('Hi') it works! -
Django Middleware to log every time a user hits a page
As the title states I am trying to create a middleware that will record every time a user hits a page. Here's my model.py I'll be working with: class UserPageTracking(models.Model): """ Page hits with user info """ id = models.AutoField(db_column='ID', primary_key=True) user_id = models.CharField(db_column='USER_ID', max_length=8, default="") url = models.URLField(db_column='URL') date_visited = models.DateTimeField(db_column='DATE_VISITED', auto_now_add=True) class Meta: managed = True db_table = 'page_views' Here's what's in my middleware: from .models import UserPageTracking class UserPageTrackingMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user_id = request.user.username # not every request will have a http_referer, so when it doesn't just ignore it and don't save anything to_url = request.META.get('HTTP_REFERER') if to_url: user_page_tracking = UserPageTracking.objects.create( url=to_url, user_id=user_id ) user_page_tracking.save() return response This works alright the only issue is every time I load a page/go to a page it'll hit this middleware multiple times (at least twice, sometimes like 3 or 4). When I check the db I'll have 3 - 4 entries that are a about 40 - 50 ms apart from each other. Am I doing something wrong, or is this something I can't do via middleware and I have to do something else to log user activity. -
Get the Model of a OneToOne
I need to get the Model of a OneToOne related model: class ModelA(models.Model): name = models.CharField(...) class ModelB(models.Model): target = models.OneToOneField( ModelA, related_name="model_a", ...) When I use an instance of ModelB to get the class of its target field with: modelb_instance.model_a._meta.model I get an error: ForwardOneToOneDescriptor' object has no attribute '_meta' I am aware that this cannot be done on OneToOne attribute, but I am not sure how to retrieve ModelA model name. Any help would be appreciated -
Setup websockets with Python/Django
Is there some way I could setup my architecture like this for my web application: Backend - Django + DRF (Rest API) Frontend - React And on the backend setup a websocket Client to listen to an external websocket Server and then forward the data from the Client to a new Server that I will create. So in React I could listen to this websocket Server that I have created? I tried implementing this in React to listen to an external websocket Server, but it just gave me headaches trying to use proxy to avoid CORS problems. How should I approach this? Am I thinking straight here? -
How to validate data in html login form with database?
I'm new to Django but read of lot of codes and intermediate in python. I'm confused on how to validata data from login post with database and then redirecting to the user URL. Does the default user authentication if I register things on admin? Help in this thing? -
How to approach file uploads for different models in Django?
Using Django 3 & Python3. What is the right way / best practice to implement this: Say I have 2 models Project and Task like this: class Project(models.Model): name = models.CharField(max_length=120) class Task(models.Model): name = models.CharField(max_length=120) And I need to be able to upload documents 'attached' to any of both models. I am doing: class BaseDocument(models.Model): name = models.CharField(max_length=80) document_date = models.DateField() def __str__(self): return self.slug class Meta: abstract = True class ProjectImage(BaseDocument): image = models.ImageField(upload_to='images/', blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_images', blank=True, null=True) class ProjectDocument(BaseDocument): raw_file = models.FileField( upload_to='raw/', blank=True, storage=RawMediaCloudinaryStorage() ) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_documents', blank=True, null=True) class TaskImage(BaseDocument): image = models.ImageField(upload_to='images/', blank=True) project = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='task_images', blank=True, null=True) class TaskDocument(BaseDocument): raw_file = models.FileField( upload_to='raw/', blank=True, storage=RawMediaCloudinaryStorage() ) project = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='task_documents', blank=True, null=True) And then creating urls, forms, CBVs for all the models. This seems inefficient and not very DRY. The question basically is what is the right approach to implement a functionality like this so that the user is able to upload documents to different models. I've been trying to implement a solution using contenttypes and GenericRelations (anticipating that I may need to attach images to other models in the future) with no … -
How to send PDF UL from Django Weasyprint view to display it in HTML Custom
I want to display PDF files in HTML using a custom PDF Viewer (PDFTron Webviewr) I'm using WeasyTemplateResponseMixin in my view to convert HTML to PDF and send it to the client-side. but I don't want the PDF to be rendered, I want to access the PDF URL in the JS function so i can display it Is there any of doing that without saving the PDF just sending it? This the view: class BarcodePrint(WeasyTemplateResponseMixin, BarcodePrintView): pdf_stylesheets = [ settings.STATIC_ROOT + '/main.css', ] template_name = 'barcode_print.html' and this is the JS code: generateWebViewr(file){ WebViewer({ path: '../../../static/webviewer', initialDoc: file , }, document.getElementById('viewer')).then(instance => { const { docViewer } = instance; docViewer.on('documentLoaded', () => { instance.print(); }); }); } Thank you! -
Django throws AttributeError: 'str' object has no attribute '_meta' when I register my Model
Im novice and I didnt find solution for problem here. Im writing code for blog. I have a model Post where I want to create field author which is ForeighKey to User. If I make migration without admin.site.register - everything is ok. But then Im trying to register my Model to Django admin it throws AttributeError: 'str' object has no attribute '_meta' Comment: my idea is that every user (after registration) can create post. And I want to show some inforamtion about author using User model models.py from django.db import models from django.contrib.auth import get_user_model class Post(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, verbose_name='Автор', related_name='posts', null=True) title = models.CharField(verbose_name='Заголовок объявления', max_length=255) text = models.TextField(verbose_name='Текст объявления') CATEGORIES = ( ('T','Танки'), ('HM','Хилы'), ('DD','ДД'), ('TrM','Торговцы'), ('GM','Гилдмастеры'), ('QG','Квестгиверы'), ('FM','Кузнецы'), ('LM','Кожевники'), ('PM','Зельевары'), ('WM','Мастера заклинаний') ) category = models.CharField(verbose_name='Категория', max_length=3, choices=CATEGORIES) pub_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') class Meta: verbose_name = 'Пост' verbose_name_plural = 'Посты' def __str__(self): return self.title admin.py from django.contrib import admin admin.site.register('Post') -
Django, use annotated field or SQL function in Case & When
I'm trying to do a query where I use an average of a column against its latest value and then use it in Case and When. I can successfully annotate the monthly average and latest field but not compare them in the DB: this is the direction of what I'm trying to do latest_known_kpi_obj = KPIs.objects.filter(tag_count__isnull=False, group__id=OuterRef(ID)) tag_count_of_latest = Subquery(latest_known_kpi_obj.values(ASSIGNED_TAG_COUNT)[:1]) places_count_of_latest = Subquery(latest_known_kpi_obj.values(PLACES_COUNT)[:1]) user = self.request.user self.kpis = user.user_selected_kpis.get_all_kpis_qs() kpis_monthly_averages_annotations = {} latest_kpis = {} for kpi in self.kpis: latest_kpis[f'{kpi.internal_name}_latest'] = Subquery(latest_known_kpi_obj.values(kpi.internal_name)[:1]) kpis_monthly_averages_annotations[f'{kpi.internal_name}_trend'] = Case( When(condition=Avg(f'farm_scores__{kpi.internal_name}', filter=Q(farm_scores__date__range=month_range)) < (latest_kpis[f'{kpi.internal_name}_latest']), then=1), When(Avg(f'farm_scores__{kpi.internal_name}', filter=Q(farm_scores__date__range=month_range)) > (latest_kpis[f'{kpi.internal_name}_latest']), then=-1), default=0 ) query_set = (Group.objects.filter(**filters). annotate(**kpis_monthly_averages_annotations,**latest_kpis) this is not possible '<' not supported between instances of 'Avg' and 'Subquery'