Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Templates: Is there a middle ground between extend and include?
I am developing a webpage with Django and I came across the problem of having certain reocurring elements within a webpage. The base layout inluding the menue for instance wraps the rest of the webpage and can thereby be outsourced by extend. Similarly if I have a reocurring element that is completly wrapped by the current webpage without altering html inside it can be implemented by using include (for instance a specific Button). However I have a third category where I do not know how to outsource redundant information: Lets say I have a card design, that always certain propery and contains of a div, with a header an image and content. I want to reuse this design displaying different contents and i also have different cards on the same page, how do I do that? Is this really the way to go: card_x.html: {% extend 'card_template.html' %} {% block title %} Title x{% endblock title %} {% content %} Content x {% endblock content %} ... card_template.html: <div> <h1>{% block title %} {% endblock title %}</h1> <div> {% content %} {% endblock content %} </div> </div> mainpage.html: {% include 'card_1.html' %} {% include 'card_2.html' %} {% include 'card_3.html' %} … -
DRF CSRF cookie not set
I have a DRF project, with an endpoint path('api/auth/', include('rest_framework.urls')), When sending a POST request from Postman to the endpoint api/auth/login/, in order to login with an existing user. I get the following error Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. Help Reason given for failure: CSRF cookie not set. I tried to set a csrf header (X-CSRFTOKEN, XSRF-TOKEN). I also logged in with the user from the DRF API interface and found the value for X-CSRFTOKEN, which I set in Postman with no success. I also tried to tweak many settings in setttings.py such as (CSRF_COOKIE_NAME, CSRF_TRUSTED_ORIGINS .. Also, to mention the POST method is working on other endpoints for creating objects. I am so thankful if anyone would have an idea. -
paragraph text caused exception findSpanStyle not implemented in this parser - Django
I am trying the generate a pdf using reportlab in django. The content I am trying to print in the pdf is a rich text data which also contains footnotes. I am generating the pdf with the following function makepdf def generate_pdf(request,cat,id): page_width, page_height = A4 page_size = A4 try: citation = get_citation(cat, id) pdf_buffer = BytesIO() # create a document template with the given title doc = BaseDocTemplate(pdf_buffer, pagesize=A4, title=id) # define a page template for all pages header_table_obj = HeaderContent().header(request) header_frame = Frame(0, 25.3*cm, page_width-1.8*cm, 3.1*cm, showBoundary=0, id="header") # define the content frame content_frame = Frame(2*cm, 2.5*cm, page_width-4*cm, page_height-4*cm-3.1*cm, showBoundary=1, id="content") page_template = PageTemplate(frames=[ header_frame, content_frame, ]) # add the page template to the document doc.addPageTemplates(page_template) # making the canvas pdf = canvas.Canvas(pdf_buffer, pagesize=A4) pdf.translate(cm,cm) # adding the pdf title pdf_title = f"SL-{str(citation.get('title', ''))}" pdf.setTitle(pdf_title) header_frame.addFromList([header_table_obj], pdf) # add your content to the content frame judgement_para= ContentParas().judgement_content(citation) // get the rich text data content_frame.addFromList([judgement_para], pdf) pdf.showPage() pdf.save() pdf_buffer.seek(0) return pdf_buffer except Exception as e: return str(e) the judgement_content function is given below which basically styles the paragraph class ContentParas: backColor='#F1F1F1' borderWidth=1 borderColor="#FF0000" borderPadding=(1,1,1) fontName="Times-Roman" fontSize=14 def judgement_content(self, citation): judgment_obj = citation.get('judgements', '') para_styles = ParagraphStyle("Para style", fontName= self.fontName, … -
{TypeError} '<=' not supported between instances of 'CombinedExpression' and 'datetime.date'
I'm new in django and I want to filter my model with certain conditions: for example get only team expired after 7 days. This is my django query: current_date = datetime.datetime.today().date() MyModel.objects.filter( Q(end_date__lt=current_date) & Q(locked=False) & Q(F('end_date') + datetime.timedelta(days=7) <= current_date) ).values('id') end_date is DateField. When I perform this piece of code I get this error: {TypeError} '<=' not supported between instances of 'CombinedExpression' and 'datetime.date'. How can I solve it? Evvery solution I found on web brings me to the same error (Cast, expression wrapper...) Thanks in advance. I try to solve the problem with Cast operator, Expression Wrapper etc. Here my last trial: MyModel.objects.filter( Q(end_date__lt=current_date) & Q(locked=False) & Q(Cast(F('end_date') + timezone.timedelta(days=7), output_field=models.DateField()) <= current_date) ).values_list('id', flat=True) -
Django cannot find 'myapp.setting' via django.setup() when running my script as a module
I'm working on a rather elaborate project and have run into some confusion regarding why I get a ModuleNotFoundError: No module named 'burrow.settings' (I called it myapp.settings in the title for better searchability) when calling __main__.py by running $ python -m burrow, but $ python burrow works perfectly well! I have no relative imports anywhere in my code and haven't touched the boilerplate generated by Django, and have tried and searched all kinds of things and can't find out why this is behaving differently, so any insight would be greatly appreciated! The repository structure may be a little confusing (suggestions for improvement welcome), but effectively consists of a single Project (meercat) consisting of two sub-packages (burrow and lookout) which represent a server and a client respectively. Within the server package (burrow), there is the regular Django boilerplate (burrow/burrow) as well as a Django REST Framework app (api). meercat - data - docs - meercat - burrow - api // newly created - burrow // created with startapp, untouched - __init__.py - __main__.py - controller.py - manage.py - env - lookout - __init__.py - core.py README.md Relevant code: # __main__.py import argparse as ap import logging import os import sys import … -
Add autocomplete CKEditorUploadingWidget with with some list of values
I have a form and I want the html_field to display a list of possible autocomplete options when the user types in matches from a certain list. However, I'm not sure how to correctly implement this, given that I'm using CKEditorUploadingWidget forms.py from ckeditor_uploader.widgets import CKEditorUploadingWidget class TemplateMesForm(forms.RequestForm): temp_html = forms.CharField( label='Html:', widget=CKEditorUploadingWidget(), #If the user types words into this form field that match the list in the function, they receive a dropdown list with all the matches and select the desired one ) views.py def get_autocomplete_list(request): autocomplete_list = ["apple", "banana", "cherry", "date", "elderberry"] return JsonResponse(autocomplete_list, safe=False) -
Why I cannot redirect to "User access URL" in Enterprise Application?
When I copy and paste this URL into the browser it works fine: https://myapps.microsoft.com/signin/xxxxxd7-xxxx-xxxx-xxxx-c6dxxxxxx83?tenantId=xxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxx but when I redirect using Django: from django.http import HttpResponseRedirect def redirect_to_login_url(): .... url = "https://myapps.microsoft.com/signin/xxxxxd7-xxxx-xxxx-xxxx-c6dxxxxxx83?tenantId=xxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxx" return HttpResponseRedirect(url) it doesn't work and I see: -
How to reset a postgres database for django
What do I need to do to get the a django app and the postgres database it connects back to the zero state? and then what do I need to do in Django to re-initialize the database tables? All of the references I've seen online are to MySQL and involve deleting the actual database file. I do not have the option of deleting the whole Postgres installation. -
Making put request to django with external script
I want to make put and post request to my django app with python script that is not in that app. I can make those request with postman but i want to automate them with just python code. Here is code that postman gives me but it doesn't seem to work import http.client import json conn = http.client.HTTPSConnection("localhost", 8000) payload = json.dumps({ data }) headers = { 'Content-Type': 'application/json' } conn.request("PUT", "api/raport/1", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) I tried to run this code and expected record in db change but it doesn't seem to do so. -
Exception while running docker-compose up with Django Rest Framework
To setup secure websocket in Django Rest Framework, I added Daphne to docker-compose.yml as follows daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always When I bring the docker-compose up, I'm seeing the following error. If I remove the daphne entry from docker-compose.yml, this error does not happen. I was able to successfully build the compose earlier. daphne_1 | Traceback (most recent call last): daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen daphne_1 | httplib_response = self._make_request( daphne_1 | File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 398, in _make_request daphne_1 | conn.request(method, url, **httplib_request_kw) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1256, in request daphne_1 | self._send_request(method, url, body, headers, encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1302, in _send_request daphne_1 | self.endheaders(body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1251, in endheaders daphne_1 | self._send_output(message_body, encode_chunked=encode_chunked) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 1011, in _send_output daphne_1 | self.send(msg) daphne_1 | File "/usr/local/lib/python3.8/http/client.py", line 951, in send daphne_1 | self.connect() daphne_1 | File "/usr/local/lib/python3.8/site-packages/docker/transport/unixconn.py", line 30, in connect daphne_1 | sock.connect(self.unix_socket) daphne_1 | FileNotFoundError: [Errno 2] No such file or directory daphne_1 | daphne_1 | During handling of the above exception, another exception occurred: daphne_1 | daphne_1 | Traceback … -
I'm facing this error "ImportError: cannot import name 'smart_text' from 'django.utils.encoding'"
I'm trying to implement Tags on my project using the django-tagging package. Below is the full error.\ File "C:\Users<user>\Desktop<App>\models.py", line 9, in from tagging.fields import TagField File "C:\Users<User>\Desktop<User><App>\env\lib\site-packages\tagging\fields.py", line 9, in from tagging.forms import TagField as TagFormField File "C:\Users<User>\Desktop<User><App>\env\lib\site-packages\tagging\forms.py", line 8, in from tagging.models import Tag File "C:\Users\Nicholas Karimi\Desktop\NicholasKarimi\WebLog\env\lib\site-packages\tagging\models.py", line 8, in from django.utils.encoding import smart_text ImportError: cannot import name 'smart_text' from 'django.utils.encoding' ("C:\Users<User>\Desktop<User><App>\env\lib\site-packages\django\utils\encoding.py) models.py\ class ModelName(models.Model): ..... tags = TagField() Working with django.VERSION (4, 2, 0, 'final', 0) -
how to add functionality of choose_all and remove_all functionality for a model in django-admin
I need to add the Choose all and Remove all functionality to one of the django model in the admin view. but not finding any documentation. I am creating Food table: <group1-> name:vegetarian food ---- vegetables nuts greens chicken egg <group2-> name: non-veg food ---- vegetables nuts greens chicken egg like above i need to choose the food-items and create a group. i want to display like groups option with choose_all/remove_all options. -
RelatedObjectDoesNotExist at /api/v1/user/
I am using drf-social-oauth2 for social authentication in django. When I make a request to backend using following json "grant_type": "convert_token", "client_id": "QhT0Z....u3m5f", "client_secret":"W2DMVGg.....CfhO", "backend":"google-oauth2", "token": "ya29.a0Ael9sCNIcDes5Zb85GJCGWj9ok5kmCH8oBAWWJP9gGRu1Mzrqgtkw6Ut4WE- aOaj0S5Fpf4IrZYjp8bYST93u6yb-MWIHzp3zmtUffbzKnA5VoKlvQ7aC5cSbCauBe4ckTn18XH0_3tWYn5QNg3D2bJqw6H1EAaCgYKARISARISFQF4udJhR0eV5UmE8pvApsrTCMq-8w0165" then following response is returned access_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjVaU2tncnpJUlNIczlrd3liNUhrQXoyOFNwVVZnZCJ9.FRk7hYDP0ndlBpH3L2jkdNpO3kopRcLqCFfx-6C5GKA" expires_in: 27791.630586 refresh_token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjdibURRUk54ckdLbVJiczR5UGd0ZTJidVNPMklQRyJ9.r5wH-RqhzN2DaG5uUF4Z7F-8ufPgBTUPn7fWLVFwt3k" scope: "read write" token_type: "Bearer" By default if this response is returned the user profile and email should automatically gets saved in the db but the drf-social-oauth2 is only returning the access tokens and is not saving user data. So when I make request to fetch user, following error occurs RelatedObjectDoesNotExist at /api/v1/user/ UserProfile has no student. Following is my written code settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', 'users', ... ] AUTH_USER_MODEL = 'users.UserProfile' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', } AUTHENTICATION_BACKENDS = ( # Google OAuth2 'social_core.backends.google.GoogleOAuth2', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Instagram OAuth2 'social_core.backends.instagram.InstagramOAuth2', # drf_social_oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) ACTIVATE_JWT = True SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv("G_APP_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv("G_APP_SECRET") # Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] urls.py from django.contrib import admin from django.urls … -
Converting string to Django model name before calling filter() (Not duplicate)
model_name = "MyModel" model_name.objects.filter() AttributeError: 'str' object has no attribute 'objects' How can I make this work, I have already tried: exec(model_name) input(model_name) [model_name] I know there is a possible method where you import the model using apps.get_model(model_name="string") but I don't want to use this method due to the model already being imported beforehand. Is there any different way where I can convert model_name (string type) to a type that can be inserted at INSERTHERE.objects.filter() -
How to redirect two different Django applications on the same server with same url but different paths?
I have two Django applications running on the same server in Docker containers. App1 is on website.com/ using localhost:9595 and App2 other is on website.com/app2. localhost:9696 Problem begins when I go to website.com/app2/something where it redirects me to website.com/something which doesn't exist instead of going to website.com/app2/something. I can fix it in NGINX by adding: /something/{ proxy_pass localhost:9696/something/ } But then I have to do it for every subpage of my application2. -
How to document a tuple with different data types using drf-spectacular?
I'm using drf-spectacular to generate a Swagger documentation. I have a viewset that returns a dict (it doesn't go through a drf serializer as it's all native objects). The dict looks like this: data = { "lines": List[str], "points": List[Tuple[float, float, int, str]] "next_failure_date": str, "estimate_nth_failure": str "status": str, } I can't find a way for drf-spectacular to properly document the "points" key, it only gives me a "points": ["string"] What I tried : class SwaggerGrowthChartPoint: """Class used to generate the Swagger documentation""" def __init__(self, x: float, y: float, sap_id: int, created_on: str): self.x = x self.y = y self.sap_id = sap_id self.created_on = created_on class SwaggerGrowthChartPointField(serializers.Field): def to_representation(self, value: SwaggerGrowthChartPoint): return f"{value.x}, {value.y}, {value.sap_id}, {value.created_on}" def to_internal_value(self, data): return SwaggerGrowthChartPoint(*data) class SwaggerGrowthChartSerializer(serializers.Serializer): """Serializer used to generate the Swagger documentation""" lines = SwaggerGrowthChartLinesSerializer(many=True) points = serializers.ListField(child=SwaggerGrowthChartPointField()) next_failure_date = serializers.ListField(child=serializers.DateField()) estimate_nth_failure = serializers.DateField() status = serializers.CharField() But no luck. -
how to get socket id from this library
I'm using this library in my python code: ''' import socket socket.socket(socket.AF_INET,socket.SOCK_STREAM) python get socket id ''' how to get socket id (sid) and how to send message to selected client by socket id -
I can't call the function value in the model
my models.py : from django.db import models from django.urls import reverse from django.utils import timezone from django.db.models import Sum # Create your models here. class Plac(models.Model): c_name = models.CharField(max_length = 50) starting_date = models.DateTimeField(auto_now=True) posting_num = models.SmallIntegerField(default = None) payment_date = models.DateTimeField(auto_now=None) billingAm = models.SmallIntegerField(default = None) billing = models.BooleanField(default=False) def get_absolute_url(self): return reverse('place:place_detail', args=[self.pk]) def get_totalbilling(self): return Plac.objects.aggregate(Sum('billingAm'))['billingAm__sum'] or 0 class Rank(models.Model): name = models.ForeignKey(Plac,on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True,) updated_at = models.DateTimeField(auto_now=True) ranking = models.SmallIntegerField(default = None) my html : <br /> <div>TotalPrice: {{plac.place.get_totalbilling}}</div> {% endblock content %} I want to see the result of "get_totalbilling" I try it for 3days.. but I can't coz I am beginner of django. -
unable get static image on webpage even after creating static folder and updating its path in settings.py and running collectstatic
I am using vscode.I created a django project named myproject, app named myapp and static folder in myproject dir. My image is not getting displayed in webpage after trying everything.I am not getting where is the issue please help. my static folder location C:\Users\nihar\myproject\static settings dir -STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') html file code {% load static %} <!DOCTYPE html> <body> <img src="{% static 'images/tttbg.jpg' %}"> </body> -
I want create a inventory management system in django(CRUD OPERATION)
Want to perform a crud operation in html view in django with this given model:- class Brand_Master(models.Model)`: brand_id = models.CharField(max_length=10,unique=True,verbose_name='Brand ID') brand_name = models.CharField(max_length=30,verbose_name='Brand Name') def __str__(self): return self.brand_name class Item_Master(models.Model): brand = models.ForeignKey(Brand_Master,on_delete=models.CASCADE,verbose_name='Brand ID') item_name = models.CharField(max_length=50,verbose_name='Item Name') item_code = models.CharField(max_length=20,unique=True,verbose_name='Item Code') price = models.FloatField(verbose_name='Price') def __str__(self): return self.item_code + "-" +self.item_name class Sale_Master(models.Model): item = models.ForeignKey(Item_Master,on_delete=models.CASCADE,verbose_name='Item') customer_name = models.CharField(max_length=100,verbose_name='Customer Name') number = models.PositiveBigIntegerField(verbose_name='Number') invoice = models.PositiveIntegerField(verbose_name='Invoice') I have created backend and want frontend view crud operation ` -
how to get a link to a file with https in json in drf
I have app with api on drf I installed the ssl certificate on the site and when I try to get the file I get an error: The page at site https://www.example.com was loaded over Https, but requested an insecure resource http://api.example.com/…… I think the problem is that with a get request in json, my link starts with http... How can i solve this problem and get file link starting with https ?? or is it something else? Json from get request: { "id": 50, "name": "Образец заполнения книги учета доходов", "category": "Бухгалтерия и налоги", "count_download": 0, "type_doc": "xls", "screenshot": "http://api.example.com/media/screenshot/%.png", "add_time": "2023-03-27", "pdffile": "http://api.example.com/media/pdf_docs/%.pdf" } I think perhaps it is necessary to somehow make a proxy server, but I don’t understand how… -
Djongo/MongoDB error while doing migration using django-allauth
Error i get djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "django_site" LIMIT 1 Params: (1,) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None I am trying to login using social media authentication(all-auth). But this gives error while migrating all-auth fields into database. I am using mongodb. -
How do I test url in Django with ?postId=1?
I want to test my url, but errors shows and something is wrong with this path Here is my path `path('comments/', views.get_comments_by_postid, name='comments')` and view i made `@require_http_methods(["GET"]) @login_required(login_url='login') def get_comments_by_postid(request): comment_id = request.GET.get('postId') comments_url = 'https://jsonplaceholder.typicode.com/comments' if comment_id is not None: comments_url += f'?postId={comment_id}' comments_response = requests.get(comments_url) comments = comments_response.json() return render(request, 'comments.html', {'comments': comments})` and that is the test i tried to make but it is not working, errors shows `def test_comments_by_added_postId_url(self): url = reverse('comments') + '?postId=1' print(resolve(url)) self.assertEquals(resolve(url).func, get_comments_by_postid)` -
"clean() got an unexpected keyword argument 'fix_unicode'"
clean() got an unexpected keyword argument 'fix_unicode' when i install clean-text i got errors Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [1 lines of output] ERROR: Can not execute `setup.py` since setuptools is not available in the build environment. [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. i tried everything available on internet but could not find any solution please help me to resolve this issue -
Auto select category code when we select the respective category
I am new in Django I am creating an admin panel where admin can create category list with category code. This is working fine. now my next task is that, admin will have the functionality to add product where he has to select the category name and i want that that category code belong to selected category should be auto selected when we select the category i have created a drop down for fetching the list of category category_list = Tcategory.objects.all() <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <label for="categories">Select Category</label> <select name="category" class="form-select form-control" id="category" name="category"> <option value="" disabled selected>Select Treatment Category</option> {%for categorys in category_list%} <option value="{{category}}">{{categorys}}</option> {%endfor%} </select> </div> </div> <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <input class="form-control" type="text" name="Tcategoryname" value="{{categorys.Tcode}}" placeholder="tcode"> </div> </div> By this I am able to fetch the list of category 1 - how i can get list of code from my model 2 - how i can do if user select category, and category code is auto selected