Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango can't execute an empty query
Im not so familiar with sql command, my sql command comes from csv file and it's all good. Im using multi database in django but I got an error : django.db.utils.ProgrammingError: can't execute an empty query. I also tried this solution but not working can't execute an empty query . Please help me on this.Thank You! Here's my csv file: Name sql James SELECT value AS id from test WHERE name ='James' AND age ='10' AND grade ='80' Ice SELECT value AS id from test WHERE name ='Ice' AND age ='14' AND grade ='85' Mike SELECT value AS id from test WHERE name ='Mike' AND age ='11' AND grade ='88' and more and more query here........ def filter(request): field = {"James","Mike"} number={3265826,61894965} df = pd.read_csv('/pathtofile/grade.csv') for name in field: data = df[df['Name'] == name] sql = data['sql'].values[0] query = sql + ' AND Number =' + "'"+ number +"'" sqldata = test.objects.using("database2").raw(query) cursor = connection.cursor() cursor.execute(sqldata) row = cursor.fetchall() -
PyJWT cant find module with import jwt
after the installation of the PyJWT 2.4.0 i can't import the module jwt it shows me "Import could not be resolved import jwt import datetime from django.conf import settings def generate_access_token(user): payload = { 'user_id':user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat' : datetime.datetime.utcnow() } return jwt.encode(payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') -
passing session in forms.py in django
I'm working on django project, in which I'm using model as form to generate an image upload page. The problem is there's a foreign key referring to user's profile table which fetches a list of users in a drop down menu. I figured i need to use the session value from logged in user but so far I haven't been able to pass the session through forms. Of course, I've tried couple of solutions found on similar questions but those options didn't work for me here's the code: forms : class ImageForm(forms.ModelForm): class Meta: model = ImageMedia fields = ['id', 'Image', 'ImageTitle', 'ImageContext', 'Uploader'] labels = {'Image' : 'Select Image', 'Image Context' : 'Image Context'} Models : class ImageMedia(models.Model): id = models.AutoField(primary_key = True) Image = models.ImageField(verbose_name="Image Name", upload_to = "ImageSet") UploadDate = models.DateTimeField(verbose_name="Date and time uploaded", auto_now_add=True) Uploader = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=False) ImageTitle = models.CharField(verbose_name="Image Title", null=False, max_length=100) ImageContext = models.CharField(verbose_name="Image Context", max_length=500, null=True) def __str__(self): return self.ImageTitle upload template <body> <div class="container"> <center><div class="card" style="width: 28rem;"> <div class="py-5 text-center bg-secondary text-white"> <div class="card-header"> <h1 class="mb-3">Upload Image</h1> </div> <form name="UploadForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% comment %} {{form.Image}} {{form.ImageTitle}} {{form.Uploader.as_hidden}} {{form.ImageContext}} {% endcomment %} {{form.as_p}} <input type="submit" id="submit" … -
Best way to convert Django ORM query to GraphQL
So I have this webapp, that the frontend side allows the user to build dashboards which in-turn create a GraphQL query. This query is sent the the Backend (Django) and all the backend does is route this request to some external DB that handles the GraphQL and returns a response. The issue: I have a complex logic in the backend, that knows how to create a Django ORM query (Q) per each request, which I would like to combine with the GraphQL query. Basically im trying to convert a Django Q (django.db.models.query_utils.Q) into a GraphQL filter section. Is there a way to do it? Maybe with a different generic lang than GraphQL? or Do I have to resort to write something myself -
Submitting Bulk Forms In Django
I have 5 different forms in forms.py; the forms are all based off of 1 model. The 5 forms are all displayed on the same html page, so as to allow the user to create or register 5 objects into the DB with 1 single button click. In the future, I might need to submit 50 forms in a single click. If I were to do this based on the existing code, I would probably need 50 forms in forms.py and repeat the registration logic in views.py for 50 times. Is there a more efficient way to do this? views.py def register(request): form1 = DetailsForm1() form2 = DetailsForm2() form3 = DetailsForm3() form4 = DetailsForm4() form5 = DetailsForm5() if request.method == "POST": form1 = DetailsForm1(request.POST) if form1.is_valid(): form1.save() form2 = DetailsForm2(request.POST) if form2.is_valid(): form2.save() form3 = DetailsForm3(request.POST) if form3.is_valid(): form3.save() form4 = DetailsForm3(request.POST) if form3.is_valid(): form3.save() form5 = DetailsForm5(request.POST) if form5.is_valid(): form5.save() return render(request, "app/registration_completed.html") context = { "form1": form1, "form2": form2, "form3": form3, "form4": form4, "form5": form5 } return render(request, "app/register.html", context) forms.py class DetailsForm1(forms.ModelForm): class Meta: model = Property fields = ( 'owner', 'address', 'postcode', ) class DetailsForm2(forms.ModelForm): class Meta: model = Property fields = ( 'owner', 'address', 'postcode', … -
Web API that itself sends data to client on availability
I am currently working with Django but I am stuck as I don't know if I am pursuing the right model given the nature of my application. Problem Statement: I have to make a REST API for a client such that whenever I get a trigger for a new entry/entries in my Database I have to send those to the client which is supposed to listen to a URL and has asked for data only once and now is open to receive data whenever available to him. It is not sending a GET request now and then. There will be different endpoints of the APIs. One is where I provide him all the new data available to me and in other where it asks for specific data (ex: '/myAPI/givemethis') I can easily implement the second requirement as it is a simple request-response case. I am not sure how to send him data that too on availability without him making a repeated request as client. It appears a Publisher-Subscriber model is better suited for my use case but I don't know how to implement it on Django. I bumped into several concepts like StreamingServices and MQTT but I am not sure … -
Django statics returns 404 error in cPanel Passenger
I used cPanel and deployed a Django application on my server using passenger_wsgi.py. The problem is when I'm trying to access static files (like admin CSS file: static/admin/css/base.css) I'm facing with 404 error. I've already done collectstatic and added PassengerPathInfoFix method to passenger_wsgi.py file but the output log is Not Found: /home/mysite/public_html/static/admin/css/base.css even though the outputted path exists and I can edit it using vim. My settings.py: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Any help would be appreciated. -
Django rest framework URL pattern of CRUD operation in single GenericAPIView class
I have been creating a class view with GenericAPIView in the Django rest framework. and define their URLs but on Django swagger, every URL shows all methods. #views.py class AmenitiesView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView): serializer_class = AmenitiesSerializer queryset = Amenities.objects.all() def get(self, request, *args, **kwargs): many, queryset = True, self.filter_queryset(self.get_queryset()) if 'pk' in kwargs and kwargs['pk']: many, queryset = False, self.get_object() serializer = self.get_serializer(queryset, many=many) return Response({"data": serializer.data, "message": "Successfully Get Amenities", "isSuccess": True, "status": 200}, status=200) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) #urls.py urlpatterns = [ path('amenities/get/', AmenitiesView.as_view()), path('amenities/get/<int:pk>/', AmenitiesView.as_view()), path('amenities/create/', AmenitiesView.as_view()), path('amenities/edit/<int:pk>/', AmenitiesView.as_view()), path('amenities/delete/<int:pk>/', AmenitiesView.as_view()), ] how to define URL with the method, like if 'amenities/get/' is URL so on swagger will show only get method and if URL is 'amenities/create/' so only post method shown on this url. -
subprocess.call() doesn't throw and error when file is not found
I'm trying to run a python script from a Django web service and I'm using the subprocess.call() method and I've put it in a try except block because I need to get the error when something is wrong. I discovered that when the path to the script is not valid is not raising an error it's only displaying it on the console, but I need it to be thrown so I can catch it in the except block. Here is my code. try: row = exec_SQL(f"SELECT [ID], [ProjectPath], [MainFileName] FROM [dbo].[WebserviceInfo] WHERE ProjectName='{project}'") command = f'python {row[1]}\{row[2]} {model} {scenario}' subprocess.call(command, shell=True) except Exception as e: error_message = str(e) This is the path to the file + some arguments that I need. f'python {row[1]}\{row[2]} {model} {scenario} Thanks in advance for your help. -
App runs locally but crashes when deployed to Heroku
My Python Flask app runs locally but when I deploy it to Heroku it successfully builds but crashes when opening the app. I'm relatively comfortable with Python but new to web dev and Heroku etc. Here's my Procfile web: gunicorn app:app From my limited understanding my Procfile is correct(?) as it's telling Heroku to run my app.py file which is what I run when running the app locally. Logs 2022-07-14T09:08:18.969324+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/werkzeug/serving.py", line 740, in __init__ 2022-07-14T09:08:18.969325+00:00 app[web.1]: HTTPServer.__init__(self, server_address, handler) 2022-07-14T09:08:18.969325+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/socketserver.py", line 452, in __init__ 2022-07-14T09:08:18.969325+00:00 app[web.1]: self.server_bind() 2022-07-14T09:08:18.969325+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/http/server.py", line 136, in server_bind 2022-07-14T09:08:18.969325+00:00 app[web.1]: socketserver.TCPServer.server_bind(self) 2022-07-14T09:08:18.969326+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/socketserver.py", line 466, in server_bind 2022-07-14T09:08:18.969326+00:00 app[web.1]: self.socket.bind(self.server_address) 2022-07-14T09:08:18.969326+00:00 app[web.1]: OSError: [Errno 98] Address already in use 2022-07-14T09:08:18.969552+00:00 app[web.1]: [2022-07-14 09:08:18 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-07-14T09:08:33.000000+00:00 app[api]: Build succeeded 2022-07-14T09:08:49.139858+00:00 app[web.1]: [2022-07-14 09:08:49 +0000] [4] [INFO] Shutting down: Master 2022-07-14T09:08:49.139897+00:00 app[web.1]: [2022-07-14 09:08:49 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-07-14T09:08:49.288295+00:00 heroku[web.1]: Process exited with status 3 2022-07-14T09:08:49.375710+00:00 heroku[web.1]: State changed from up to crashed 2022-07-14T09:08:49.378964+00:00 heroku[web.1]: State changed from crashed to starting 2022-07-14T09:08:59.395728+00:00 heroku[web.1]: Starting process with command `gunicorn app:app` 2022-07-14T09:09:00.585739+00:00 app[web.1]: [2022-07-14 09:09:00 +0000] [4] [INFO] Starting … -
Django Rest Framework Custom Permission not taking effect
I have a permissions.py file that holds a custom permission called CanViewUserRecord. I have assigned this to a viewset called UserRecordView. The permission isn't working though, whenever I call the endpoint attached to the viewset all of the data from the database is returned. Here is the custom permission code: from accounts.models import Staff class CanViewUserRecord(permissions.BasePermission): edit_methods = ("PUT", "PATCH") def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: if obj.account_type == "staff": # If user is the manager of staff if obj.staff.manager == request.user.id: return True # If the user is the owner if obj == request.user: return True # Allow admins to access if request.user.account_type == "admin": return True return False elif obj.account_type == "manager": # If the user is the owner if obj == request.user: return True # Allow Admins to access if request.user.account_type == "admin": return True return False elif obj.account_type == "admin": # If the user is the owner if obj == request.user: return True # Allow Admins to access if request.user.account_type == "admin": return True return False else: return False elif request.method in self.edit_methods: if obj.account_type == "staff": if ( request.user.account_type == "manager" or request.user.account_type == "admin" ): return True else: return False elif … -
Blog API with DRF getting Anonymous User Error
I am creating a BlogAPI with LoginAPI(using dj-rest-auth). I have created a model for my Post- models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): content = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) Then I have made 2 serializers User and Post - serializers.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Post class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'id', 'email'] class PostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Post fields = ['user', 'content'] My view looks like this- views.py from rest_framework import viewsets, permissions from .serializers import UserSerializer, PostSerializer, CommentSerializer from . import models from rest_framework.response import Response from rest_framework.decorators import action, api_view, permission_classes class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer class PostViewSet(viewsets.ModelViewSet): queryset = models.Post.objects.all() serializer_class = PostSerializer permission_classes = [permissions.AllowAny] def create(self, request): serializer = PostSerializer( data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) print(request.data) print(request.user) serializer.save(user=request.user) return Response(serializer.data) I have kept the permissions_class as AllowAny because then I was not able to test the API. urls.py(inside app) router = routers.DefaultRouter() router.register(r'^users', views.UserViewSet) router.register(r'^posts', views.PostViewSet) urlpatterns = [ path('', include(router.urls)), re_path(r'^posts/(?P<pk>\d+)/comments/$', view=views.PostViewSet.as_view({'get': 'comments', 'post': 'comments'})), re_path(r'^posts/(?P<pk>\d+)/comments/(?P<comment>\d+)/$', view=views.PostViewSet.as_view({'delete': 'remove_comment'})) ] After running it on locahost on http://127.0.0.1:8000/posts/ I am able to do … -
Check if the data in json file exit in django models
I want to check if the data in json file exit in django models table For example: In models.py table called activity in that table different fields are there Such as activity_name , activity_status I want to check the activity names in json file exit or not If exit print true or if not false Plese help me -
How to solve celery 'Not Registered' Exception
dev env django = 3.2.4 celery = 5.2.3 redis I use Celery to asynchronously process. I'm using it for email transmission and AI Inference functions, but @sharedtask applied to email works well without any problems. However, the AI Inference function is different. Once successful and then the same action is performed, the 'Not registered' Exception is displayed. Why does this happen? The success and failure of the same task are shown below. enter image description here -
Got an unexpected keyword argument 'pzn'
I'm struggling with following problem: fachbereich_detailview() got an unexpected keyword argument 'pzn' The error tells me that there is something wrong with my urls. If I change the last part of the url to int:test, it tells me that the unexpected keyword argument is test. The query 'product = Products.objects.get(pzn="existingpzn")' is working fine (Tested with shell). view.py: [...] def fachbereich_detailview(request, pzn): context = {} try: product = Products.objects.get(pzn=pzn) except: return redirect('fachbereich') context['product'] = product return render(request, 'app/LoginArea/fachbereich_detailview.html', context) [...] urls.py: [...] path('Produkt/<int:pzn>/', views.fachbereich_detailview, name='fachbereich_detailview'), [...] html: <a href="{% url 'fachbereich_detailview' product.pzn %}" class="small-text text-underline text-uppercase">Mehr erfahren</a> I just can't figure out what the problem is. I hope that someone is able to help me! Thank you in advance Nader -
When to use Django instead of Streamlit
We are devloping various web applications for design and optimization of energy infrastructure. We have been working in Django for some time now. I just became aware of Streamlit. I believe it is pretty easy to use. So my question: Why would you use Django instead of Streamlit? Streamlit seems much less complicated. Thanks. -
hello. I'm learning django. I downloaded small project from git hub and problem is intalling requrement.txt
how can i install requirement.txt? created project with different virtual environment(pipenv and venv) but in the end Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\User\AppData\Local\Temp\pip-install-x_oh84s8\django-localized-names_d98dfe1d2720418d895d5cf15016e5dd\setup.py", line 17, in <module> long_description=read('README.rst'), File "C:\Users\User\AppData\Local\Temp\pip-install-x_oh84s8\django-localized-names_d98dfe1d2720418d895d5cf15016e5dd\setup.py", line 8, in read return open(os.path.join(os.path.dirname(__file__), fname)).read() File "C:\Python39\lib\encodings\cp1251.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 2468: character maps to <undefined> [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. how can I fix it please? -
Combining javascript search with dropdown filter
I have a working code with a live javascript search where I can search in a table for a user by either their first and last name or one of them. I also have a working dropdown filter, where you can choose a rank, which will only show the users with that specific rank. The problem is, they don't combine --> If I do a search and then select the rank, it shows all users with that rank, and it doesn't use the search. It also doesn't work the other way. Does anyone have an idea how I can combine the two filters? I work in Django, so my java and HTML are on the same page. I left out the sort function because it's not relevant for my question. Here a pic of how it looks: How it looks right now HTML: {% extends 'puma_core/layouts/navbar.html' %} {% load static %} {% block content %} <div class="container mt-5"> <div class="mb-4"> <div> <div class="row"> <div class="col-8"> <h1> Gebruikers {{ peloton }} </h1> </div> <div class="col position-relative mt-sm-2 me-3"> <a class="btn btn-secondary btn-sm position-absolute end-0" href="{% url 'peloton' peloton.id %}" role="button"> Terug </a> </div> </div> </div> </div> <input id="userInput" placeholder="Zoek een gebruiker..." … -
DJango ProgrammingError: can't execute an empty query
My sql command are inside csv file after that I read and forloop each row, SQL command are printout like this also Im using multi database. SELECT value AS id from test_table WHERE name ='James' AND age ='10' AND gender ='male' AND number ='205485' But if I execute the sql I got an error django.db.utils.ProgrammingError: can't execute an empty query Here's my code: @api_view(['GET']) def filter(request): field = {"James","Chris"} number = "205485" df = pd.read_csv('path/to/file/filter.csv') for name in field: data = df[df['Name'] == name] sql = data['sql_query'].values[0] query = sql + ' number =' + "'"+ number +"'" try: data = test_table.objects.using("database_2").raw(query) cursor = connection.cursor() cursor.execute(data) row = cursor.fetchone()[0] finally: cursor.close() -
how to show list of categories in navbar using django framework
hello I want to list my categories in navbar from database but the navbar is a partial view and I included my navbar in base.html . how can i give the data to this navbar -
Unable to use multiple Authentication Classes in Djangorestframework
I have the following permission class: class FirebaseAuthentication(authentication.TokenAuthentication): """ Token based authentication using firebase. """ keyword = "Token" def authenticate_credentials( self, token: str ) -> Tuple[AnonymousUser, Dict]: try: decoded_token = self._decode_token(token) firebase_user = self._authenticate_token(decoded_token) local_user = self._get_or_create_local_user(firebase_user) return (local_user, decoded_token) except Exception as e: raise exceptions.AuthenticationFailed(e) def _decode_token(self, token: str) -> Dict: """ Attempt to verify JWT from Authorization header with Firebase and return the decoded token """ try: token = self.__generate_id_token(token) # appliable only when testing with ID token decoded_token = firebase_auth.verify_id_token( token, check_revoked=True ) log.info(f'_decode_token - decoded_token: {decoded_token}') return decoded_token except Exception as e: log.error(f'_decode_token - Exception: {e}') raise Exception(e) def _authenticate_token( self, decoded_token: Dict ) -> firebase_auth.UserRecord: """ Returns firebase user if token is authenticated """ try: uid = decoded_token.get('uid') log.info(f'_authenticate_token - uid: {uid}') firebase_user = firebase_auth.get_user(uid) log.info(f'_authenticate_token - firebase_user: {firebase_user}') if not firebase_user.email_verified: raise Exception( 'Email address of this user has not been verified.' ) return firebase_user except Exception as e: log.error(f'_authenticate_token - Exception: {e}') raise Exception(e) def __generate_id_token(self, token: str) -> str: """ Follow """ id_token_endpoint = ( "https://identitytoolkit.googleapis.com/v1/accounts" ":signInWithCustomToken?key={api_key}" ) url = id_token_endpoint.format( api_key="AIzaSyCurgq3Cn_3UzaPerWkhuHe8omS_RlIQTU" ) data = {"token": token, "returnSecureToken": True} res = requests.post(url, data=data) time.sleep(5) # Sleep for 5 seconds to avoid exception … -
limiting __in lookup in django
i have are question about "__in" lookup in Django ORM. So here is the example of code: tags = [Tag.objects.get(name="sometag")] servers = Server.objects.filter(tags__in=tags)[offset_from:offset_to] server_infos = [] for server in servers: server_infos.append(query.last()) So here is the problem: we making about 60-70 sql requests for each server. But i want to do something like this: tags = [Tag.objects.get(name="sometag")] servers = Server.objects.filter(tags__in=tags)[offset_from:offset_to] server_infos = ServerInfo.objects.filter(contains__in=servers) assert servers.count() == server_infos.count() Can i do this without raw sql request? All i need to understand is how to limit "__in" expression in Django to get only last value as in example above. Is it possible? -
VariableDoesNotExist at /blog/blog_posts/ Failed lookup for key [categories] in [{'True': True, 'False': False, 'None': None}, {}, {},
I trying to create categories with MPTT and I get this error: eVariableDoesNotExist at /blog/blog_posts/Failed lookup for key [categories] in `enter code here`[{'True': True, 'False': False, 'None': None}, {}, {}, I know that I have to pass the queryset from views.py to my template and its still does not work. views.py class BlogCategoriesList(generic.ListView): model = Category template_name = 'blog/blog_categories_list.html' def get_queryset(self): content = { 'categories': Category.objects.all() } return content models.py class Category(MPTTModel): name = models.CharField(max_length=100, null=True,default=None) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] verbose_name_plural = 'Categories' def get_absolute_url(self): return reverse('blog:category_details_view', args=[str(self.slug)]) def __str__(self): return self.name class Post(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') options = (('draft','Draft'),('published','Published'),) title = models.CharField(max_length=300,null=True) category = TreeForeignKey(Category, on_delete=models.PROTECT, null=True, blank=True, default=None) excerpt = RichTextField(blank=True,max_length=30000,null=True) slug = models.SlugField(max_length=300, unique_for_date='published',null=True) featured_image = models.ImageField(upload_to='media/blog_featured_images', null=True) published = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts',null=True) content = RichTextField(blank=True,null=True) status = models.CharField(max_length=10, choices=options, default='draft',null=True) objects = models.Manager() newmanager = NewManager() def get_absolute_url(self): return reverse('blog:single_post', args=[self.slug]) class Meta: ordering = ('-published',) verbose_name_plural = 'Posts' unique_together = ('title','slug') def __str__(self): return self.title blog_category_list.html {% block content %} {% load mptt_tags %} <ul> {% recursetree categories %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ … -
xhtml2pdf not show the personal font, i don't understand how i should import my font
I need to create a pdf and I need my own font which is present in static / font / I just don't understand how to import it. the font always remains the same and I don't know how to do it, can someone help me? I used: http://127.0.0.1:8000/static/font/titolo.ttf /static/font/titolo.ttf {% static 'font/titolo.ttf' %} but not work, how should i import my font for it to work correctly? css <style> @font-face { font-family: "Titolo"; src: url('/static/font/titolo.ttf'); } @page { size: A4 portrait; @frame header_frame{ -pdf-frame-content: header; top: 10mm; width: 210mm; margin: 0 10mm; } @frame content_frame{ width: 210mm; top: 40mm; margin: 0 10mm; } @frame footer_frame{ -pdf-frame-content: footer; top: 276mm; width: 220mm; margin: 0 10mm; } } h1 {font-size: 4rem; margin-bottom: 0; font-family: 'Titolo';} #header p, .total p {font-size: 1.4rem;} .title-element {margin-bottom: 1.5rem} .element img {width: 60px; height: 60px;} .element p, .title-element p {font-size: 1.2rem;} .element td {text-align: center;} .title-element p {line-height: 1;} </style> views from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def pdf_order(request, id): ordine = get_object_or_404(Summary, user = request.user, id = id) # template e context template_path = 'pdf.html' context = {'ordine': ordine} # oggetto django formato pdf response = HttpResponse(content_type='application/pdf') # view … -
AnonymousUser automatically created for TestCase
I'm encountering a situation where an anonymous user is automatically created upon constructing a TestCase which is not expected nor desired. The example test case that is posted below is not the sole test case experiencing this behavior. A custom User model has been created for my project, but I'm not sure if that has inadvertently done something to cause this. In python manage.py shell, I queried all users with get_user_model().objects.all(); within the queryset there was an instance of <User: AnonymousUser>. That was deleted as I closed/re-opened the shell and checked the admin as well. To specify what database I'm using for testing I'm using the built in test database Django provides with SQLite What would be causing the testcase to automatically populating with an AnonymousUser? from django.test import TestCase class TestViewUserQuestionsPostedPage(TestCase): @classmethod def setUpTestData(cls): cls.viewed_user = get_user_model().objects.create_user("ItsYou") testcase_users = get_user_model().objects.all() request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1})) cls.view = UserProfilePage() cls.view.setup(request, id=2) cls.view_context = cls.view.get_context_data() def test_viewed_profile_of_user(self): self.assertIsInstance(self.view, Page) self.assertIn('user', self.view_context) self.assertEqual(self.view_context['object'], self.viewed_user) (Pdb) testcase_users = get_user_model().objects.all() (Pdb) testcase_users <QuerySet [<User: AnonymousUser>, <User: ItsYou>]> from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = CharField( unique=True, max_length=16, error_messages={ "unique": "Username not available" } )