Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change form input from text value to model instance in django
I want to create Aviz entry using AJAX form. In the form the input material has a jquery ui function autocomplete, that gets all the material names from the Material Model. When I submit the form I get this error in the console : ValueError: Cannot assign "'ADEZIV LIPIRE VATA MINERALA, CT 180, 25 KG CERESIT'": "Aviz.material" must be a "Material" instance. I know that I need to get the input from the form, and turn it in a Material instance...but do not know how/did not find any info about this. models.py: class Material(models.Model): name = models.CharField(max_length=255,default=None,verbose_name='Nume material') class Aviz(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE,related_name="aviz") quantity = models.FloatField(default=0,verbose_name="Cantitate") views.py: class AvizCreate(LoginRequiredMixin, AjaxCreateView): model = Aviz form_class = AvizForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['pk'] = self.kwargs.get('centrudecost') return kwargs @login_required def autocomplete(request): if 'term' in request.GET: qs = Material.objects.filter(name__icontains=request.GET.get('term')) name = list() id = list() cod_nexus = list() name = [prod.name for prod in qs] id = [prod.pk for prod in qs] cod_nexus = [prod.cod_nexus for prod in qs] return JsonResponse({"name": name, "id":id, "cod_nexus":cod_nexus}, safe=False) templates.html $('#id_material').autocomplete({ source: function(request, response) { $.ajax({ url: "{% url 'materiale:autocomplete' %}", dataType: "json", data: { term: request.term }, success: function(data) { response($.map(data.name, function(value, key) { return … -
i working on django application to charge a user before posting his products. i want to offer a free option, how to archive this and save add with sti
i am working on django application where admin can set pricing,and give coupon, my proble is how to offer a free option or free listing whe you are using stripe. this is a function on my views.py your text@login_required(login_url='/users/login') def create_ad_func(request): user = request.user if request.method == "POST": data = dict(request.POST) data = clean(data) ad = AdList.objects.create_ad(**data) img_counter = 0 img_files = request.FILES if len(request.FILES) > 0: for ad_img in request.FILES: print(img_files[ad_img]) upload_img(ad_img, img_files, ad) else: url = upload_image(request.FILES[ad_img], ad.id, img_counter) img_counter = img_counter + 1 data[ad_img] = url date_time = arrow.utcnow().format('YYYY-MM-DD HH:mm:ss') data['post_date'] = date_time pprint(data) AdList.objects.filter(pk=ad.id).update(**data) objectss = AdList.objects.filter(pk=ad.id) subscription_list = ['urgent_ad', 'regular_ad', 'featured_ad'] for key in data.keys(): if key in subscription_list: ad_subscription = AdSubscription.objects.values()[0] price = ad_subscription[key] charge = ad_subscription[key] * 100 print(price, charge) key = settings.STRIPE_PUBLISHABLE_KEY return render(request, 'checkout.html', {"user": request.user, 'ad': ad, 'price':price, 'key':key, 'charge':charge}) else: ad_subscription = AdSubscription.objects.values()[0] return render(request, 'ad-list-cat.html', {"user": request.user, "subscription": ad_subscription}) and this is my manage.py `class AdListManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_ad(self, **data): """ Create and save a User with the given email and password. """ email = data["email"] email = self.normalize_email(email) ad = self.model(**data) … -
Django+Heroku+MySQL - R10 - Error R10 (Boot timeout) -> Web process failed to bin d to $PORT within 60 seconds of launch
I am running: git push heroku master heroku open My Procfile: release: python manage.py migrate web: waitress-serve --listen=localhost:8000 storefront.wsgi:application My Log: 2023-02-20T05:47:22.531135+00:00 heroku[web.1]: State changed from crashed to starting 2023-02-20T05:47:41.700316+00:00 heroku[web.1]: Starting process with command `waitress-serve --liste n=localhost:8000 storefront.wsgi:application` 2023-02-20T05:47:44.005026+00:00 app[web.1]: Serving on http://127.0.0.1:8000 2023-02-20T05:48:05.000000+00:00 app[heroku-redis]: source=REDIS addon=redis-acute-18444 sample#activ e-connections=1 sample#load-avg-1m=0.195 sample#load-avg-5m=0.355 sample#load-avg-15m=0.4 sample#read -iops=0 sample#write-iops=0 sample#memory-total=16084924kB sample#memory-free=9997524kB sample#memory -cached=3236532kB sample#memory-redis=335784bytes sample#hit-rate=1 sample#evicted-keys=0 2023-02-20T05:48:42.244149+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bin d to $PORT within 60 seconds of launch 2023-02-20T05:48:42.327725+00:00 heroku[web.1]: Stopping process with SIGKILL 2023-02-20T05:48:42.567303+00:00 heroku[web.1]: Process exited with status 137 2023-02-20T05:48:42.623286+00:00 heroku[web.1]: State changed from starting to crashed 2023-02-20T05:48:57.777654+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path ="/" host=vin-prod.herokuapp.com request_id=d46cea93-368f-4c0a-855f-7e482bc4e826 fwd="174.82.25.34" d yno= connect= service= status=503 bytes= protocol=https 2023-02-20T05:48:58.128022+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path ="/favicon.ico" host=vin-prod.herokuapp.com request_id=8cbbf38a-b258-4ae0-8aef-9d451c099b33 fwd="174. 82.25.34" dyno= connect= service= status=503 bytes= protocol=https I am running my code on windows(VS code). I tried running heroku ps:scale web=1. It works fine : Scaling dynos... done, now running web at 1:Basic In my heroku dynos are set to my waitress-serve. [enter image description here](https://i.stack.imgur.com/eaIyM.png) Please help me out -
I want to display this python dataframe values as a table so in html how can I do that?
performersInfo = MyUser.objects.prefetch_related('newreport_set').filter( Q(is_active=True) & Q(groups__name = 'ITOfficer')).exclude(is_superuser=True).values('id', 'name').annotate(onGoingCount=Case (When (newreport__performer_completion_date__isnull = True, then=(Count('newreport__id'))), default=0)) # .aggregate(totalTask = sum('onGoingCount')) print(performersInfo) performersInfo2 = pd.DataFrame(performersInfo) print(performersInfo2) performersInfo2.columns = performersInfo2.columns.get_level_values(0) aggregateOngoing = performersInfo2.groupby(['id', 'name']).sum() print(aggregateOngoing) the last print results onGoingCount id name 26 Dagim 0 27 Michael M 0 28 Nahom T 2 29 Dawit B 0 30 Kalkidan L 1 31 Kalkidan T 0 32 Melesew 0 33 Michael B 1 {% for key in aggregateOngoing.items %} <p>{{key.1}} {{key.0}}- ({{value.0}})</p> {% endfor %} The format that I want to display in loop is like this 26 Dagim 0 27 Michael M 0 28 Nahom T 2 29 Dawit B 0 30 Kalkidan L 1 31 Kalkidan T 0 32 Melesew 0 33 Michael B 1 -
Can't install mysqlclient
pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) .. done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) .. error ERROR: Command errored out with exit status 1: command: 'c:\users\hp\appdata\local\programs\python\python36\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\HP\\AppD ata\\Local\\Temp\\pip-install-mmb7531p\\mysqlclient_a141c7c0a933439fbe19807e877c7cc2\\setup.py'"'"'; __file__='"'"'C:\\Users\\HP\\AppData\\Local\\Temp\\pip-install -mmb7531p\\mysqlclient_a141c7c0a933439fbe19807e877c7cc2\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.St ringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"' ))' bdist_wheel -d 'C:\Users\HP\AppData\Local\Temp\pip-wheel-44gqcvbi' cwd: C:\Users\HP\AppData\Local\Temp\pip-install-mmb7531p\mysqlclient_a141c7c0a933439fbe19807e877c7cc2\ Complete output (25 lines): c:\users\hp\appdata\local\programs\python\python36\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... … -
Form Django can't update data
here's my code i can't update my data if i used type "file" My form can't be updated, I try print(form.error) but "this field requirement" appears, even though the form is filled out views.py : @login_required def data_karyawan_edit(request, id): karyawan = Karyawan.objects.get(id=id) ar_divisi = Divisi.objects.all() if request.method == 'POST': form = KaryawanForm(request.POST, request.FILES, instance=karyawan) print(form.errors) if form.is_valid(): form.save() messages.success(request, "Berhasil disimpan") return redirect('data_karyawan') else: form = KaryawanForm() return render(request, "data_karyawan/edit.html", {'karyawan': karyawan, 'ar_divisi': ar_divisi}) -
django-tailwind not loading page if django_browser_reload enabled
I use Cookiecutter Django templpate to generate my project using docker. then I want to integrate it using django-tailwind. django-tailwind work properly when django_browser_reload removed from INSTALLED_APPS, urls.py, and the middleware. Post CSS is generated and loaded successfully when django_browser_reload disabled. But when I enabled it, it just stuck and wont load the page. How can I make django_browser_reload work properly? -
How to create a base serializer to custom generate file field urls
I'm using Django's django-private-storage When an api is created using drf, in the case of a general file field, the url starts with http:// in local and https:// in dev and prod. But for privateFileField it starts with http:// everywhere. Therefore, I want to create a BaseSerializer and create a custom url when the field is a privateFileField. And I want the model serializer with privateFileField to inherit from that serializer. What should I do? I could use get_value() function, but I don't want to implement that function in every model serializer with privateFileField. I want to reduce repetition. Also, the settings that change http:// to https:// are already applied. Only privateFileField is a problem. -
Django partial index on date
Django has allowed partial indices for a while now. I’ve seen examples where it’s set on boolean and strings, but what if I want to set it on a date, for example > 01-01-2023? Engine is PostgreSQL. -
why block tag in django framework is working properly?
i'am new to django , i have been trying to replace small contant of the "base.html" with the contant of "contact.html" but nothing happends base.html <!DOCTYPE html> <html> <head> <title>this is base</title> </head> <body> {% block content %} replace me {% endblock %} </body> </html> contact.html {% extends "base.html" %} {% block content %} <h1>this is contact,contact is working congrats</h1> {% endblock %} result setting.py -
Author page in django migrations and questions
I want to make a website for eBooks with a page that has all the books published by one of the authors. The problem is that I have no idea how to do that. I will mention that I am a beginner. I tried this int the model file class Author(models.Model): author = models.TextField() class Product(models.Model): … author=models.ForeignKey(Author,on_delete=models.CASCADE) The result in the terminal was: File "/home/user/petnet/petnet-env/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 264, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'store_product' with primary key '2' has an invalid foreign key: store_product.author_id contains a value 'anonim' that does not have a corresponding value in store_author.id. I think this is caused by the act that I made the author field later and there were already authors fields from before, but then, when I tried to revert back to what I had before doing this, I got some errors regarding migrations. Also the views were: def author_detail(request, slug): author = get_object_or_404(Author, slug=slug) products = author.products.filter(status=Product.ACTIVE) return render(request, 'store/author_detail.html', { 'author':author, 'products':products }) But I am also curious if there is a chance I could use only this for models so I could use the form for adding a product in a much easier way. class Product(models.Model): … -
Django: Problems passing a list and the results of the list treated by a function as two separate variables to the template
I'm trying to make CV website which has a sudoku generator and solver. The generator and solver are two separate functions in the functions.py file imported into the views.py file. My sudokus are stored in a list of 9 lists of 9 ints. from views.py: from functions import * def sudoku(request): grid = make_sudoku() # generates unsolved sudoku list solved = solve(grid) # generates solved list of unsolved list fed in. count = [i for i in range(9)] context = { 'grid': grid, 'solved': solved, 'count': count } return render(request, 'main/sudoku.html', context) if I print grid, I get an unsolved sudoku list. If I print solved, I get a the same list which has been solved. Everything works dandy up until that point, but if I go to sudoku.html and type {{ grid }}, I get a solved sudoku list. As the tree said to the lumberjack, I'm STUMPED! I'm completely baffled as to why this might happen because at no point in sudoku.html do I refer to grid or solved outside of passing them on to sudoku.js which actually makes the puzzle. -
I can't connect to postgresql database in deployment
Hello I just want to deploy my django project in python anywhere .... and when I run the command py manage.py migrate it shows this error message django.db.utils.OperationalError: connection to server at "<Host name>" (<IP address>), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I think that the problem in python anywhere because when I connect to the server in pgadmin using the same info in the settings.py file I don't get any error messages and you have to know that I am using neon.tech for my postgresql database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '<the database>', 'USER':'<User>', 'PASSWORD':'<Password>', 'HOST':'<Host>', 'PORT':5432, } } and I am sure that all information is right because I used it to connect to the server in pgadmin in my local machiene -
can we integrate websockets (ws) in our current project which only uses http.Can websockets and http can work together in one project .DJANGO CHANNELS
I created a social network site using django and my project or site was only using django with http protocols. I only have crud like features in my site but now i discovered about django channels. Django Channels allow django project to not only handle http but can also work with websockets protocol. So can we integrate websockets protocol in the website which only uses http ?. Can http and websockets protocol can work together in one project or one website ?. Can we integrate django channels in the existing django project which only uses http protocol ?. Is any website only have to use one protocol ? Hope you will help me in my journey. 😊 I tried using django channels and django in one project and it was working fine . Both http and websockets protocols was working fine but i want answer from a experience developer bcoz i don't have much knowledge about networking and protocols and i never used websockets before. -
how to do makemigrations/migrate in gnadi(python/postgresql web hebergement)
I am a python developer and new to GANDI (python/PostgreSQL web hosting). There is no document to migrate databases to their server. they have their document to deploy a Project Django but not very clear there are a lot of things missing. After taking a lot of time on the internet, I managed to deploy a Django project in their server. The site works smoothly with an SQLite database. Now I would like to make a Django Project with PostgreSQL. I have an emergency console, but I would like to work locally and then I would like to migrate the DBs to their phpPGadmin server. I just need your help to do makemigrations/migrate to thier PostgreSQL(PhpPGadmin) server. Thanks in advance. -
Different behavior between multiple nested lookups inside .filter and .exclude
What's the difference between having multiple nested lookups inside queryset.filter and queryset.exclude? For example car ratings. User can create ratings of multiple types for any car. class Car(Model): ... class Rating(Model): type = ForeignKey('RatingType') # names like engine, design, handling user = ... # user Let's try to get a list of cars without rating by user "a" and type "design". Approach 1 car_ids = Car.objects.filter( rating__user="A", rating__type__name="design" ).values_list('id',flat=True) Car.objects.exclude(id__in=car_ids) Approach 2 Car.objects.exclude( rating__user="A", rating__type__name="design" ) The Approach 1 works well to me whereas the Approach 2 looks to be excluding more cars. My suspicion is that nested lookup inside exclude does not behave like AND (for the rating), rather it behaves like OR. Is that true? If not, why these two approaches results in different querysets? -
problème sur makemigration en Django [closed]
Comment résoudre le problème de Aucun changement détecté en Django en faisant le makemigration. Comment résoudre le problème de Aucun changement détecté en Django en faisant le makemigration. -
Is good convention to define list_select_related always for all model ForeignKey fields?
I'm just doing some optimizations in my Django app and I wondered if it's a good convention when I always define list_select_related with all model ForeignKey fields in the model Admin. Now I'm not talking about ManyToMany etc where I should use prefetch_related on my own in queryset. -
Django ORM vs raw SQL - security
My django project makes use of lots and lots of database queries, some are complex and some are basic SELECT queries with no conditions or logic involved. So far I have been using the sqlite3 module to manage my database, instead of the django ORM which has worked very well. One problem or drawback I am aware of using raw SQL queries is their security flaws when compared to django's ORM, such as being viable to SQL injection attacks when passing in user input into my raw SQL queries. My question is - Is it absolutely necessary to use django's ORM for queries involving user input or can I use a general function to remove any potentially malicious characters eg (,' -, *, ;) def remove_characters(string:str): characters = ["'", ";", "-", "*"] for char in characters: if char in string: string = string.replace(char, "") return string example of vunrable query in my project username = "logan9997" password = "x' or 'x' = 'x" def check_login(self, username, password): sql = f""" SELECT * FROM App_user WHERE username = '{remove_character(username)}' AND password = '{{remove_character(password)}' """ Without the remove_characters function a hacker could gain access to someone else's account if the inputs were … -
How to log in in existing password account with google auth django?
I have problem with google auth. Steps to reproduce problem: Register password account Try to log in with google auth Get 500 answer Traceback: Internal Server Error: /api/v1/auth/google/ Traceback (most recent call last): File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 54, in dispatch return super().dispatch(*args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/andrew/Documents/pets_backend/project/api_v1/views/social.py", line 77, in post response = super().post(request, *args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 125, in post self.serializer.is_valid(raise_exception=True) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 220, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 422, in run_validation value = self.validate(value) File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/registration/serializers.py", line 151, in validate complete_social_login(request, login) File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 151, in complete_social_login return _complete_social_login(request, sociallogin) File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 172, in _complete_social_login ret = _process_signup(request, sociallogin) File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", … -
Importing a file to a Django project - errors when running manage.py due to location of script
So, I know the source of my error, and I can fix it in a kind of hacky way, but I want to know the sort of best practices way of solving it - especially as my hacky way runs into issues when running stuff via commandline - and throws errors in my IDE. So, I have a django project, the folder tree looks like this (edited out irrelevant parts) ├── manage.py ├── simulator │ ├── angus_testing.py │ ├── events.py │ ├── parser.py │ ├── parser_test.py │ ├── patch.py │ ├── simulator.py ├── VSPOMs │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── VSPOMsApp ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── urls.py └── views.py When I run manage.py that is obviously running in the . directory. views.py is in the VSPOMSapp directory. If I have the following imports in views.py from ..simulator.patch import Patch from ..simulator.simulator import Simulator The IDE doesn't throw an error - and this is correct as it is searching in the parent directory for a file called patch in a folder called simulator that is in the dir above. However, when I run manage.py this causes me to get an error ImportError: attempted … -
Can't add ManyToMany relation in admin
I have following model created in Django: class Content(models.Model): publish_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length = 100, blank = False, default='name') summary = models.CharField(max_length=400, blank=True, default='summary') description = models.TextField(blank = True, max_length=5000, default = LOREM_IPSUM) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) rules = models.TextField(blank = True, default='rule set') parent = models.ManyToManyField(to = 'self', related_name="child", symmetrical = False, blank=True) I added four Content objects through Django admin: Project1 Task1 Task2 Task3 And set parent to Project1 for all TaskX. When I want to display all the content with detailed parent atrribute it turns out to be None. views.py def display_ideas(request): ideas = Content.objects.filter(name="Task3") return render(request, 'display_ideas.html', context = { 'ideas' : ideas }) ** display_ideas.html ** <div class="container bg-success"> {% for idea in ideas %} <div class="container bg-danger"> <h2>Name:</h2> {{ idea.name }} has parent: {{ idea.parent.name }} </div> {% endfor %} </div> The output is: Name: Task3 has parent: None What am I doing wrong? All migrations are done and the site is up and running. -
Python Django Interaction with Third Party Backend via Client Library
I am programming a web frontend and backend with Python Django for a FinTS client (https://python-fints.readthedocs.io/en/latest/). The FinTS client library provides an API to communicate with a third party backend. The communication with the FinTS client has to be done in multiple steps: first connect then the backend asks for a TAN number the TAN number has to be provided then transactions can be fetched Basically the sequence looks like this: Sequence I am struggling with the question how I could realize this in detail with Django. I did some experiences with Django, Django Channels and Websockets, but without real success. I tried so far: A Django view provides a Django form The web client creates a websocket connection to a WebSocketConsumer The WebSocketConsumer provides its Django channel name to the web client The web client posts the form with credentials including the channel name When the form is posted, the view sends a message via a Django Channel to a BackgroundWorker inlcluding the web socket channel name The BackgroundWorker instantiates the FinTS client object and initiates the connection. The BackgroundWorker sends a message to the WebSocketConsumer asking for the TAN The WebSocketConsumer sends a web socket message to the … -
Can't add file apache2/wsgi.24.0.1.sock to tar: archive/tar: sockets not supported
I try to build my Docker image : sudo docker build --ulimit nofile=8192:8192 . And I got the following error : Can't add file /var/lib/docker/overlay2/8a4e2447c4fc77a20c1f075fc5d887520fe22dd6ee559cfd480287e4914a1c5c/diff/run/apache2/wsgi.24.0.1.sock to tar: archive/tar: sockets not supported Some informations on my env : . ├── .dockerignore ├── .env ├── .git ├── .gitignore ├── .gitlab-ci.yml ├── Dockerfile ├── Project ├── README.md ├── docker-entrypoint.sh ├── requirements.txt ├── site-config.conf ├── user └── utils Dockerfile : FROM debian:bullseye-slim RUN apt-get update RUN apt-get install -y apt-utils dialog RUN apt-get install -y nano curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 python3-venv RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN pip install --upgrade pip ENV PYTHONUNBUFFERED 1 RUN mkdir /code/ WORKDIR /code/ COPY requirements.txt /code RUN python -m venv .env RUN pip install -r requirements.txt COPY . /code/ ENV F_FROM_DOCKER=True RUN chmod 775 docker-entrypoint.sh ADD ./site-config.conf /etc/apache2/sites-available/mpn.conf RUN a2dissite 000-default RUN a2ensite mpn RUN service apache2 start EXPOSE 80 3500 CMD ["./docker-entrypoint.sh"] It's a Django project using apache. I already tried solutions here but nothing worked for me. When I run my docker image in interactive mode I haven't any interactivity (I am not sure this is linked with the build error) : ~/workspace/docker_mpn$ sudo docker run --interactive … -
How can I send swift json to django server?
Swift code: static func send(url: URL, data: Data) async { var request = URLRequest(url: url) request.httpMethod = "POST" let json: [String: Any] = [ "order_details": ["meal_id":"6", "quantity":"1"], "restaurant_id": "1", "access_token": "FUJMNpU77OyuLiohOl5wzRQkGpHleV", "address": "13" ] let jsonData = try? JSONSerialization.data(withJSONObject: json) request.httpBody = jsonData print(String(data: jsonData ?? Data(), encoding: .utf8)) do { let (_, response) = try await URLSession.shared.data(for: request) guard let statusCode = (response as? HTTPURLResponse)?.statusCode, 200..<300 ~= statusCode else { throw URLError(.badURL) } } catch { print(error) } } Print: Optional("{\"address\":\"13\",\"order_details\":{\"quantity\":\"1\",\"meal_id\":\"6\"},\"restaurant_id\":\"1\",\"access_token\":\"FUJMNpU77OyuLiohOl5wzRQkGpHleV\"}") JSON looks normal. BUT in my django server I get this: if request.method == "POST": print(request.POST) Print: <QueryDict: {'{"address":"13","order_details":{"quantity":"1","meal_id":"6"},"restaurant_id":"1","access_token":"FUJMNpU77OyuLiohOl5wzRQkGpHleV"}': ['']}> i.e. my request becomes a key I tried to compose the request in different ways, I used JSONEncoder and JSONSerializer but nothing happened