Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'
i dont want to have username field in django and removed it but now when i want to create a superuser got an error for missing username field!! error: TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' my user model class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Unpack the list and put as variable
I have source code like this chain accept the multple number of lists. list1 = [1,2,3] list2 = [1,2,3] list3 = [1,2,3] chain(list1,list2,list3) However I want to treat list1 list2 list3 as one list and put this in chain total = [list1,list2,list2] chain(total) # it doesn't work , ochain doesn't accept the list. Is there any good way to do this? -
Apache virtual hosts on subdirectories
I am trying to setup Apache to serve multiple apps on one IP-Address over subdirectories. Lets say, I would like to access App1 over http://aaa.bbb.ccc.ddd/app1 and App2 over http://aaa.bbb.ccc.ddd/app2. Both, App1 and App2, are independent django projects. I ensured, that both apps are working fine by serving only one of them over Apache. I added the following lines to the httpd.conf file of Apache: # App1 <VirtualHost *:80> DocumentRoot "D:/Projects/App1/App1" ServerName App1 <Directory "D:/Projects/App1/App1"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /app1 "D:/Projects/App1/App1/wsgi.py" </VirtualHost> # App2 <VirtualHost *:80> DocumentRoot "D:/Projects/App2/App2" ServerName App2 <Directory "D:/Projects/App2/App2"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /app2 "D:/Projects/App2/App2/wsgi.py" </VirtualHost> Working like this results into an error saying "Forbidden, You don't have permission to access this resource." when I call http://aaa.bbb.ccc.ddd/app2 from another machine. Similar to this, if I put the App2 virtual host in front of the App1 virtual host, I can not access http://aaa.bbb.ccc.ddd/app1 anymore. So it is either App1 or App2 that is accessible, but never both of them. First question: Is my idea of serving to webpages over sub-URL's even possible? If not, what would be the alternative? Using different ports for different applications? If it is a "valid" approach, … -
extract signature from SignatureField in Django
here i am using python3 and Django 3.0 Here am i saving the signature into my database and now i need to display this signature in my pdf file But i am not able to display it in the pdf file here is my views.py def jobspecific_view_1(request, pk): form = CustomerSignatureForm(request.POST or None) if form.is_valid(): customer_signature = form.cleaned_data.get('customer_signature') if customer_signature!=None: signature_picture = draw_signature(customer_signature) output = io.BytesIO() signature_picture.save(output, "PNG") contents = base64.b64encode(bytes('output', 'utf-8')) customer_data = contents output.close() job = AddJob.objects.get(id=pk) job.signature = customer_data job.save() ...... ...... here is my views.py for generating the pdf def render_to_pdf(template_src, context_dict, pdf_title): template = get_template(template_src) context = Context(context_dict) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = "attachment; filename={0}".format( unidecode( pdf_title.replace( ',', '').replace( ';', '').replace(' ', '_'))) logger.debug('Content-Disposition: {0}'.format(response['Content-Disposition'])) return response logger.error(pdf.err) return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html)) def generate_pdf_view(request, pk): client = request.user.client job_id = AddJob.objects.filter(id=pk) viewed_job = get_object_or_404(AddJob, id=pk, created_by__client=client) job_data={} for val in job_id: job_data['job_id'] = pk job_data['title'] = val.title job_data['job_number'] = val.job_number job_data['customer_signature_1'] = val.customer_signature_1 ...... ...... pdf_title = u'{0}_{1}_{2}.pdf'.format( job_data['title'], job_date.strftime('%d_%m_%Y'), job_data['job_type']) return render_to_pdf('jobs/jobpdf.html', { 'pagesize':'A4', 'job_data': job_data, 'viewed_job': viewed_job, 'request': request, }, pdf_title) Here is my forms.py … -
Django floatformat and intcomma not formatting the string right
I have been trying to use floatformat and intcomma to format a string with only 1 decimal place and with the dot divider for thousands So I'd like to get 1 -> 1,0 4000 -> 4.000,0 4567,56 -> 4.567,6 By using intcomma only I get 4.567,56 By using floatformat and intcomma I get 4,567,56 I have tried in the settings to use USE_I18N = True USE_L10N = True DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' but nothing changed, how does this work? -
Cannot properly save to a db with OneToOne relationship
The flow of what I want to do is the following: I have two tables, namely Event and Result. The Event table is connected with ForeignKey with a user and the Result table is connected with OneToOne relationship with Event. In my views.py I have one POST and one GET. In POST, I take some data and save it in the table Event. In GET, I solve an optimization problem and I want to save the solution into Result. The models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) The serializers.py is as follows: from rest_framework import serializers from vpp_optimization.models import Event, Result class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') class ResultSerializer(serializers.ModelSerializer): HVAC_flex = serializers.ListField(child=serializers.FloatField()) DHW_flex = serializers.ListField(child=serializers.FloatField()) lights_flex = serializers.ListField(child=serializers.FloatField()) class Meta: model = Result fields = ('__all__') The views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework … -
nameError: name 'request is not defined
I'm trying to build an absolute url with reverse but I get the above error. Code: def get_endpoint(payload): url = request.build_absolute_uri(reverse("app-start-conversation")) data = json.dumps(payload) response = requests.post(url, data, headers=head) Urls.py: path( "api/v2/app/startconversations", views.StartConversation.as_view(), name="app-start-conversation, ) I get the error nameError: name 'request is not defined How do I import request? The reason I need the full url is because with reverse alone, when I run the app locally I get the following error and I do not want to hardcode 120.0.0.1:8000/ to the url. requests.exceptions.MissingSchema: Invalid URL '/api/v2/app/startconversations': No schema supplied. Perhaps you meant http:///api/v2/app/startconversations? -
Importing django modules without settings being configured
Consider following simple scenario. Given File common.py from data import MyModel # This is a Model inheriting django.db.models.Model def foo(bar: MyModel): print(bar) def other_func(): pass And given file main.py, using one of the functions in common, but not the other one that depends on django. import common from django.conf import settings if __name__ == "__main__": config_file = sys.argv[1] # This would be argparser in real life scenario settings.configure(....config_file...) common.other_func() This format is how i believe most main functions would look like since settings often depend on environment variable, config files or command line arguments. I'm not able to run this code because any time one simply imports a django model, it attempts to load settings and access the database. With following error: raise 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. Next attempt, move the settings.configure above the imports inside main.py, from django.conf import settings settings.configure(.....) import common This works, but it infects the entire code base, making it impossible to import common from any other modules and in unit tests. Unless every single potential entrypoint is guaranteed to also call settings.configure first. Last … -
Can't get form class object in template view
I want to get the form object from self.Form This is my form class ActionLogSearchForm(forms.Form): key_words = forms.CharField(required=False) and I set form as form_class, however I can't fetch the form data in view class ActionLogListView(LoginRequiredMixin, ListSearchView): template_name = "message_logs/action_log.html" form_class = ActionLogSearchForm def get_queryset(self): res = [] form = self.form ## somehow form is None print(form.cleaned_data) # error occurs here. 'NoneType' object has no attribute 'cleaned_data' I think this is the simplest set, but how can I make it work? -
Can't import a module in Django project
This is my django project folder: mysite ├── mypage │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── mysite │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── utils ├── __init__.py ├── __pycache__ │ └── __init__.cpython-38.pyc └── util.py This is the error message that I get when I run the server. Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/checks/urls.py", … -
How to get the selected foreign key's value?
Models: class Item(models.Model): name = [...] # unique quantity = [..integer_field..] class Sales(models.Model): sold_to = [...] sold_item = foreign key to Item sold_quantity = [..integer field..] I want to make sure that if the selected Item has the quantity of 5, and you pass 6 or more to the sold_quantity, throw a validation error saying "You have only X in stock and wanted to sell Y". I tried to override the save method, but however I try to do so, it changes nothing. When I try to access self.sold_item, it returns the name of the selected item. When I try to do item.objects.get(name=self.sold_item), whatever I do it returns just the name of the item and I can't access other fields (known as Quantity). Conc: Item.objects.get(name=self.sold_item) returns the name of the item. using the same but Filter instead of Get returns a queryset, which contains <Item: the items name> and I can't access other fields of it. -
How to show terminal result into HTML in Django? [duplicate]
terminal shows hello I want to put "hello" on HTML. def test(request): cmd = './hello.sh {}'.format(res) subprocess.run(cmd, shell=True) return HttpResponse() -
Django aggregation for 3 related tables with one to one and one to many relation
I have 3 django models (tables), let's say singer, album, and song. singer has columns id, album_id (foreign key to album table), first_name, last_name album has columns id, title, num_of_album_wishlist, num_of_album_stars song has columns id, album (foreign key to album table) num_of_streams, song_duration_in_secs Singer has one to one relation with album and album has one to many relation with song. these tables are just a dummy representation and don't necessarily makes sense but adequately demonstrate the problem. Have to create a queryset where for each singer (in the queryset), have to find out sum of num_of_album_wishlist, num_of_album_stars from song table, as well as total_num_of_songs for the user, sum of num_of_streams and song_duration_in_secs in a single queryset. Singer.objects.annotate( wishlist=Sum('album__num_of_album_wishlist'), stars=Sum('album__num_of_album_stars'), streams=Sum('album__song_group__num_of_streams'), duration=Sum('album__song_group__song_duration_in_secs') ) The query above gives wrong results pertaining to one to many relation of album table with song table. subq = Singer.objects.annotate( streams=Sum('album__song_group__song_duration_in_secs'), duration=Sum('album__song_group__song_duration_in_secs') ).filter(pk=OuterRef('pk')) queryset = Singer.objects.prefetch_related( 'album').annotate( streams=Subquery(subq.values('streams')), duration=Subquery(subq.values('duration')), wishlist=Sum('album__num_of_album_wishlist'), stars=Sum('album__num_of_album_stars'), ) Using Subquery to tackle this works but generates different blocks for joining in SQL query (which further results in a long time to execute the query) Any suggestions on how to tackle this problem? -
Django application fails with error "NameError: name '_mysql' is not defined" [closed]
With Python 3.7.9, our Django application always fails with the error "NameError: name '_mysql' is not defined". We tried to install and uninstall multiple YUM packages, but the error stays in the same way. Please see the pip package list attached in the Details section below, and let me know if you need to see the yum package information. We highly appreciate your help. The pip list: amqp==5.0.2 anyjson==0.3.3 appdirs==1.4.4 arrow==0.13.2 asgiref==3.3.1 attrs==20.3.0 backcall==0.2.0 backports.functools-lru-cache==1.6.1 beautifulsoup4==4.9.3 billiard==3.6.3.0 caniusepython3==7.2.0 celery==5.0.4 certifi==2020.12.5 chardet==3.0.4 click==7.1.2 click-didyoumean==0.0.3 click-plugins==1.1.1 click-repl==0.1.6 decorator==4.4.2 distlib==0.3.1 Django==3.1.4 django-cors-headers==3.5.0 django-debug-toolbar==3.2 django-easy-pjax==1.3.0 django-rest-auth==0.9.5 djangorestframework==3.12.2 fake-factory==9999.9.9 fissix==20.8.0 gunicorn==20.0.4 idna==2.10 importlab==0.5.1 importlib-metadata==3.1.1 ipython==7.19.0 ipython-genutils==0.2.0 jedi==0.17.2 kombu==5.0.2 line-profiler==3.1.0 lxml==4.6.2 mock==4.0.2 modernize==0.8.0 mysqlclient==2.0.1 networkx==2.5 ninja==1.10.0.post2 packaging==20.7 parso==0.7.1 pexpect==4.8.0 pickleshare==0.7.5 Pillow==8.0.1 pip==21.0 pip-review==1.1.0 pipdeptree==1.0.0 prompt-toolkit==3.0.8 ptyprocess==0.6.0 Pygments==2.7.3 pyparsing==2.4.7 python-dateutil==2.8.1 pytype==2020.12.2 pytz==2020.4 PyYAML==5.3.1 qrcode==6.1 requests==2.25.0 setproctitle==1.2.1 setuptools==51.3.3 six==1.15.0 soupsieve==2.0.1 sqlparse==0.4.1 traitlets==5.0.5 typed-ast==1.4.1 urllib3==1.26.2 vine==5.0.0 wcwidth==0.2.5 wheel==0.36.2 yet-another-django-profiler==1.1.0 zipp==3.4.0 -
django celery queue task
api View class IsBuyNowAvailable(APIView): permission_classes = [RazorpayPermission] def post(self, request, format=None): data = request.data res = buy_now_available.delay(data) print("Celery res", res) if res.get("success"): return Response(res, status=status.HTTP_200_OK) else: return Response(res, status=status.HTTP_400_BAD_REQUEST) celery task from celery import Celery from settings.settings import CELERY_BROKER_URL app = Celery("celery_app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task() def buy_now_available(data): asset_id = data.get("asset_id") asset = Asset.objects.filter(id=asset_id).get() return {"success": True, "asset_id": asset.id} web | Celery res b926b9b1-a3cd-4461-a73f-5baf8f7e51c9 celery_1 | [2022-04-14 05:17:03,198: INFO/MainProcess] Task api.tasks.buy_now_available[b926b9b1-a3cd-4461-a73f-5baf8f7e51c9] received celery_1 | [2022-04-14 05:17:03,254: INFO/ForkPoolWorker-1] Task api.tasks.buy_now_available[b926b9b1-a3cd-4461-a73f-5baf8f7e51c9] succeeded in 0.05360425729304552s: {'success': True, 'asset_id': 425} Here i am able to see the task in celery but it returns task id and in celery the response is generating . I wants to make it delay and wait till the response ready and the reponse should come inside my view not only in celery task so that i can send that response to user . The reason i want this becvause i am implementing queue task. If 10 users called that api same time then it will wait for next user untill first one is complete. and put rest request in queue before the first request is complete. Please take a look and tell me how can i achive this -
Django deploy Heroku error 500 Debug = False
Im trying to deply my django application Main tools that im utilizing that i dont know if require a special configuration: Stripe (Payment Method - but its not in my index page so It shouldnt be because of it) Mailgun(but i commented in my settings and im also not utilizing in Index page, so probably couldn't be it) Procfile release: python3 manage.py migrate web: gunicorn store.wsgi --preload --log-file – My Env Variable setters: from store.settings.base import * env = environ.Env() DEBUG = env.bool("DEUBG", False) SECRET_KEY = env("SECRET_KEY") DATABASES = { 'default': env.db(), } My settings: import django_on_heroku import os import environ from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent DEBUG = True ALLOWED_HOSTS = ['afternoon-brook-19806.herokuapp.com', '127.0.0.1', 'localhost'] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [BASE_DIR / 'templates/static'] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # BUG MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' CART_SESSION_ID = 'cart' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' PUBLISHED_KEY = 'pk_live_xxxxxxx' STRIPE_SECRET_KEY = 'sk_live_xxxxxxxxx?' STRIPE_ENDPOINT_SECRET = 'xxxxxxx?' django_on_heroku.settings(locals()) Where I get the error 500 in Heroku Logs: 2022-04-14T04:33:35.002535+00:00 heroku[router]: at=info method=GET path="/account/login/" host=afternoon-brook-19806.herokuapp.com request_id=ac9b6df0-3598-427e-a672-9519419de8b3 fwd="177.124.150.24" dyno=web.1 connect=0ms service=68ms status=500 bytes=451 protocol=https 2022-04-14T04:33:35.003893+00:00 app[web.1]: 10.1.51.13 - - [14/Apr/2022:01:33:35 -0300] "GET /account/login/ HTTP/1.1" 500 145 "https://afternoon-brook-19806.herokuapp.com/account/register/" "Mozilla/5.0 (Windows NT … -
When sorting the chained queryset, 'itertools.islice' object has no attribute 'next'
Thanks to this article https://stackoverflow.com/questions/431628/how-can-i-combine-two-or-more-querysets-in-a-django-view#:~:text=Use%20union%20operator%20for%20queryset,querysets%20by%20using%20union%20operator.&text=One%20other%20way%20to%20achieve,to%20use%20itertools%20chain%20function. I use QuerySetChain class to concatenate multiple queryset class QuerySetChain(object): """ Chains multiple subquerysets (possibly of different models) and behaves as one queryset. Supports minimal methods needed for use with django.core.paginator. """ def __init__(self, *subquerysets): self.querysets = subquerysets def count(self): """ Performs a .count() for all subquerysets and returns the number of records as an integer. """ return sum(qs.count() for qs in self.querysets) def _clone(self): "Returns a clone of this queryset chain" return self.__class__(*self.querysets) def _all(self): "Iterates records in all subquerysets" return chain(*self.querysets) def __getitem__(self, ndx): """ Retrieves an item or slice from the chained set of results from all subquerysets. """ if type(ndx) is slice: return list(islice(self._all(), ndx.start, ndx.stop, ndx.step or 1)) else: return islice(self._all(), ndx, ndx+1).next() Now I pick up some tables md = sm.Message.history.all() sw = sm.Worker.history.all() st = sm.Template.history.all() gp = sm.GlobalParam.history.all() matches = QuerySetChain(md, sw, st,gp) # it makes one queryset successfully result_list = sorted( #error occurs here matches, key=lambda instance: instance.updated_at) When I am trying to sort the items, The error occurs like this below. 'itertools.islice' object has no attribute 'next' when sorting chained object Is it possible to sort this? -
Should I compress python files in Django?
I know that I should compress frontend files (HTML, CSS, JS) to increase the security and loading speed of a website. But how about the backend files (for example Python)? Should I compress them too? Do I get any benefits from doing that? -
Django hot reload only working on certain files
I have this weird issue where not all file edits are being picked up by the hot reloader for Django. I have this structure: / app/ ... apps in here. config/settings.py manage.py Now, any changes to config/settings.py or manage.py will result in the django runserver reloading. But any changes to files inside app/... don't trigger a reload - I have to go and add a newline to manage.py and save (quite irritating). Any ideas why this might be? At first I thought it was a docker thing, and it was only picking up files in the base dir, but then changes to config/settings.py also trigger the reload, so clearly it can see deeper. -
python image scrapper become base64 not real urls
I have scrapper tools, but my code are always scrap base64 instead of real urls,here is my code: import requests from bs4 import BeautifulSoup baseurl = "https://www.tes.com/search?q=tes" headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0"} r = requests.get(url=baseurl, headers=headers) soup = BeautifulSoup(r.content, 'lxml') for product_images in soup.findAll('div', attrs={'class': 'ArOc1c'}): print (product_images.img['src']) the result is something like: data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== I also use "soup = BeautifulSoup(r, 'html.parser')" but it is still the same. -
How can i using the setting of CKEDITOR_CONFIGS in class ckeditor?
i have already set CKEDITOR_CONFIGS in settings.py but when i try to use <td><textarea class="ckeditor" name="remark" id="test1" cols="30" rows="10"></textarea></td> both are different style how can i make ckeditor in class using the style i have set in CKEDITOR_CONFIGS -
How to create key to get a request to Django API?
I am creating a database with Django, and I am accesing it with Excel and Apps Script. I can't log in into my superuser account (the only account I'll be having). Therefore, I want to know if there is a way to set a key, or a password, passed through an HTTP header, that I can use to access my API. Currently I only have one API get method, but I'll have more create, update, etc., and I want to be able to use the same key for these as well. It is a really simple Django application deployed in heroku, so I am not using django-REST-framework, nor graphene-django. So if the solution can come without installing anything else, it would be nice. However, if this is not possible, it is better if the solution comes through graphene-django, since I have used it before, and I am more familiar with it. It is important to notice that both the excel file and the apps script are private, since I am using django as a database manager for a small, personal project. Thank you very much in advance! -
How do i change what django looks for in .filter()?
take this example code: from .models import Employees filters = { "name" : request.GET.get("name"), "work_place" : request.GET.get("work_place_filter") } for index, item in enumerate(filters): key = list(filters.keys())[index] value = filters[item] flykninger = Employees.objects.filter(key = value) what im trying to do here is to change what key the filter() function compares the value to if the input fields are not None. But whenever i try to run my own code that includes this snippet, i get Cannot resolve keyword 'key' into field. Choices are: alder... How do i do this? is there another way to do it that i'm not aware of? Thanks -
Is it possible to edit the page_obj before passing template?
I can catch <class 'django.core.paginator.Page'> in get_context_data function of django view class. What I want to do is alter the showing item and get it back to <class 'django.core.paginator.Page'> again. django.core.paginator.Page source code is here. https://docs.djangoproject.com/en/4.0/_modules/django/core/paginator/ I found it has object_list,so I try to change def get_context_data(self): temp = super().get_context_data() print(type(temp['page_obj'])) #<class 'django.core.paginator.Page'> new_object_list = [] for t in temp['page_obj'].object_list:## I can iterate the item here. # make new_object_list here temp['page_obj'].object_list = new_object_list print(temp) # nothing changes return temp However object_list doesn't change. -
no module error on python when I connect EC2 with ssh
I am a junior(more like kindergarten to be specific) web developer and I get some project which already exists. it is deployed on EC2 and I had to deal with some python files. I wanted to execute python files, So I connect project with ssh via key files. and I tried to execute python files but I couldn't and get a message like this. ModuleNotFoundError: No module named 'bs4' Well, I thought I could run a file because modules are already downloaded on EC2server?? how can I solve this and run python file on ssh? ps. when I make a new python file and run print("pypy") It runs OK thx for reading, your help will be appreciated.