Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin automatic rtl for some languages
I'm trying to add multi language support for a django project using Django i18n official documentaion: https://docs.djangoproject.com/en/4.1/topics/i18n/translation/ When I change the LANGUAGE_CODE to something like 'fa', by default the admin panel changes to RTL. But the problem is when I use other RTL languages like 'ku' (kurdish) the page remains in ltr. I know we can change the css manualy, but wonder what is the problem here and how some languages like Arabic or persian does the RTL part automaticaly but others dont. Thanks in advance # settings.py LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True TIME_ZONE = 'UTC' USE_TZ = True LANGUAGES = ( ('en', _('English')), ('ku', _('Kurdish')), ('fa', _('Persian')), ) LOCALE_PATHS = [ Path(BASE_DIR, 'django_i18n', 'locale'), ] # url.py urlpatterns = i18n_patterns( path('admin/', admin.site.urls), ) +static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) -
Update view in Django WITHOUT using generic classes
I think I don't understand something fundamental here, but every single tutorial on the topic proposes a solution using either a function or a generic class, and both of them work for me, but I can't figure out how to deal with the issue using just View. So to illustrate where I am at, I am building a very simple blog and want to update data on a single post based on it's id. So what I have is: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.CharField(max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' urls.py urlpatterns = [ path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update') ] update_post.html <form method="post"> {% csrf_token %} {{ isolated_post.as_p }} <input type="submit" value="Update"> </form> and finally views.py class PostUpdateView(View): form_class = PostForm initial = {'key': 'value'} template_name = "blog/update_post.html" def get(self, request, pk): isolated_post = Post.objects.get(pk=pk) form = self.form_class(instance=isolated_post) return render(request, self.template_name, {'form': form}) def post(self, request, pk, form): updated_post = self.form_class(request.POST, instance=form) if updated_post.is_valid(): updated_post.save() return HttpResponseRedirect("/post/" + f'{pk}/') return render(request, self.template_name, {'updated_post': updated_post}) I've tried a lot of things, this time it says that form has not been passed … -
Reverse for 'download' with arguments '({'qualities': [(0, '360p'), "Also have issue with stream" not found. 1 pattern(s) tried: ['download/\\Z'])';
It happens when I try to pass the dictionary from view to html in django View.py from django.shortcuts import render,redirect from pytube import YouTube import os def Yt(request): if request.method == 'POST': # url of the youtube video video_url = request.POST.get('url') # get the video yt = YouTube(video_url) # get all available streams streams = yt.streams.filter(progressive=True, file_extension='mp4') # Get the qualities qualities = [(i,stream.resolution) for i, stream in enumerate(streams)] context = { 'qualities' : qualities, 'streams' : streams, } return redirect('download', context) return render(request, 'yt.html') def Yt_det(request): if request.method == 'POST': streams = request.session.get('streams') # get the quality of video selected_quality = int(request.POST.get('selected_quality')) # download the video stream = streams[selected_quality] # name of the video custom_name = request.POST.get('custom_name') # download the video stream.download(filename=custom_name) return render(request, 'yt-det.html', {'message': 'Video downloaded successfully'}) Yt.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* Import Google Font - Poppins */ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body { display: flex; padding: 0 10px; min-height: 100vh; align-items: center; background: #3498DB; justify-content: center; } ::selection { color: #fff; background: #3498DB; } .wrapper { height: 265px; max-width: 410px; background: #fff; border-radius: … -
javascript download docx file from ajax response
I have a django function with return: ... return FileResponse(open('demo.docx', 'rb')) I use ajax to get it on client side. Now I need to download it on client side. I use this code: ... success:function(response){ var blob = new Blob([response]); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "file.docx"; link.click(); }, ... Edited: function func(){ var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ type: 'POST', url: '/myapp/func/', headers:{ "X-CSRFToken": csrftoken }, data: {name:"",'image1': Data1}, success:function(response){ var blob = new Blob([response]); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.setAttribute('target', '_blank'); link.download = "file.docx"; link.click(); }, error : function(xhr,errmsg,err) { alert("ajax error: func"); } }); } However it downloads a corrupt something, probably not a docx file. How can I get on client side what I read as a docx? -
Django Views not getting POST Data from api call
I am not using django rest frame work but in normal views.py I have a simple views #views.py def api_post_operations(request): pdb.set_trace() if request.POST: print(request.POST["name"]) print(request.POST["address"]) now I call it import requests url = "http://localhost:8000/api_post_operations" payload = {"name":"raj", "address": "asasass" } rees = requests.post(url, data=payload, headers={}) it is comming (Pdb) request.POST <QueryDict: {}> Any reason why it is comming {} balnk request.body also comming blank -
Custom rendered input for django-formtools wizard field
New to Django. I've created some bootstrap card UI widgets that function as radio buttons and this works ok in plain old html, but I'm trying to integrate it into a Django wizard. How would I go about telling the form the data field is associated with? I just have a bunch of widgets included for each option like this <div class="col-6"> {% include "./domain_type_widget.html" with radio_group="domain_type" title="People" description="For a URL with your name" left="name" mid="people" type_id="name" checked=True %} </div> <div class="col-6"> {% include "./domain_type_widget.html" with radio_group="domain_type" title="Event" description="For events" left="eventname" mid="event" type_id="event" %} </div> And domain_type_widget.html looks like so <label class="card m-1 {% if checked %}selected_type{% endif %}" id="{{ type_id }}_card"> <div class="card-body" onclick="selectDomainType({{type_id}})"> <div class="row"> <div class="col-sm-12 col-md-10"> <h5 class="card-title">{{ title }}</h5> <p class="card-text">{{ description }}</p> {% if left %} <p class="domain-example" class="domain-example"> <span class="left">{{ left }}</span> <span>.</span> <span class="mid">{{ mid }}</span> <span>.</span> <span class="right">site.com</span> </p> {% endif %} </div> <div class="col-sm-12 col-md-2 d-flex align-items-center justify-content-center"> <input type="radio" class="radio" name="{{ radio_group }}" id="{{ type_id }}" {% if checked %}checked{% endif %} onchange="selectDomainType(this)"> </div> </div> </div> -
How do you use the Django timezone.override(utc) to create datetimes with tzinfo?
I can use timezone.now() to get a UTC timestamp in Django. I can use timezone.make_aware(datetime(2012,1,1)) to add UTC as the TZ for the datetime. Last one is cumbersome and a lot of extra typing. Meanwhile I find these docs: https://docs.djangoproject.com/en/4.1/topics/i18n/timezones/ But activating the TZ doesn't seem to affect datetime creation (still no tzinfo included) I also found these docs inside python: >>> from django.utils import timezone >>> help(timezone) Help on module django.utils.timezone in django.utils: NAME django.utils.timezone - Timezone-related classes and functions. CLASSES contextlib.ContextDecorator(builtins.object) override class override(contextlib.ContextDecorator) | override(timezone) | | Temporarily set the time zone for the current thread. | | This is a context manager that uses django.utils.timezone.activate() | to set the timezone on entry and restores the previously active timezone | on exit. | | The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a | time zone name, or ``None``. If it is ``None``, Django enables the default | time zone. | | Method resolution order: | override | contextlib.ContextDecorator | builtins.object | | Methods defined here: | | __enter__(self) | | __exit__(self, exc_type, exc_value, traceback) | | __init__(self, timezone) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from … -
Show another static content as part of Django page
Collaborator is giving me static content that I'd like to display as a component of a page in a Django app. I'd like to do this without styling interruptions. Specifically: I have a Django template templates/page.html that extends templates/base.html. The base.html includes header/footer/navbar/etc. In the middle of page.html, I'd like to insert external HTML (with its own CSS) exactly as being imported, so that external CSS styling in templates/base.html doesn't get applied. (But I also don't want the CSS I am importing to affect stuff in base.html either.) Is there a Django-native, or HTML/CSS-native way to accomplish this? -
The json formatted response from django API with serializers
i have been trying to get the response as given below but am a little stuck as to how to achieve it.. I tried other ways without serializers but then my pagination does not work as expected.. the question for the pagination issue is Pagination does not seem to be working using get method and APIView below is my dataset: data = [['1','2023-01-04 12:39','{"kpiThreshold": 23, "kpiValue": 25, "kpiDiff": 2}'], ['2','2023-01-03 12:39','{"kpiThreshold": 23, "kpiValue": 26, "kpiDiff": 3}'], ['1','2023-01-02 12:39','{"kpiThreshold": 23, "kpiValue": 27, "kpiDiff": 4}']] df_new = pd.DataFrame(data, columns=['id', 'date','kpi']) df_new serializer.py from rest_framework import serializers from pegaapi.models import PegaAlerts class AlertsSerializer(serializers.ModelSerializer): class Meta: model = PegaAlerts fields = ('id','generateddatetime','kpiValues') views.py class FullLogsAPI(GenericAPIView): pagination_class=CustomPagination serializer_class = AlertsSerializer def get(self,request, *args, **kwargs): envid = self.kwargs.get('envid') nodeid = self.kwargs.get('nodeid') startdatetime = self.request.GET.get('startdatetime') enddatetime = self.request.GET.get('enddatetime') filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime') page = self.paginate_queryset(filter_list) serializer = AlertsSerializer(page, many=True) return Response(serializer.data, status=status.HTTP_200_OK) Response : [ { "id": 1, "generateddatetime": "2023-01-04 12:39", "kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 25, \"kpiDiff\": 2}" }, { "id": 2, "generateddatetime": "2023-01-03 12:39", "kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 26, \"kpiDiff\": 3}" }, { "id": 3, "generateddatetime": "2023-01-02 12:39", "kpiValues": "{\"kpiThreshold\": 23, \"kpiValue\": 27, \"kpiDiff\": 4}" } ] But the response i'm looking for is [ { … -
Facing problems when I try to deploy drf + angular to digitalocean droplet
I am trying to deploy my django + angular application to a digitalocean droplet. Here is all the relevant information: File structure: home/ USER_NAME/ projectdir/ env/ test_project/ several_django_apps/... dist/ frontend/ assets/ images/... index.html favicon.ico some_relevant_js_files.js test_project/ __init__.py asgi.py urls.py settings.py wsgi.py In the above structure, the dist folder has a frontend folder which contains the angular build data. When I try to access my domain, I get a 500 Internal Server error. Now, here is my nginx configuration: server { listen 80; server_name IP_ADDRESS www.DOMAIN_NAME DOMAIN_NAME; location = /favicon.ico { access_log off; log_not_found off; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location / { root /home/USER_NAME/projectdir/test_project/dist/frontend; try_files /index.html $uri $uri/; } } When I run sudo tail -f /var/log/nginx/error.log, I get the following errors: [crit] 2446#2446: *9 stat() "/home/USER_NAME/projectdir/test_project/dist/frontend/index.html" failed (13: Permission denied) [crit] 2446#2446: *9 stat() "/home/USER_NAME/projectdir/test_project/dist/frontend///////////" failed (13: Permission denied) [error] 2446#2446: 2446#2446: *9 rewrite or internal redirection cycle while internally redirecting to "////////////" I am extremely new to all of this stuff so I apologize for any silly errors on my end. If you require any other information please let me know. Thanks! I also tried increasing the memory of my droplet if that were … -
How to install mysqlclient python package?
I now learn django. On database learn mysql. But dont install mysqlclient. Initially get Microsoft C++ 14.0 or greater than required error. I solve this. I install build tools. But now get another error: running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-cpython-38 creating build\temp.win32-cpython-38\Release creating build\temp.win32-cpython-38\Release\MySQLdb "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\bin\HostX86\x86\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,1,'final',0) -D__version__=2.1.1 "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include" -IC:\Users\Feruz\.virtualenvs\storefront-GD3EPR4W\include -Ic:\users\feruz\appdata\local\programs\python\python38-32\include -Ic:\users\feruz\appdata\local\programs\python\python38-32\Include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-cpython-38\Release\MySQLdb/_mysql.obj _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: ЌҐ г¤ Ґвбп ®вЄалвм д ©« ўЄ«о票Ґ: mysql.h: No such file or directory, error: command 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x86\\cl.exe' failed with exit code 2 note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> mysqlclient note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. [0m Installation Failed How to solve this? Please help me. I use windows -
Iterate over page data stored in a settings Orderable
I have created a Wagtail settings page that allows me to select 1-5 pages which I'd like to display in my site footer as 'Most popular pages'. I've done this using an Orderable and PageChooserPanel, see below: @register_setting class MostPopularPosts(BaseSetting, ClusterableModel): display_most_popular_posts_in_sidebar = models.BooleanField("Display most popular posts in sidebar", default=True, help_text='Untick to hide the most popular posts widget') panels = [ FieldPanel('display_most_popular_posts_in_sidebar'), InlinePanel('popular_pages', max_num=5, min_num=1, label="Most popular pages"), ] class MostPopularPostPages(Orderable): settings_page = ParentalKey(MostPopularPosts, related_name="popular_pages") popular_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', verbose_name="Page Link" ) panels = [ PageChooserPanel('popular_page') ] The above works fine, but I'm struggling to get the content of the individual pages selected to appear in my templates. {% for popular_page in settings.home.MostPopularPosts.popular_pages.all %} <li> {{ popular_page.title }} </li> {% endfor %} The above loop iterates the expected number of times, but {{ popular_page.title }} doesn't output the page titles. I've tried {{ popular_page.specific.title }} but this also doesn't work. If someone could explain how I should be structuring my template tags to access the individual pages data within my for loop here I'd be eternally grateful. -
Why i can choose only decimal multiple 0,5 in admin panel?
I created a model in Django with multiple choice of numbers from 0 to 14 with steps 0,1. I can see them all in the admin panel, but can choose only numbers multiple 0,5. My model: class SoilPh(models.Model): SOIL_PH_CHOICES = ( (i / 10, str(i / 10)) for i in range(MAX_PH_LEVEL * 10 + 1) ) name = models.DecimalField( max_digits=2, decimal_places=1, validators=[ MinValueValidator(0, '0'), MaxValueValidator(MAX_PH_LEVEL, f'{MAX_PH_LEVEL}') ], choices=SOIL_PH_CHOICES, unique=True, null=True, ) class Deciduous(Plant): soil_ph = models.ManyToManyField( SoilPh, related_name='soil_ph', ) Error: Select a valid choice. 0.3 is not one of the available choices. Where is my mistake? -
how to override _default manager used by ModelSerializer
Given below snippet, class CustomManager(models.Manager): def create(**kwargs): super().create(external_id='xyz', **kwargs) class Person(models.Model): internal_id = models.AutoField(db_column='id', primary_key=True) f_name=models.CharField(db_column='f_name', max_length=15, blank=True, null=True) external_id = models.CharField(db_column='ext_id', null=True, blank=True, max_length=20) objects = models.Manager() custom = CustomManager() class PersonSerializer(serializer.ModelSerializer): class Meta: model=Person fields='__all__' Here, when .save() method gets called on the serializer, the default manager used by the the create function in serializer is objects. I would like this to be changed to custom so that when save call happens, create function inside CustomManager gets invoked. I can achieve this by overriding the super class method create in the serializer. But is there any better workaround for this without overriding base class method? -
Can I use only one redis connection for my django app?
Introduction: django 3.2.16 django-redis 4.12.1 Problem: I use redis as a cache storage. I put the data to redis manually using the next code: from django_redis import get_redis_connection def redis_handler() -> None: redis = get_redis_connection() ... # some business logic ... redis.close() I call redis_handler() often and every time a new connection to redis created. Idea/Solution: Can I create a "global" redis connection once for a project and then import and use it everywhere? Where I can do it? What problems can be? Because I will not close it while the project works. I was inspired FastApi - it has hooks when the project starts and stops. -
django unit test database connection error
I am trying to run the Django rest framework unit test and at the beginning, it works well but after a while, I start getting this error : error I have no idea why I keep getting this error or what change caused this error in my unit test my unit test: image my setting.josn : image my local.py settings: image -
Github Webhook Verification within Django-Ninja
I have the following end-point inside a Django-Ninja application that I am using to verify incoming GitHub Webhooks. I'm not sure what I'm doing wrong but the hmac.compare_digest() keeps returning False even when I know it is GitHub sending the post request from ninja import NinjaAPI import hmac import hashlib import os import requests api = NinjaAPI() class GitHubVerify: my_secret = os.getenv('GITHUB_SECRET_KEY') def verify(self, request) -> bool: return self._verify_signature(request=request) # and self._verify_ip(request=request) def _verify_signature(self, request): incoming_signature = request.headers.get('X-Hub-Signature-256', None) if incoming_signature is None: return False sha_name, incoming_signature = incoming_signature.split('=') if sha_name != "sha256": return False print(sha_name, incoming_signature) calculated_signature = hmac.HMAC( key=self.my_secret.encode('utf-8'), msg=request.body, digestmod=hashlib.sha256 ).hexdigest() print(calculated_signature) print(request.headers) return hmac.compare_digest(calculated_signature, incoming_signature) def _verify_ip(self, request): """ TODO: figure out why the IP being parsed here doesn't seem to match GitHub's API """ webhook_ips = self._get_hook_ips() print(webhook_ips) print(request.headers) return request.headers.get('X-Forwarded-For') in self._get_hook_ips() def _get_hook_ips(self): return requests.get('https://api.github.com/meta').json()['hooks'] @api.post("/webhook") def github_webhook(request): github_verify = GitHubVerify() return github_verify.verify(request=request) I've copy-pasta'd the secret key from my environment to GitHub Webhook. I parse the incoming headers to make sure a 256SHA signature exists. Then I calculate my own signature using hmac, passing in my secret, request.body and SHA256 Am I missing something glaringly obvious? Another thing I noticed is that … -
Using PageChooserPanel as an Orderable in Settings, getting "'list' object has no attribute 'bind_to'" Attribute error
I'm trying to create a settings page within Wagtail that will allow me to manually choose 1-5 pages that will be displayed as 'Most popular pages' on my site. I'm using a PageChooserPanel within an Orderable, but I'm getting an Attribute error that I don't know how to fix - "'list' object has no attribute 'bind_to'" Code used is below: from django.db import models from wagtail.core.models import Page, Orderable from wagtail.admin.edit_handlers import PageChooserPanel, FieldPanel, MultiFieldPanel, InlinePanel from wagtail.contrib.settings.models import BaseSetting, register_setting from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel @register_setting class MostPopularPosts(BaseSetting, ClusterableModel): display_most_popular_posts_in_sidebar = models.BooleanField("Display most popular posts in sidebar", default=True, help_text='Untick to hide the most popular posts widget') panels = [ FieldPanel('display_most_popular_posts_in_sidebar'), InlinePanel('popular_page', max_num=5, min_num=1, label="Post"), ], class MostPopularPostPages(Orderable): settings_page = ParentalKey(MostPopularPosts) popular_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', verbose_name="Page Link" ) panels = [ PageChooserPanel('popular_page'), ] Error message in full: Internal Server Error: /admin/settings/home/mostpopularposts/2/ Traceback (most recent call last): File "C:\Users\willr\repos\mapbox\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\wagtail\admin\urls\__init__.py", line 127, in wrapper return view_func(request, *args, **kwargs) File "C:\Users\willr\repos\mapbox\env\lib\site-packages\wagtail\admin\auth.py", line 172, in decorated_view … -
How to save python docx on client side using ajax?
I use python 3.6 Django, my code looks like this: from docx import Document document = Document() document.add_heading('My docx', 0) document.save('myFile.docx') return HttpResponse(document, content_type='application/vnd') I don't want to save it on server, instead I want to send it to client side using ajax and save it on client pc. Any thoughts how to do it? -
Django Oscar - Override form - AddToBasketForm
Alright, To be able to add another field to the "AddToBasketForm" in Django Oscar, I created a fork for the basket app and tried overriding the default "AddToBasketForm". #forms.py import datetime from django import forms from oscar.apps.basket.forms import AddToBasketForm as CoreAddToBasketForm # noqa isort:skip class AddToBasketForm(CoreAddToBasketForm): pass def __init__(self, basket, product, *args, **kwargs): # Note, the product passed in here isn't necessarily the product being # added to the basket. For child products, it is the *parent* product # that gets passed to the form. An optional product_id param is passed # to indicate the ID of the child product being added to the basket. self.basket = basket self.parent_product = product super().__init__(*args, **kwargs) # Dynamically build fields if product.is_parent: self._create_parent_product_fields(product) self._create_product_fields(product) # Create an aditional DateField self.fields['date'] = forms.DateField(initial=datetime.date.today) Now by overriding the form, I get an error saying: TypeError at /catalogue/product_1/ __init__() missing 2 required positional arguments: 'basket' and 'product' So by overrriding the form, I lost the initial form data, basket and product. It feels like this isn't the correct way to modify a form within Django Oscar. Anyone any ideas? Best regards, Kevin -
In Django how to convert a single page pdf from html template?
I am using puppeteer_pdf package to convert an HTML template into a pdf, but when my content increases, it creates another page in the pdf. I want the whole pdf as a single page. My main goal is the make a jpg image from that pdf and send the image to the client. If there is another way to make a jpg image from HTML maintaining all CSS and images it will be very helpful. This is my code : import os from puppeteer_pdf import render_pdf_from_template from django.conf import settings from django.http import HttpResponse def generate_pdf_invoice(invoice): context = { 'invoice': invoice } output_temp_file = os.path.join( settings.BASE_DIR, 'static', 'temp.pdf') pdf = render_pdf_from_template( input_template='shop/invoice_email_pdf.html', header_template='', footer_template='', context=context, cmd_options={ 'format': 'A4', 'scale': '1', 'marginTop': '0', 'marginLeft': '0', 'marginRight': '0', 'marginBottom': '0', 'printBackground': True, 'preferCSSPageSize': False, 'output': output_temp_file, 'pageRanges': '1-2', } ) filename = 'test.pdf' # return pdf response = HttpResponse(pdf, content_type='application/pdf;') response['Content-Disposition'] = 'inline;filename='+filename return response -
ImportError create_namedtuple_class Django Modeltranslation
I have an error while trying to use django-modeltranslation 0.18.3 in Django 2.2. Here's the end of the traceback: [...] from django.db.models.utils import create_namedtuple_class ImportError: cannot import name 'create_namedtuple_class' from 'django.db.models.utils' (/home/me/project/.venv/lib/python3.10/site-packages/django/db/models/utils.py) I can't figure what's wrong with modeltranslations and with django. I recreated a clean venv, nothing works. -
Django 'Makemigrations' are unable to access the database
When running python manage.py makemigrations I'm all of a sudden running into an error about being unable to connect to the database. The application itself is running perfectly fine and can connect with no issues, but manage.py is broken. This is the error in question: /Users///.venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? I've tried restarting everything, the database, application, computer, etc. I've nuked the venv and created a new one, double checked the database settings in settings.py and they are listed below: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.getenv("DB_NAME"), "USER": os.getenv("DB_USER"), "PASSWORD": os.getenv("DB_PASSWORD"), "HOST": os.getenv("DB_HOST"), "PORT": os.getenv("DB_PORT"), } } -
Meta descriptions and titles on all html pages
I'm building a website using django and i'm now esploring about SEO and how to make my page visible when i'll publish it. I read that you should put titles and description for your website in all of your html pages that compose your website, however is it really necessary to put a title and a description for an URL that i use for exemple a password reset that you should not search directly from google? I used a block in the django template of my base.html and i was adding manually a title and a description tag for every html i have in this project. The fact is that i don't know what to write in specific URLs used for the website service reason and i would let it blanked. -
404 page not found django cookiecutter without error message
First time running the app on production (35.231.94.10) I am getting 404 page not found Not from django server and there aren't any error messages last logs belal-django-1 | PostgreSQL is available belal-django-1 | [2023-01-12 11:54:08 +0000] [1] [INFO] Starting gunicorn 20.1.0 belal-django-1 | [2023-01-12 11:54:08 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1) belal-django-1 | [2023-01-12 11:54:08 +0000] [1] [INFO] Using worker: sync belal-django-1 | [2023-01-12 11:54:08 +0000] [9] [INFO] Booting worker with pid: 9 belal-django-1 | [2023-01-12 11:54:08 +0000] [10] [INFO] Booting worker with pid: 10 belal-django-1 | [2023-01-12 11:54:08 +0000] [11] [INFO] Booting worker with pid: 11 belal-django-1 | [2023-01-12 11:54:08 +0000] [12] [INFO] Booting worker with pid: 12 belal-traefik-1 | time="2023-01-12T12:04:06Z" level=warning msg="A new release has been found: 2.9.6. Please consider updating." Tried rebuilding it Tried every page and still nothing