Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display one question per page in Django
Suppose I have 10 rows in the table Question and I can call questions= Question.objects.all() It displays all the questions on the page like this but I am trying to display one after one on the page. how can I display it? Any help is appreciated -
Django form - How to save data or get data without having to save it to database?
I've created a form with some fields for users to enter data, and a button to submit them and run some functions, then display the results on the same page (without having to store it to the database). Now I would like to add a button (view/download as PDF) to have the page generated as a PDF file, so that the user can save the results. But I'm having trouble retrieving the entered data, even they are still displaying on the page. They don't seem to be stored in the variables (or I don't know where to look). I've read that if using modelForm I can call the .save function and save data to the database. But for this app I don't really need a database (it's more like an one-off calculations). So I would like to know if there's any way to: Get the entered data directly while they are still on display (after submitting the form). Generate a PDF directly from what's on the page (like the print to PDF file function that most browsers have, but with some customization such as without the headings and navigation bars). Is there a way to do this? I've been searching … -
ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers'
I have been trying to understand which part of the app has a circular import but I just can't get the logical flow in this. If I may show you the directory tree of this app called, "api": When I run a unit test, I get this error: E ====================================================================== ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * File "/Users/nick/work/shiftwork_backend/api/views/base.py", line 10, in <module> from api.serializers import ConfigSerializer ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) So I looked at the views/base.py and saw this: import requests from django.http import JsonResponse from django.shortcuts import get_object_or_404 from rest_framework.permissions import AllowAny from api.constants import Constants from api.models import Config, UserCompany, UserPattern from api.serializers import ConfigSerializer and views/init.py looks like below: from .base import * from .alarm import * from .company import * from .config import * from .holiday … -
Model hierarchy in Django
Sorry for the long text Models are given: User Hierarchy There are users, they can invite each other. The invitees, in turn, can accept the invite or reject it. Suppose that Mark invited Masha, Katya and Dima. Masha accepted Mark's invitation, and even invited Kolya herself. On one tab, you need to display the hierarchy. Continuing the example, Mark should have: 1st level: Masha, Katya, Dima 2nd level: Kolya and other guys 1st level for Mark - those whom he invited. 2nd level - those who were invited by people invited by Mark. And so on. Tell me how to implement it | what to familiarize yourself with to get closer to the result -
Django: saving models using parallel processing
I have a 35000 list of items which i have to update. I am planning to use bulk update. In bulk update we have the batch_size=option. I am planning to use a batch size of 20. Now what i found is that this runs the 20 sets of update in sequence. one after another Is it good idea to parallelize the update sets. If yes, how can i do it using multiprocess I came to know about multiporcessing a bit: import multiprocessing import django django.setup() # Must call setup def db_worker(item): from app.models import Model1 Model1.bulk_update(item).save() if __name__ == '__main__': list_update_values = 3500 items list_chunks = [] chunk_size = 20 for i in range(0,35000,chunk_size) list_chunks.append(list_update_values[i:i+chunk_size]) p = [multiprocessing.Process(target=db_worker,args=(item)) for item in list_chunks] p.start() p.wait() Will this going to help much -
How to solove, django.db.utils.IntegrityError: NOT NULL constraint failed: new__todolist_postcomment.comment_user_id
(projectenv) E:\demo practice\django-todolist_new\projectenv\src>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, todolist, userprofile Running migrations: Applying todolist.0012_auto_20201112_2021...Traceback (most recent call last): File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__todolist_postcomment.comment_user_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\demo practice\django-todolist_new\projectenv\src\manage.py", line 22, in main() File "E:\demo practice\django-todolist_new\projectenv\src\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\backends\sqlite3\schema.py", … -
directive is not allowed here in /etc/nginx/default.d/app.conf:1 NGINX Config EC2
I'm trying to configure my app to run on ec2 with some difficulty. It's a multi container app built with docker-compose consisting of django, drf, channels, redis gunicorn, celery and nuxt for frontend. I've an instance running and can SSH to the instance and install the relevant packages, docker nginx docker-compose etc. What I can't do is edit my app.conf nginx file to use the public ip 33.455.234.23 (example ip) To route the backend, rest and frontend. I've created and app.conf nginx file which works fine local but when I try edit the nginx files after install to configure my app to the public ip's I run into errors. The error I have when writing my config is 2020/11/13 01:59:17 [emerg] 13935#0: "http" directive is not allowed here in /etc/nginx/default.d/app.conf:3 nginx: configuration file /etc/nginx/nginx.conf test failed This is my nginx config worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; client_max_body_size 100m; upstream asgiserver { server asgiserver:8000; } upstream nuxt { ip_hash; server nuxt:3000; } server { listen 80 default_server; server_name localhost; location ~ /(api|admin|static)/ { proxy_pass http://asgiserver; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location /ws/ { proxy_pass http://asgiserver; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; … -
How to store video transcripts in a database
I have some video transcripts that I would like to be able to search and filter on. They are stored in SRT files currently. I have around 200 files/videos and they are for videos that are 4 hours long and each file is around 200-400KB depending on the length. I'm using Django for my backend and a Postgres database. Here's a snippet of an example: 1 00:00:00.503 --> 00:00:02.782 SPEAKER 1: text text text 2 00:00:02.782 --> 00:00:04.090 SPEAKER 2: more text So I was thinking I might store it so each of the pre-made blocks as a single entry in my db. So I would have a table like: speaker | text | start | end I'd say per file there is 6k entries so that's around 1.2 million records and it will keep growing. I'm not sure if that's going to be fast for a text search. How should I store my transcripts so I can search by text and filter on speaker quickly? -
Passing List of Dictionaries to Django View Using Ajax
I am new to Ajax and Django, so I might be missing something basic here. I am trying to pass a list of dictionaries to a Django view. Example: data = [ {'item':'itemname','qty':'qty','price','price'},{'item':'itemname','qty':'qty','price','price}, etc. ] I have set up my Ajax call to fire when a button is pressed. My cart.js $(document).ready(function(){ var userCart = grabCart(); userCart = JSON.stringify(userCart); $("#Checkout").click(function(){ $.ajax({ URL: some URL headers: csrf_token, //Im passing the token using Django type: 'POST', data: {'userCart':userCart}), success:function(){//stuff} complete:function(){//stuff, but its routing to confirmation.html} error:function(){//stuff} }); }); My Django view def confirmation(request): data = json.loads(request.POST.get('userCart')) # <-- this line is throwing the error print(type((data)) # this prints out list print(data) #this prints out the list of the dictionaries return render(request,'confirmation.html') I keep getting an Error 500, Type Error. The JSON object must be str, bytes, or byte array, not NoneType This is confusing. The results are there but Django is throwing an error and won't render the confirmation page. -
Loading Comments to page without Refreshing
I am new to JS and I am trying to learn steps to add comments to posts without refreshing the page. So, far I was successful in using JS in loading Like button without refreshing by following tutorials but I need some help with the comments. Here is the comments view.py class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the template: <legend class="border-bottom mb-0"></legend> {{comments.count}} Comment{{comments|pluralize}} <div class="container-fluid mt-2"> <div class="form-group row"> <form action="{% url 'blog:post-comment' post.slug %}" method="post" class="comment-form" action="."> {% csrf_token %} {{ comment_form.as_p }} <input type="hidden" name="post_id" value='{{post.id}}' class="btn btn-outline-success"> <button type="submit" … -
Django ModuleNotFoundError: No module named 'Web_App.index'
I'm trying to use a function inside index.py which is in the same directory as views.py in Django but it won't work. These are my files.1 Dir -
How can I do to do some specific filter using Django?
I am using Django and I woud like to do some specific filter. Let's take this example : MyTable.objects.filter(number=3) This query will return me all the entries which has the following criteria number=3 but in what I would want is something like this : MyTable.objects.filter(number='all') And in this case I will get all the entries. I know I can do something like that : MyTable.objects.all() But I would like to use only filter to do that. Could you help me please ? Thank you a lot ! -
djanjo get values from related models
I have 2 models- class POWStage(Content): time_slot = models.OneToOneField( TaskTime, on_delete=models.CASCADE, help_text='Link to time slot describing the stage timescale', verbose_name='Time slot link', null=True, blank=True class TaskTime(Content): schedule_finish = models.DateTimeField( help_text='Scheduled finish date', verbose_name='Scheduled finish', blank=True, null=True, I would like to get the latest end date for a list of POwStages.... e.g. If I have 8 POWStages will have 8 corresponding schedule finish dates. I have tried the following with no success: pow_stage_list = POWStage.objects.get_stage_by_pow(pow_detail) task_time_list = TaskTime.objects.get_task_time_by_id(getattr(pow_stage_list,'time_slot')) and also: time_list = [] time_slot=[] time_finish[] for time_slot in pow_stage_list: time_list.append(time_slot) for entry in time_list: time_entry.append(entry.id) for finish_date in time_entry: time_finish.append(TaskTime.objects.get_task_time_by_id(finish_date)) to try and at least get the values of the finish dates in order to process them further (neither of which are working) Im thinking of getting the POWStages - using a filter - no problems 2)FOr each of the POWStages - loop through them to get the id of TaskTime I can do this ok -ish ( I manage to get the id which is returned as UUID() object. which I cannot then pass to get the TaskTime For each of the TaskTime get the value of schedule finish Iterate through the values to find the latest finish date. Im … -
DataError: value too long for type character varying(1024) TextField
Hello I am having this problem with my Django model. Field is HTMLField from TinyMCE which inherts from Django's TextField so it should be unlimited. Is it possible that db somehow truncated this length? I am inserting string which is about 4k characters long and I am using psql (PostgreSQL) 12.3 as my database. Thanks Model: class Category(Model): page_content_html=HTMLField(_("page content"), blank=True, null=False, default=''), ) HTMLField: class HTMLField(models.TextField): """ A text area model field for HTML content. It uses the TinyMCE 4 widget in forms. Example:: from django.db.models import Model from tinymce import HTMLField class Foo(Model): html_content = HTMLField('HTML content') """ def __init__(self, *args, **kwargs): self.tinymce_profile = kwargs.pop('profile', None) super(HTMLField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = { 'widget': TinyMCE(profile=self.tinymce_profile) } defaults.update(kwargs) # As an ugly hack, we override the admin widget if defaults['widget'] == AdminTextareaWidget: defaults['widget'] = AdminTinyMCE(profile=self.tinymce_profile) return super(HTMLField, self).formfield(**defaults) psql: Sloupec | Typ | Collation | Nullable | Implicitně -------------------+------------------------+-----------+----------+---------------------------------------------------------- id | integer | | not null | nextval('product_category_translation_id_seq'::regclass) language_code | character varying(15) | | not null | name | character varying(256) | | not null | long_name | character varying(512) | | not null | page_content_html | text | | not null | master_id | integer | … -
Can we loop through an array send from context data function to django template?
I am asking this question second time because last time I didn't get proper answer of this question. Well I think its hard to explain that what I am actually trying to do but let me try to explain briefly so you guys can understand better. Here in a picture you can see there is a list of followers and we can also see the list followers and following of each follower. I want run this kind to query. I am trying with the following code views.py def get_context_data(self, *args, **kwargs): context = super(FollowerView,self).get_context_data(*args, **kwargs) user = context['user'] user_com = User.objects.get(username=user) myfollowers = user_com.is_following.all() followers_Array =[] followerings_Array =[] for target_list in myfollowers: user_obj = User.objects.get(username=target_list) followers_obj = user_obj.is_following.all() print(followers_obj,'name o ki line') followerings_Array.append(followerings_Array) print(followers_obj,user_obj) followerings_obj = user_obj.userprofile.follower.all() followerings_Array.append(followerings_obj) print(followerings_obj,user_obj) print(followerings_Array,'arry one one one ') context['myfollowers_data']= followers_Array context['myfollowerings_data']= followerings_Array return context Well I am using two arrays in the code but i don't want to use them,right now i am not getting right output by returning arrays in context. If arrays are unnecessary than tell me the other way and tell me how can i show data the way i show you in the picture, I am sharing followers template here … -
Nginx Redirect 80 port insted of 443
I moved my server digitalocean to google cloud. I am using same config on my django website. I am using gunicorn and nginx. Website works perfect 80 port and I am trying enamble ssl and getting 301 Moved Permanently error. Problem is when I logged 443 port it redirects 80 port again and I have redirect command to redirect https connection. SO I am trying to connect https://example.com it redirect me with 301 code to http://example.com and nginx redirect it again https://example.com so It is a infinity loop. Here my nginx conf: It is workig with just 80 port server { server_name www.example.com; return 301 $scheme://example.com$request_uri; } server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; } server{ listen 443 ssl http2; server_name example.com; root /home/www/example/example; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/letsencrypt/live/example.com/fullchain.pem; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s; ssl_buffer_size 4k; add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"; add_header X-Frame-Options sameorigin; add_header X-Content-Type-Options nosniff; add_header X-Xss-Protection "1; mode=block"; if ($host = www.example.com ) { return 301 $scheme://example.com$request_uri; } location /static/ { } location /media/ { } location / { … -
No Django Documentation On Subdomains
Django Documentation is silent on subdomains. Is that because they're not advised or all together unnecessary? -
Django + AJAX, need to click buttom twice to works
trying to develop a single page to perform the CRUD I chose to use nav-tabs, I am using AJAX to navigate between them and load the content, the part of creating an object is happening correctly, however, when I click in the edit button i need to click twice for him to execute the changeTAB () function that has the logic of switching to the CREATE / UPDATE tab. I do not imagine how to solve this problem. index.html: {%load static%} <!DOCTYPE html> <html lang="pt-br"> <head> <title>CRUD EXAMPLE</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Ordens de Serviço</h2> <ul class="nav nav-tabs"> <li class="active"><a class="js-list" data-toggle="tab" href="#list" > Ordens de Serviço</a></li> <li><a data-toggle="tab" class="js-create-update" data-url="{% url 'example:create' %}" id="tab-create-update" href="#create-update" > Create/Update</a></li> <li><a data-toggle="tab" href="#detail">Ver</a></li> </ul> <div class="tab-content"> <div id="list" class="tab-pane fade in active"> <h3>Equipamentos</h3> {% include 'example/list.html' %} </div> <div id="create-update" class="tab-pane fade"> <h3>Criar/Editar</h3> {% include 'example/create.html' %} </div> <div id="detail" class="tab-pane fade"> <h3>Detalhes</h3> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p> </div> </div> </div> <script src="{% static 'js/example.js' %}"> </script> <script src="{% static 'js/bootstrap.js' %}"> </script> </body> </html> list.html: <table class="table" … -
Python 3.8: re.error: bad escape \s at position 3
I use django RegexValidator in a model field: city = models.CharField(max_length=30, blank=False, null=False, validators=[RegexValidator(r"^((\p{L}|\s)+)$")]) But I keep getting errors: bad escape \s at position 3 bad escape \p at position 3 I can't understand what's wrong. I've been reading online but nothing seems to solve this problem. I use Python 3.8 and Django 3.1.3. -
django-activity-stream with aggregation
I'm using django-activity-stream to create a feed of goals. A simplified version of Goal object is as follows: class Goal(models.Model): user = models.ForeignKey(User, related_name="goals", on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, related_name="goals_cheered") title = models.CharField(_("title"), max_length=80) There are 2 actions in place: the goal should appear in the feed once it's created and once it has been completed. Then users can like the goal, and here's where I'm stuck: adding the 'likes' count on the feed. This was the (failed) attempt that made the most sense to me so far: from django.db.models import Prefetch goal_qs = Goal.objects.annotate(likes=Count("liked_by")) prefetch = [Prefetch("action_object", queryset=goal_qs)] # in a `group` feed: qs = group.target_actions.all().prefetch_related("actor__profile").prefetch_related(*prefetch) This gives me a ValueError: "Custom queryset can't be used for this lookup." Maybe it's because django-activity-stream uses GFKs? How can I get a count of likes? Can I limit the content_type somehow? -
Django template not rendering time correctly
I have datetime object that I need to show in two different timezones. In the backend, I use astimezone() to change the original datetime tzinfo, this is the code: print("event.date_start: %s" % event.date_start) print("event.date_start.hour: %s" % event.date_start.hour) print("event.date_start.tzinfo: %s" % event.date_start.tzinfo) user_timezone = pytz.timezone("America/Guayaquil") print("user_timezone: %s" % user_timezone) event_user_timezone = event.date_start.astimezone(user_timezone) print("event_user_timezone: %s" % event_user_timezone) print("event_user_timezone.hour: %s" % event_user_timezone.hour) This code prints the datetimes correctly, event.date_start is in UTC time, 18hrs - event_user_timezone is in "America/Guayaquil", 13hrs. event.date_start: 2020-11-17 18:00:00+00:00 event.date_start.hour: 18 event.date_start.tzinfo: UTC user_timezone: America/Guayaquil event_user_timezone: 2020-11-17 13:00:00-05:00 event_user_timezone.hour: 13 However, when rendering the html, with this code: <p class="text-muted font-weight-bold" > {{ event.date_start|date:"h:i A" }} ({{ owner_profile.timezone }}) </p> <p class="text-muted font-weight-bold"> {{ event_user_timezone|date:"h:i A" }} {{ logged_user_profile.timezone }} </p> both times are displayed as 6pm. Why? -
How to dynamically select django model fields in views.py
I am using the DRF and I am trying to dynamically select fields from a django model object so that I can compare them to incoming data. I know how to do this manually def put(self, request): businessPage = BusinessPage.objects.get(id=request.data['id']) if businessPage.name != request.data['name']: businessPage.name = request.data['name'] if businessPage.address != request.data['address']: businessPage.address = request.data['address'] businessPage.save() res = { 'status': 'Success' } return Response(res) While this works it feels very messy and repetitive so I started looking for a way to dynamically check if the object field matched the incoming data. def put(self, request): businessPage = BusinessPage.objects.get(id=request.data['id']) for obj in request.data: if businessPage[obj] != request.data[obj]: businessPage[obj] = request.data[obj] businessPage.save() res = { 'status': 'Success' } return Response(res) I haven't been able to figure out the correct syntax to get the correct field from businessPage. Is this possible? Is there a better way to accomplish this task? Any help here would be much appriciated! -
Creating seperate URL endpoints for text files for a SaaS application
I have an architecture question so I don't need a specific answer but some guidance around a general approach. I am running a single Django App which has multiple GraphQL endpoints (multiple schemas on a single database). As an example I have the following endpoints all running from the same database: - example1.com/graphql - example2.com/graphql - example3.com/graphql I have a requirement to expose a text file which will be publicly accessible. e.g. - example1.com/textfile.txt - example2.com/textfile.txt - example3.com/textfile.txt Each text file will have its own data in it related to the customer URL. The problem I have is that at moment all of the URL endpoints write data to the same text file (since it is not stored on the schema). What I need is for them to write this data to distinct and seperate text files. What is the best way to resolve this problem - is it best to write this data straight to something like AWS S3 storage and create folders for each URL. In the case of S3 storage, is it possible to run append and delete operations on the text file directly. Any help is really appreciated. -
Individual use of password field names in Django All-Auth SignUpForm
I am trying to use Django All-Auth forms in a predefined Bootstrap template so I want my fields to match the styling. Therefore I want to use each field individually in the template such as; I have done this successfully for the LoginForm by adding custom attributes to the fields in my forms.py. class YourLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(YourLoginForm, self).__init__(*args, **kwargs) self.fields['login'].widget = forms.TextInput(attrs={'type': 'email', 'class': 'form-control', 'name': 'loginUsername', 'id': 'loginUsername', 'placeholder': 'name@address.com', 'autocomplete': 'off', 'required data-msg': 'Please enter your email'}) self.fields['password'].widget = forms.PasswordInput(attrs={'type': 'password', 'class': 'form-control', 'name': 'loginPassword', 'id': 'loginPassword', 'placeholder': 'Password', 'required data-msg': 'Please enter your password'}) And then referring to them with the following template tags. {{form.login}} {{form.password}} However, when I try and repeat this for the SignUpForm, I keep getting a key error which returns password1. The code I am using for this is outlined below. class MyCustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['email'].widget = forms.TextInput(attrs={'type': 'email', 'class': 'textinput textInput form-control', 'name': 'email', 'id': 'id_email', 'placeholder': 'name@address.com', 'autocomplete': 'email', 'required data-msg': 'Please enter your email'}) self.fields['password1'].widget = forms.PasswordInput(attrs={'type': 'password', 'class': 'textinput textInput form-control', 'name': 'password1', 'id': 'id_password1', 'placeholder': 'Password', 'autocomplete': 'new-password', 'required data-msg': 'Please enter your password'}) self.fields['password2'].widget = forms.PasswordInput(attrs={'type': 'password', 'class': 'textinput … -
Use Django Channels without views
We want to use Django Channels to use Keras with Tensorflow as model. We've tried Flask but it's not usable for production. Then we tried Javas DeepLearning4J but also got to many problems. We want to solve it with Python. The problem is that Django is fullstack and we just need to use the websockets and execute our python code and send the results back. There is literally no example on Google how to do this. We do this because we got an Angular frontend, Spring Boot backend and another Spring Boot Application as connector between all services. We don't need the most functionalities of Django. It's very hard to find out what do. There is no @socket.route or something like this I think. Websocket using Django Channels this question was maybe a bit helpful but 3 years old and probably outdated. What is the way to achieve what we need?