Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'storages'
I no idea why this error kept occur in my terminal my current django version, 4.2.3 python version, 3.10.6 and my virtual environment is on, and I did downloaded these pip pip install boto3 pip install django-storages and my settings.py INSTALLED_APPS=[ ... 'storages', ] and DEFAULT_FILE_STORAGE='storages.backends.s3boto3.S3Boto3Storage' ok then, I try to run my server, python manage.py runserver it came out these error ** Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python latest\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python latest\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\Desktop\udemy react django e commerce\env\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Python latest\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
Django reloading a page without loosing user inputs in a form
I am working on translating my Project. I implemented a language Switch in my basetemplate: {% load i18n %} {% load language_tags %} <!-- imports all tags from templatetags/language_tags.py (see below) --> ... <div class="collapse navbar-collapse justify-content-end" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% translate 'Language' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as langs %} {% for lang in langs %} <li><a class="dropdown-item" href="{% translate_url lang.code %}">{{lang.name_local}}</a></li> {% endfor %} </ul> </li> </ul> </div> ... The important part here ist the href={% translate_url lang.code %} It is a custom template tag (see templatetags/language_tags.py) in my projetc that i have from here: https://stackoverflow.com/a/17351858/21828018 It's usage ({% translate_url de %}) is to give back the url you are visiting in the given language e.g. if you are visiting en/product/product_id and you use {% translate_url de %} it returns de/product/product_id. In combination with i18n_patterns the translation works so far. templatetags/language_tags.py: """language_tags.py""" from django import template from django.urls import reverse, resolve from django.utils import translation from django.conf import settings register = template.Library() class TranslatedURL(template.Node): """gets current path and creates new url with passed … -
Django .aggregate() on prefetched element not filtering by date
I have a queryset that I am prefetching entries between a range of dates, I am trying to annotate the totals of the prefetched elements into the outer element. When I call .annotate() on the outer element the filtered date ranges do not pass through. How do I fix this? GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__gte=start_date, date_entered__date__lte=end_date)), ).filter(account_identifier='1011.00').annotate(Sum('general_ledger__credit_amount')) The annotated value grabs all general ledger entries from the start of time. -
Master Ref ID is not working as expected in Details Table
I am getting this error message: {"status":400,"message":{"reason_items":[{"master_ref_id":["This field is required."]}]}} master_ref_id isn't supposed to be passed in postman(Details Table gets connected to Masters Table by master_ref_id which is autogenerated). But When I manually give master_ref_id, I get an obvious error: TypeError at /chargeback-reason/ django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() got multiple values for keyword argument 'master_ref_id' This is the data I am passing in postman for 'POST' request. { "name": "name3", "action_id": 1, "reason_items": [ { "attachement_format_id": 1, } ] } serializer.py file class ChargeBackReasonDetailsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = ChargeBackReasonDetails fields = '__all__' class ChargeBackReasonSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) reason_items = ChargeBackReasonDetailsSerializer(many=True) class Meta: model = ChargeBackReason fields = '__all__' def create(self, validated_data): item_row = validated_data.pop('reason_items') reason = ChargeBackReason.objects.create(**validated_data) for item in item_row: ChargeBackReasonDetails.objects.create(**item, master_ref_id = reason) return reason views.py file def create(self, request): with transaction.atomic(): data = dict(request.data) data['created_by'] = request.user.id data['updated_by'] = request.user.id data['updated_date_time'] = datetime.now(pytz.timezone(TIME_ZONE)) for item in data['reason_items']: item.update({'created_by':request.user.id,'updated_by':request.user.id,'updated_date_time':datetime.now(pytz.timezone(TIME_ZONE))}) serializer = ChargeBackReasonSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({STATUS: RECORD_CREATED}, status=status.HTTP_201_CREATED) else: return Response({STATUS: status.HTTP_400_BAD_REQUEST, MESSAGE: serializer.errors}, status=status.HTTP_400_BAD_REQUEST) models.py file class ChargeBackReason(models.Model): action_id = models.ForeignKey(ChargeBackAction, verbose_name="action_id", on_delete=models.PROTECT) name = models.CharField(max_length=100,verbose_name='name') class ChargeBackReasonDetails(models.Model): master_ref_id = models.ForeignKey(ChargeBackReason, verbose_name="Master Ref Id",related_name="reason_items",on_delete=models.PROTECT) attachement_format_id = models.ForeignKey(AllMaster,verbose_name="Attachement Format",on_delete=models.PROTECT)) -
Django Query loads for too long
i have an sqlite database for a cbt app and it is a small database with just over students registered. but when i query the database to get all the exams written, it takes over 2 minutes to load the query. i have used .select_related() but it's still so slow. i know sqlite is slow but i don't believe it's so slow def examination(request, id): courses = Course.objects.all().order_by('-pk') course = courses.filter(id=id).first() exams= Examination.objects.filter(course=course).select_related('student').order_by('-id') if (request.method == 'POST'): search = request.POST.get('search',None) if(search != None): return_url = return_url = reverse('user:examSearch', args=[id, search]) return redirect(return_url) paginator = Paginator(exams, 20) page = request.GET.get('page') try: exams = paginator.page(page) except PageNotAnInteger: exams = paginator.page(1) except EmptyPage: exams = paginator.page(paginator.num_pages) context ={ 'course': course, 'exams':exams, 'page': page, } return render(request, 'exam.html', context) Please what could be causing this performance issue? -
Django-MySql database error : png-config not found
/bin/sh: pkg-config: command not found /bin/sh: pkg-config: command not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Traceback (most recent call last): I want to install mysqlclient package but when I do so I get this error -
Issue in Django Prefetching same objects, but with different dates
I know there has to be a simple way to get around this, but I am having an issue figuring it out. Overall I have a semi-complex Prefetch giving me general ledger entries between a specific date range. Works great, and gives me the data I need. However, now I need to figure out a calulation based on any date before the selected date range but I am unable to prefetch the items again, even while casting to_attr=... from those dates. The error I get is: lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. So how would I take this query in the same queryset and filter by different dates? custom_report = AccountTree.objects.select_related().prefetch_related( 'account_tree_total', 'account_tree_regular', Prefetch('account_tree_header', queryset=AccountTreeHeader.objects.select_related( 'associated_account_from_chart_of_accounts', 'associated_total_account_tree_account__associated_account_from_chart_of_accounts' ).prefetch_related( 'associated_regular_account_tree_accounts', Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts', queryset=GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( 'accounts_payable_line_item', 'accounts_payable_line_item__accounts_payable_entry', 'accounts_payable_line_item__property', 'accounts_payable_line_item__account', 'accounts_payable_line_item__book', 'journal_line_item', 'journal_line_item__journal_entry', 'journal_line_item__payment_id__code', 'journal_line_item__charge_id__code', 'journal_line_item__payment_id__balance', 'journal_line_item__charge_id__balance', 'journal_line_item__payment_id__balance__unit', 'journal_line_item__charge_id__balance__unit', 'journal_line_item__payment_id__balance__unit__building', 'journal_line_item__charge_id__balance__unit__building', 'journal_line_item__property', 'journal_line_item__account', 'journal_line_item__book', ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__gte=start_date, date_entered__date__lte=end_date).order_by('date_entered')), )), # duplicate query causing issue... Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts', queryset=GLAccount.objects.prefetch_related( Prefetch('general_ledger', queryset=GeneralLedger.objects.select_related( 'accounts_payable_line_item', 'accounts_payable_line_item__accounts_payable_entry', 'accounts_payable_line_item__property', 'accounts_payable_line_item__account', 'accounts_payable_line_item__book', 'journal_line_item', 'journal_line_item__journal_entry', 'journal_line_item__payment_id__code', 'journal_line_item__charge_id__code', 'journal_line_item__payment_id__balance', 'journal_line_item__charge_id__balance', 'journal_line_item__payment_id__balance__unit', 'journal_line_item__charge_id__balance__unit', 'journal_line_item__payment_id__balance__unit__building', 'journal_line_item__charge_id__balance__unit__building', 'journal_line_item__property', 'journal_line_item__account', 'journal_line_item__book', ).filter(Q( accounts_payable_line_item__property__pk__in=property_pks, journal_line_item__property__pk__in=property_pks, _connector=Q.OR, ), date_entered__date__lt=start_date).order_by('date_entered'), to_attr='prior_general_ledger'), )), Prefetch('associated_total_account_tree_account__associated_account_from_chart_of_accounts', queryset=GLAccount.objects.prefetch_related( Prefetch('gl_manual_journal_entry', queryset=JournalLineItem.objects.select_related('property').filter( … -
Django serve static files e.g. favicon.ico without `{% load static %}`
I have successfully followed the popular solution for serving static files in Django: I have /myproject/myapp/static/favicon.ico I use <link rel="icon" href="{%static 'favicon.ico' %}" /> in my html template But if I omit the <link rel...> from html then the browser will by default try to GET /favicon.ico which predictably logs Not Found: /favicon.ico How can I tell Django "if anything in urlpatterns does not match the GET string, and that GET string matches a file within a certain directory, just serve that file"? (Then I would be able to write e.g. <script src="/script.js"> and have /myproject/myapp/static-or-wherever/script.js be served without using {% use static %} in a template -- e.g. if I browse to http://my-site.com/script.js manually.) -
how to change this thing in django
how to change this thing in django, then command manage.py runserver is executed. Add some information, for example the server's IP address, Server name, versions of the necessary programs, uptime, anything at all I don't know where to look -
How to add a ModelMultipleChoiceField to a model?
How can I display my model in ModelMultipleChoiceField I have models.py # Модель заказа class ProductsSet(models.Model): # Название набора id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID") name = models.CharField(max_length=200) products_set = models.ManyToManyField('ProductsInstance', related_name='sets') borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) created_date = models.DateField(null=True, blank=True) class ProductsInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID") product = models.ForeignKey('Products', on_delete=models.RESTRICT, null=True) И admin.py @admin.register(ProductsInstance) class ProductsInstanceAdmin(admin.ModelAdmin): list_display = ('product', 'price_for_client', 'borrower', 'coeff') list_filter = ('status','borrower',) fieldsets = ( (None, { 'fields': ('product', 'coeff', 'price_for_client', 'id') }), ('Availability', { 'fields': ('status', 'borrower') }), ) @admin.register(ProductsSet) class ProductsSetAdmin(admin.ModelAdmin): list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount') fields = ['id', 'name', 'products_set', 'created_date', 'borrower', 'status', 'total_amount'] list_filter = ['borrower','created_date','status'] What does it look like for me now enter image description here And this is how I want it: enter image description here -
django if else template tag using object from with template tag
I have an if/else statement that determines which button will be displayed in my base.py template. From doing my research I think I am on the right path, but regardless of if the enddate field is null or populated, the endcast button displays. model: class Cast(models.Model): id = models.AutoField(db_column='Id') startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') class Meta: managed = True db_table = 'Cast' verbose_name_plural = "Cast" get_latest_by = "pk" template block: <div class="top-button-container stickey-top"> {% with last=Cast.objects.latest %} {% if last.enddate %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'caststart' %}">Start Cast</a> </button> {% else %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'cast_end' %}">End Cast</a> </button> {% endif %} {% endwith %} </div> I was expecting the "start cast" button to render when the last objects enddate field is populated. The "end cast" button should render when the enddate field is none. It currently renders the "end cast" button regardless of the last objects enddate field value. -
UniqueConstraint working only in django admin site
Hello I'm facing some issues with the UniqueConstraint class on my model. Here is my model : class ModeleEquipement(models.Model): id = models.AutoField(primary_key=True) fabricant = models.ForeignKey(FabricantEquipement, on_delete=models.SET_DEFAULT, default='') type = models.ForeignKey(TypeEquipement, on_delete=models.SET_DEFAULT, default='') reference = models.CharField(max_length=50, default='') designation = models.CharField(max_length=50, default='') def __str__(self): return str(self.id) class Meta: constraints = [ models.UniqueConstraint(fields=['fabricant', 'type', 'reference', 'designation'], name='unique_model_constraint') ] I have a form in my site to select Fabricant, Type and to fill reference and designation and then post it to add the object in the backend with this code : form = ModeleEquipementForm(request.POST) if form.is_valid(): fabricant = FabricantEquipement.objects.get(id=form.cleaned_data["fabricant"]) type = TypeEquipement.objects.get(id=form.cleaned_data["type"]) ModeleEquipement.objects.create( designation=form.cleaned_data["designation"], reference=form.cleaned_data["reference"], fabricant=fabricant, type=type ) And the form looks like this : class ModeleEquipementForm(forms.Form): fabricant = forms.ChoiceField(widget=forms.Select()) type = forms.ChoiceField(widget=forms.Select()) reference = forms.CharField(label="Référence", max_length=20) designation = forms.CharField(label="Désignation", max_length=50) action = forms.CharField(widget=forms.HiddenInput(attrs={'value': 'add_modele'})) But unfortunately, I can add duplicate rows with this code. And it's also working when I add manually in the MySQL database. But the constraint is working when I use the Admin part of my site to try to add a new row manually. That's the only way I interpreted that my constraint is active in Django model but I don't understand how I can add duplicates with the … -
How to get the browser to render links in streamed content
I am using EventSource to get streamed text content in the browser. The problem is that when I want a link to appear even though I have the correct text, the link doesn't render. This is the text that is outputted (correctly) Here are a few options for single burner camping stoves that you might find suitable:1. The <a href='https://www.bcf.com.au/p/companion-lpg-portable-single-burner-gas-stove/292578.html?cgid=BCF08188'>Companion LPG Portable Single Burner Gas Stove</a> is a great option. It's portable and uses LPG, which is a common fuel type for camping stoves. This makes it a practical choice for camping trips.2. Another good choice is the <a href='https://www.tentworld.com.au/buy-sale/companion-1-burner-wok-cooker-stove'>Companion 1 Burner Wok Cooker Stove</a>. This stove is also portable and has a wok cooker, which adds versatility to your cooking options.For more options, you can check out the range of <a href='https://www.anacondastores.com/camping-hiking/camp-cooking/camping-stoves?q=:relevance:brand:coleman:dealType:OnSale:dealType:CLUB%20PRICE'>Camping Stoves</a> at Anaconda stores. They offer a variety of brands and styles, so you might find other single burner stoves that suit your needs. And here is the html/js: <div id="response-display"></div> <script> const responseDisplay = document.getElementById('response-display'); const eventSource = new EventSource('http://127.0.0.1:8000/do-chat'); eventSource.onmessage = function(event) { console.log('We have a message'); console.log(event.data); // Append received data to the div // responseDisplay.textContent += event.data + "\n"; responseDisplay.innerHTML += event.data; }; … -
Issues with django-channels deployment on elastic-beanstalk
I am working on deploying my django app on Elastic Beanstalk using gunicorn for my wsgi and daphne to handle asgi. I managed to get my app deployed but the websockets are not functioning properly. I was able to test that the EC2 instance connects to the redis cache by running the code below on my elastic beanstalk environment : eb ssh source /var/app/venv/*/bin/activate cd /var/app/current/ python manage.py shell >>> import channels.layers >>> from asgiref.sync import async_to_sync >>> channel_layer = channels.layers.get_channel_layer() >>> async_to_sync(channel_layer.send)('test_channel', {'foo': 'bar'}) >>> async_to_sync(channel_layer.receive)('test_channel') >>> {'foo': 'bar'} # <---------- I was able to receive a response However, I was not able to run the initiate the daphne server on my EC2 instance manually : daphne -b 0.0.0.0 -p 5000 tattoovalley.asgi:application The code above generated the following error : ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. However I have configured the DJANGO_SETTINGS_MODULE environment module in my .ebextensions config file : .ebextensions/01_env.config option_settings: aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static value: static/ aws:elasticbeanstalk:container:python: WSGIPath: tattoovalley/wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: tattoovalley.settings PYTHONPATH: /opt/python/current/app/tattoovalley:$PYTHONPATH aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /ws/* Process: websocket Priority: 1 … -
React make messages of other user appear different color
I am making a chat app with django channels and react and I want messages from a different user to appear at a different color. To create the messages I save them in state const [messages,setMessages] = useState([]) chatSocket.onmessage = function(e) { if (ran == true) { const data = JSON.parse(e.data); setMessages(old => [...old, <p ref={oneRef} className={currentUser[0]?.username}>{data.message}</p>]) } } For every message's className it is the current user's username. I want to basically do something like this. {currentUser.username} { background:'red' } And if not then appear a different color. How can I make it work. -
Cal-heatmap, date not converted with good timezone
I have a problem with the cal-heatmap library and the timezone. I use Django, and I have a date in UTC like this: 2023-10-04T14:03:31.040000+00:00 I want to use the timezone Europe/Paris so if I convert the date with timezone, I have this: 2023-10-04T16:03:31.040000+02:00. I don't arrive to display the good date in cal-heatmap, I have always the date with hour 14... I only get it if I use the date 2023-10-04T16:03:31.040000+00:00 (So the good hour with UTC timezone) So I tried with the UTC timestamp (1696428211040), but I have always the same hour even if I change the timezone in the date key options in cal-heatmap... Do you have a solution? -
how should i add the tradingview chart to my website usding python/django. i am using louisnw01/ lightweight-charts-python from github
i am using the following code : import pandas as pd from lightweight_charts import Chart def get_bar_data(symbol, timeframe): if symbol not in ('AAPL', 'GOOGL', 'TSLA'): print(f'No data for "{symbol}"') return pd.DataFrame() return pd.read_csv(f'bar_data/{symbol}_{timeframe}.csv') def on_search(chart, searched_string): # Called when the user searches. new_data = get_bar_data(searched_string, chart.topbar['timeframe'].value) if new_data.empty: return chart.topbar['symbol'].set(searched_string) chart.set(new_data) def on_timeframe_selection(chart): # Called when the user changes the timeframe. new_data = get_bar_data(chart.topbar['symbol'].value, chart.topbar['timeframe'].value) if new_data.empty: return chart.set(new_data, True) def on_horizontal_line_move(chart, line): print(f'Horizontal line moved to: {line.price}') if __name__ == '__main__': chart = Chart(toolbox=True) chart.legend(True) chart.events.search += on_search chart.topbar.textbox('symbol', 'TSLA') chart.topbar.switcher('timeframe', ('1min', '5min', '30min'), default='5min', func=on_timeframe_selection) df = get_bar_data('TSLA', '5min') chart.set(df) chart.horizontal_line(200, func=on_horizontal_line_move) chart.show(block=True) here chart.show() gives the Python webview app but I want to integrate this chart into my own website. I tried searching the web a lot but every time I get the Tradingview lightweight chart widget or its javascript library that the trading view provides by itself but not using the above python library. -
Github Action exits with code 1 even if command returns 0
I have a Django application and a step in the workflow that should check if any migrations need to be done: - name: Check outstanding migrations run: | python manage.py makemigrations --check The makemigrations --check command exits with 0 when I run it locally in Powershell but the Github Action workflow fails with Error: Process completed with exit code 1.. The only output of the command is a log warning message that I set. -
Is there a good way to access the "model" attribute for a ListView in Django so that it can be used in a template?
thanks in advance for the help. Long story short, I'm attempting to build a CRM-type application in Django (think of it as a Salesforce clone, if you're familiar). I want to be able to access the model attribute that I'm providing to my ExampleListView class. I'm reading through the docs on the ListView class but either can't find how to do it, or I'm just missing the connection. For context here's some example code (what I've got so far isn't far off of the boilerplate from the docs): views.py: class ExampleListView(ListView): model = Example app/templates/app/example_list.html: {% block content %} <h2>Examples</h2> <!-- Ideally, I'd love to be able to create this dynamically --> <table> <thead> <tr> {% for header in ???? %} <!-- Here's what I can't figure out --> <th>{{header}}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for example in object_list %} --- Display record data here --- {% endfor %} </tr> </tbody> </table> {% endblock %} I've thought about the idea of trying to add the model attribute to the context dictionary, but I'm unsure how to go about it. Am I on the right track? -
Some Models permission are missing from the permission list in django admin
Account models has lot of the models but only the user models permission are visible -
Django-table wrong output
I have django model: class Sessions(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey('Users', on_delete=models.CASCADE, related_name='user') session_start = models.DateTimeField() last_confirmation = models.DateTimeField(null=True) error_status = models.CharField(max_length=50, default="Lost connection.", null=True) session_end = models.DateTimeField(null=True) status = models.CharField(null=True, max_length=1) And I have a view function which must return QuerySet with three columns ( 'session_start','last_confirmation',differenc_time ('last_confirmation' - 'session_start'): def user_home(request): info = Sessions.objects.filter(user=request.user.id).annotate( time_difference=ExpressionWrapper( F('last_confirmation') - F('session_start'), output_field=fields.DurationField() ) ).values('last_confirmation', 'session_start', 'time_difference') return render(request, 'home_user.html', context={'data': info}) But in browser i get all columns: -
Aspose.slides python error convert a pdf to PowerPoint ( ppt )
I want to convert a pdf to PowerPoint ( ppt ) using the Aspose library with python and I got this error below: pres.slides.add_from_pdf(pdfPath) RuntimeError: Proxy error╗): Bad state (unknown compression method (0x47)) the code I wrote to convert pdf to ppt is the following : def pdf2ppt(pdfPath, pptPath): with slides.Presentation() as pres: pres.slides.remove_at(0) pres.slides.add_from_pdf(pdfPath) pres.save(pptPath, slides.export.SaveFormat.PPTX) I would really appreciate the help. -
a function for print S3 data to html by usiong django
I had a correct connection to S3, because i am able to upload pdf file to Amazon S3, but i can't display the S3 data into django template my expecting result is when i open the page to view pdf that upload to Amazon S3 it should show all the pdf that had upload. But right now nothing had show in django template Following is my code models.py class PDFDocument(models.Model): title = models.CharField(max_length=100) pdf_file = models.FileField(upload_to='pdfs/') urls.py path('display-pdf/<str:file_key>/', views.DisplayPDFView, name='display_pdf'), view.py class DisplayPDFView(View): def get(self, request, file_key, *args, **kwargs): print(s3) s3 = boto3.client('s3') bucket_name = settings.AWS_STORAGE_BUCKET_NAME try: print('ds') response = s3.get_object(Bucket=bucket_name, Key=file_key) pdf_content = response['Body'].read() print(response) # Set the appropriate content type for PDF response = HttpResponse(pdf_content, content_type='application/pdf') response['Content-Disposition'] = f'inline; filename="{file_key}"' return response except s3.exceptions.NoSuchKey: return HttpResponse('PDF not found.', status=404) except: print("fucking error") viewCVpage.html {% for pdf_document in pdf_documents %} <div class="col-md-4 col-sm-12"> <div class="card" style="width: 100%; float: left; margin-bottom: 10px;"> <!-- Display the PDF using an object tag --> <object data="{{ pdf_document.pdf_file.url }}" type="application/pdf" style="width: 100%; height: 400px;"> <p>Unable to display PDF. Please <a href="{{ pdf_document.pdf_file.url }}">download the PDF</a> instead.</p> </object> </div> </div> {% endfor %} -
Django Cors Headers stopped working all of a sudden
I have set up my back-end with Django over 10 months ago and it's been working perfectly fine... However, after changing virtual environment recently and re-downloading the required packages, I am receiving cors errors. Below is my code for the cors issue I'm facing. ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'playgroundapp', 'budgetapp', 'rest_framework', 'rest_framework.authtoken', 'djoser', "corsheaders" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", "https://mywebsite.com" ] Django version: 4.2.6 This is the order on my settings.py Error I'm currently getting is: Access to fetch at 'https://myexamplebackend.com' from origin 'https://myexamplewebsite.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Not sure if it's related but after changing virtual environments I am getting the error: "WARNING:root:No DATABASE_URL environment variable set, and so no databases setup" on VS Code... I've tried "heroku config" to fix the problem but it didn't solve the issue. What did I try? I have read a lot … -
How can I solve this error? : 'WSGIRequest' object has no attribute 'objects'
I am trying to create a web app for managing expenses for a company but I ran into a problem that I quite don't know how to work around it. The error message is 'WGSIRequest' object has no attribute 'objects'. I am new in python that's why it is stressing me out. I have linked the line that spawns the error as well as my views.py file as well as my urls.py. The error: 'WGSIRequest' object has no attribute 'objects' Line associated with error: user = request.objects.filter(email=email) My view.py file: from django.shortcuts import render, redirect from django.views import View import json from django.http import JsonResponse from django.contrib.auth.models import User from validate_email import validate_email from django.contrib import messages from django.core.mail import EmailMessage from django.contrib import auth from django.utils.encoding import force_bytes, force_str, DjangoUnicodeDecodeError from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse from .utils import token_generator from django.contrib.auth.tokens import PasswordResetTokenGenerator # Create your views here. class EmailValidationView(View): def post(self, request): data=json.loads(request.body) email=data['email'] if not validate_email(email): return JsonResponse({'email_error': 'Email is invalid'}, status=400) if User.objects.filter(email=email).exists(): return JsonResponse({'email_error': 'Sorry email in use, choose another one'}, status=409) return JsonResponse({'email_valid': True}) class UsernameValidationView(View): def post(self, request): data=json.loads(request.body) username=data['username'] if not str(username).isalnum(): return JsonResponse({'username_error': …