Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issues with looping through an object in django channels
Am Trying to loop through an a model object in django, I think this the error is coming from consumer.py file this file in particular, I keep getting this error for message in messages: TypeError: 'Messages' object is not iterable and i think the error comes from this code in particular def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result My models.py class Messages(models.Model): sender = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) msg = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.sender.username def last_30_messages(self): return Messages.objects.order_by('-timestamp').all()[:20] My consumer.py from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messages User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Messages.last_30_messages() content = { 'messages': self.messages_to_json(messages) } self.send_chat_message(content) def new_messages(self, data): sender = data['from'] author_user = User.objects.filter(username=sender)[0] message = Messages.objects.create(sender=author_user, msg=data['message']) content = { 'command': 'new_messages', 'message': self.messages_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'msg': message.msg, 'timestamp': str(message.timestamp) } command = { 'fetch_messages': fetch_messages, 'new_messages': new_messages } def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_link"] self.room_group_name = "chat_%s" % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( … -
How do I add custom user model fields to the Wagtail user settings page?
I am building a wagtail site. I've followed the instructions found in the docs and my additional fields show up in the edit and create user forms, found at [site url]/admin/users/[user id]. However, I want them to also show up in the account settings page accessed from the bottom left. This page seems to describe what I want to do, but I don't understand the instructions it gives. I have an app named user, and my settings point the AUTH_USER_MODEL to the model User within it. My models.py in this app is as follows from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): id = models.AutoField(primary_key=True) bio = models.CharField(blank=True, null=True, max_length=2048) nickname = models.CharField(blank=True, null=True, max_length=64) def __str__(self): """String representation of this user""" return self.get_full_name() and my forms.py is from django import forms from django.utils.translation import gettext_lazy as _ from wagtail.users.forms import UserEditForm, UserCreationForm class CustomUserEditForm(UserEditForm): nickname = forms.CharField(required=False, label=_("Nickname")) bio = forms.CharField(required=False, label=_("Bio")) class CustomUserCreationForm(UserCreationForm): nickname = forms.CharField(required=False, label=_("Nickname")) bio = forms.CharField(required=False, label=_("Bio")) From the docs it sounds like I would want to add something like this to that same forms.py: class CustomSettingsForm(forms.ModelForm): nickname = forms.CharField(required=False, label=_("Nickname")) bio = forms.CharField(required=False, label=_("Bio")) class Meta: model = django.contrib.auth.get_user_model() fields = … -
Add column Heroku database
Goodnight. I have a project done in Python and Django and today I added one more Model Table and added a column manually and it worked in the development environment. But when deploying to Heroku , Heroku cannot find this manually created column and returns this error "column does not exist" . How do I manually add a column to the Heroku database? -
Django Error: Reverse for 'delete_ingredient' not found. 'delete_ingredient' is not a valid view function or pattern name
I'd appreciate whatever help you can give to get me past this block. Thanks! The code breaks when I modify the code that used to work to add Delete functionality. When I run the code without the modified urls.py I get the error. The error is: > NoReverseMatch at /ingredients/ Reverse for 'delete_ingredient' not found. 'delete' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ingredients/ Django Version: 4.1.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'delete_ingredient' not found. 'delete' is not a valid view function or pattern name. Exception Location: C:\Users\Dropbox\Python Projects\Django Projects\djangodelights\djangodelights_env\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: inventory.views.IngredientsView Python Executable: C:\Users\Dropbox\Python Projects\Django Projects\djangodelights\djangodelights_env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Python Projects\\Django ' 'Projects\\bwa-django-final-project-main\\bwa-django-final-project', 'C:\\Users\\Python Projects\\Django ' 'Projects\\djangodelights\\djangodelights_env\\Scripts\\python39.zip', 'd:\\users\\miniconda3\\DLLs', 'd:\\users\\miniconda3\\lib', 'd:\\users\\miniconda3', 'C:\\Users\\Python Projects\\Django ' 'Projects\\djangodelights\\djangodelights_env', 'C:\\Users\\Python Projects\\Django ' 'Projects\\djangodelights\\djangodelights_env\\lib\\site-packages'] Server time: Wed, 19 Oct 2022 19:44:34 +0000 Error during template rendering In template C:\Users\Dropbox\Python Projects\Django Projects\bwa-django-final-project-main\bwa-django-final-project\inventory\templates\inventory\ingredients_list.html, error at line 30 Reverse for 'delete_ingredient' not found. 'delete' is not a valid view function or pattern name. 20 </thead> 21 <tbody> 22 {% for ingredient in object_list %} 23 <tr> 24 <td> 25 <a href="{% url "update_ingredient" ingredient.id %}">{{ ingredient.name }}</a> 26 </td> 27 <td>{{ ingredient.quantity … -
AppConfig.__init__() missing 1 required positional argument: 'app_module'
Just running my first app but facing this issue. **AppConfig.__init__() missing 1 required positional argument: 'app_module'** Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.2 Exception Type: TypeError Exception Value: AppConfig.__init__() missing 1 required positional argument: 'app_module' Exception Location: \studybud\env\lib\site-packages\django\template\context.py, line 254, in bind_template Raised during: base.views.home views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html') def room(request): return render(request, 'room.html') Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'base.apps.BaseConfig' ], }, }, ] urls.py from django.urls import path from . import views urlpatterns = [ path ('',views.home, name="home"), path ('room/',views.room, name="room"), ] -
Django mail attachments blank except for 1st email sent, when looping through recipients
I have a newsletter being sent out using Django forms, with multiple files that can be attached. I'm looping through the list of recipients (if they are verified, and agreed to receive the newsletter, etc.) It all works fine, emails are received to these users, including 1 or more attached files. The problem is only the first user gets file\s with content, others get the file/s, but they are empty/blank (Zero bytes). Is it linked to some temp files or the need to cache these files first? so they're available for the loop to handle? (note: the file name, number of files, etc. received to all recipients is all correct - they are just empty, except the first email) How can I resolve that? Thanks forms.py class NewsletterForm(forms.Form): message = forms.CharField(widget = forms.Textarea, max_length = 8000) attach = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) views.py def newsletter(request): users = User.objects.all() receipient_list = [] for user in users: if user.profile.newsletter_agree == True and user.profile.verified_member == True: receipient_list.append(user.email) if request.method == 'POST': form = NewsletterForm(request.POST, request.FILES) if form.is_valid(): mail_subject = 'Some newsletter subject' message = form.cleaned_data['message'], files = request.FILES.getlist('attach') for contact_name in receipient_list: try: email = EmailMessage(mail_subject, message, 'email@email.com', to=[contact_name]) email.encoding = 'utf-8' for f … -
502 gateway on reverse proxy after adding python module pandas
I'm configured with a reverse proxy using nginx to 2 backend servers with different applications that are both python / django running on apache. They direct users to the correct application and everything was working fine until I installed a new module in python. Specifically the pandas module. Now, when loading the application site with the pandas module loaded, it gives me a 502. If I comment out the "import pandas" line from views, it loads fine. No idea what could be causing this. Anyone know? -
Docker on Virtual Box
I installed Docker on Virtual Box because my computer is 32-bit and Docker only ran on 64-bit systems. Now, how can I use Docker on my editor and windows terminal? -
django-main-thread error when running manage.py runserver
I've made some changes to my code while trying to deploy my django app on digital ocean, and now when I try to test my code in my local server, I get this error: (my_chaburah) ~/Desktop/Code/my_chaburah (main) $ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): Library not loaded: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' Referenced from: '/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so' Reason: tried: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file), '/opt/homebrew/Cellar/postgresql@14/14.5_5/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/apps/config.py", line 304, in … -
Traefik, Django, Angular, Docker - Mixed Content
I am trying to set up a Traefik to serve my Django API over HTTPS, but not to expose it to the outside network/world. My docker-compose: --- version: "3.6" services: backend_prod: image: $BACKEND_IMAGE restart: always environment: - DJANGO_SECRET_KEY=$DJANGO_SECRET_KEY - DATABASE_ENGINE=$DATABASE_ENGINE - DATABASE_NAME=$DATABASE_NAME - DATABASE_USER=$DATABASE_USER - DATABASE_PASSWORD=$DATABASE_PASSWORD - DATABASE_HOST=$DATABASE_HOST - DATABASE_PORT=$DATABASE_PORT - PRODUCTION=TRUE security_opt: - no-new-privileges:true container_name: backend_prod networks: - traefik_default calendar_frontend_prod: image: $FRONTEND_IMAGE restart: always security_opt: - no-new-privileges:true container_name: frontend_prod environment: - PRODUCTION=TRUE networks: - traefik_default labels: - "traefik.enable=true" - "traefik.http.routers.frontend.entrypoints=webs" - "traefik.http.routers.frontend.rule=Host(`mywebsite.org`)" - "traefik.http.routers.frontend.tls.certresolver=letsencrypt" - "traefik.http.services.frontend.loadbalancer.server.port=4200" - "traefik.http.services.frontend.loadbalancer.server.scheme=http" networks: traefik_default: external: true Inside my frontend files, I got it set up like it: export const environment = { production: true, apiUrl: 'http://backend_prod' }; After that when I got to mywebsite.org and look at networking I am seeing: polyfills.js:1 Mixed Content: The page at 'https://mywebsite.org/auth/login' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://backend_prod/api/users/login'. This request has been blocked; the content must be served over HTTPS. I was trying to add to backend_prod service below lines: - "traefik.enable=true" - "traefik.http.routers.backend_prod.entrypoints=webs" - "traefik.http.routers.backend_prod.rule=Host(`be.localhost`)" - "traefik.http.services.backend_prod.loadbalancer.server.port=80" - "traefik.http.services.backend_prod.loadbalancer.server.scheme=http" but then I was getting from frontend an error: https//be.localhost Connection Refused. How could I solve this problem? -
Django - Set current date as initial/default in a DateField form with SelectDateWidget
I have a model: class Planning (models.Model): #other fields# month = models.DateField(default=date.today) class Meta: verbose_name_plural = 'Planning' And I have this model form: class PlanningForm(forms.ModelForm): #other fields# month = forms.DateField( label='Mês/Ano', required=True, widget=forms.SelectDateWidget( attrs={'type': 'date', 'value': date.today},), error_messages={'required': '', }, ) class Meta: model = Planning fields = '__all__' I'm using SelectDateWidget to show only month/year (I hid the day selector using CSS), like this: The form is working as intended, but the issue is that I can't set the field to show the current date. When the form is rendered, it always shows the first date of the year. In the above code, I tried to show the date using the value attribute from HTML. This works perfectly when I use widget=forms.DateInput but I imagine that the widget is changing the input completely so it doesn't work. I also tried to add an initial value the same way I did for the model using the line initial=date.today, but for what i can get, this only works for unbound forms and since my view runs a if form.is_valid():, that is not the case. And I did try to set a range for the months, along the lines of this question, … -
USER_ERROR Master in a Duplicate Resolution Operation
I'm working with Customer records in a User Event beforeLoad script. Since record.setValue doesn't work in beforeLoad, I'm using record.submitFields to submit 3 field values. This works most of the time, however rarely there is a USER_ERROR: {"type": "error.SuiteScriptError", "name":"USER_ERROR", "message": "This entity was marked as a master in a duplicate resolution operation.<br><br>This operation is in progress, and the entity is temporarily unavailable for editing."} In the error it points to the line where my record.submitFields is located. From my research into the issue, I think there is somehow a separate process also trying to submitFields and creating a second record to be saved. But I've been through the scripted records and can't seem to find any scripts that could be causing that. Does anyone have thoughts on what could be happening and how it's typically fixed? -
Key Error: 'Secret_Key' cant run server in django
Hello i just downloaded an open source Django CRM. Im using VSCode. Installed all the requirements in the dir and inside the venv. When I try to run the server there is a KeyError. These are the final lines that the error comes with: File "C:\Users\stani\OneDrive\Desktop\Ladyfit Site\Django-CRM-master\crm\settings.py", line 12, in SECRET_KEY = os.environ["SECRET_KEY"] File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\os.py", line 679, in getitem raise KeyError(key) from None KeyError: 'SECRET_KEY' From what I can see the Secret_key is in the env file. In settings.py the key is called with SECRET_KEY = os.environ["SECRET_KEY"]. I dont seem to see the problem and I read a ton of fixes today that dont fix it :). Please help. -
Django translation flags
I am trying to show flags using django-translation-flags in my app but this is showing me both languages' flags. How to configure this app so it shows only active language. {% load i18n flags %} <div class="translation"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <ul> {% for lan in languages %} {% if lan.code != LANGUAGE_CODE %} <li class='cur-lan' ><a href="/{{lan.code}}{{request.path|slice:'3:'}}">{{lan.name_local}} </a></li> {% languages %} {% endif %} {% endfor %} </ul> </div> -
How can i count list of value from another model in Django?
I have two models and one of them contain a list of values that I want to count in another model. query1= list(Model1.objects.filter(CUSTOMER=customer.id).values_list("NAME",flat=True)) print(subquery) # [{'test1','test2,'test3','test4'}] response of query query2=list(Model2.objects.values('CUSTOMER_NAME').annotate(Count(subquery))) Is it possible to create all of that in one query set ? To keep the server running smoothly NB:If one of value does not exist the second model the query should return 0 for the count of this value Example of the return that i want to receive : [{'name':'test1','count':7}, {'name':'test2','count':4}, {'name':'test3','count':0}, {'name':'test4','count':0}, {'name':'test5','count':2}, {'name':'test5','count':4}] -
Django from Submit button doesn't do anything
I'm new to Django, and I'm trying to submit a form to process the data in a view function, but I can't find why when I press the Send button it doesn't do anything. i read many other questions but were syntax related problems, which I believe is not my case. Here's my form. It is in the new.html template: <from action="{% url 'notes:create' %}" method="post"> {% csrf_token %} <input type='text' name='note_name' id='note_name' placeholder='Title...'> <input type='date' name='note_date' id='note_date'> <input type="submit" value="Send"> </form> Here it is urls.py: app_name = 'notes' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('new/', views.new_note, name='new'), path('output/', views.create_note, name='create') ] And here the views.py file. Currently the create_note view only redirects to the index. I'm going to process the entered data once the form works correctly. class IndexView(generic.ListView): template_name = 'notes/index.html' context_object_name = 'all_notes' def get_queryset(self): return Note.objects.all() def new_note(request): return render(request, 'notes/new.html') def create_note(request): return HttpResponseRedirect(reverse('notes:index')) -
saving form data into csv in django- How to store data into csv file taking from html form in django
here are my views.py. I want to save my HTML form data into a CSV file. But my code is not working, this code shows no error. can anyone solve my issues? views.py import CSV result = 0 a1=0 a2=0 a3=0 a4=0 list = [] if request.POST.get('suu1'): a1 = request.POST['a1'] a2 = request.POST['a2'] a3 = request.POST['a3'] a4 = request.POST['a4'] a4=(str(a4)) a3=(str(a3)) a2=(str(a2)) a1=(str(a1)) # # try: # # result = eval(a1) + eval(a2) + eval(a3) + eval(a4) # print(result) # except: # result = 0 # print(result) try: with open('activityV3.csv', 'w+') as file: myFile = csv.writer(file) # myFile.writerow(["Id", "Activity", "Description", "Level"]) activityID = a1 activity = a2 desc = a3 level = a4 print(activityID,activity,desc,level) myFile.writerow([activityID, activity, desc, level]) except Exception as e: print('file error :', e) context = { 'result': result, 'a1':a1, 'a2':a2, 'a3':a3, 'a4':a4, } return render(request, "test.html", context) my form is working fine but data is not saving into CSV. I tried the above code in my project. but the data is not saved in the CSV file. But the HTML form is working very well. my main focus is to store data in CSV files taken from the form. thanks all. -
How to use gunicorn django and procfile with nested dirs?
The project structure goes like back\ |anwis\ | |anwis\ | |... | |wsgi.py |dg.sqlite3 |manage.py |... |venv\ | |... |Procfile |... In that Procfile i tried various things like web: gunicorn anwis.wsgi or web: gunicorn anwis.anwis.wsgi But somehow it all ended up now working, it just says "ModuleNotFoundError: No module named 'anwis.wsgi'" and that's it, there's nothing left to do else, i figure out that it needs a relative path to the wsgi file, but what is it then? -
annotate model with aggregate state of manytomany field
I have a Stream that has permissions = ManyToManyField(Permission) Permission has a state field. If all of the state's permissions are True then annotate state with allowed=True, else annotate state with allowed=False from django.db import models class Permission(models.Model): name = models.CharField(max_length=10), state = models.BooleanField() class Stream(models.Model): permissions = models.ManyToManyField(Permission) p1 = Permission.objects.create(state=True) p2 = Permission.objects.create(state=False) s = Stream.objects.create(name='s') s.permissions.add([p1, p2]) s1 = Stream.objects.create(name='s1') s1.permissions.add(p1) s2 = Stream.objects.create(name='s2') s2.permissions.add(p2) # How can I do something like this? annotated_streams = Stream.objects.annotate(allowed={... all([p.state for p in permissions]) ...}) [(s.name, s.allowed) for s in annotated_streams] [('s', False), ('s1', True), ('s2', False)] -
Is there any more pythonic way to checkfor keys in an ordered dictionary in Django
type of data <class 'collections.OrderedDict'> if("a" not in data or "b" not in data or "c" not in data or "d" not in data or "e" not in data or "f" not in data or "g" not in data or "h" not in data or "i" not in data): raise serializers.ValidationError("All Required Parameters not provided") i am checking for all these parameters whether they are present in my ordered dictionary or not is there any better way to check this? -
This page isn’t working. 127.0.0.1 didn’t send any data. Django
I am new to Django, trying to create a REST API with Django REST Framework. But, I have a problem when trying to run the server. Is there any problem in my manage.py file? I really need help. [These are the folders in VS Code][1] [I follow exactly like the tutorial.][2] [It said 127.0.0.1 didn't send any data.][3] [1]: https://i.stack.imgur.com/5TLYA.png [2]: https://i.stack.imgur.com/gRxk1.png [3]: https://i.stack.imgur.com/w8Cur.png -
Other Django Field Lookups for DurationFields?
I have a dynamic advanced search interface implemented in Django and javascript where the user selects: a field, a comparator (using a field lookup such as "iexact", "startswith", "gt", "lte", etc.), and a search term for any number of fields in the database Currently, for the 2 duration fields we have (age and "sample collection time (since infusion)"), the user is required to enter their search term in a format compatible with the timedelta used for django's database query, e.g. d-hh:mm:ss, foir the search to work properly. What we would like to do is accept search terms in the units in which the data is entered in the database (age in weeks and time collected in minutes). I could of course write one-off code to accomplish this, but I want this advanced search module I've written to be a generic implementation, so we can apply it to other projects without changing any code... So I was looking at the django doc's field lookups, which doesn't appear to have lookups for duration fields, but it links to a doc that gives advice on writing custom field lookups. There are definitely a few ways I can think of to do this, but … -
Change Data source in PowerBI according to userid entered in django html form
I am developing a web app in Django which takes user information and an excel file as input(the user fills out a form and uploads an excel file). The data from that excel file is extracted and stored in an SQL database. The extracted data is fed to an optimization model which produces a result that is stored in a separate excel file in an Amazon S3 bucket. The naming of the output excel file is unique(name contains userid). I want my PowerBi dashboard to connect to the output file depending on who is logged in to the Django web app ie get the userid from the web app search if the file containing that userid is present in the Amazon S3 bucket and if it is, connect that excel file to PowerBi dashboard, then embed that dashboard to a separate web page in Django, so that the specific user can see the visualizations. I went through multiple Powerbi articles, I know we can connect files in S3 to Powerbi using a custom python script, but don't know how to do it dynamically or even how to get the userid from the form and search the S3 bucket. Can anyone … -
How can user download database from django heroku?
I make a apllication in django. I want put a download button in the my aplicattion. User can download then in this button. In local host this work, but when i put in heroku don't. listar.html: <p> <form method="POST"> <a href="{% url 'baixa' %}" download>Download</a> </form> <a class="btn btn-outline-primary" href="{% url 'cadastrar_colecao' %}">Adicionar Novo</a> </p> urls.py: urlspatterns = [ path('download/',Download.Download,name='baixa'), ] views.py: class Download(TemplateView): def Download(self): conn = sqlite3.connect('db.sqlite3') db_df = pd.read_sql_query("SELECT * FROM formulario_colecao", conn) db_df.to_csv('formulario/colecao_UFMGAC.csv', index=False) return FileResponse(open('formulario/colecao_UFMGAC.csv', 'rb'), as_attachment=True) In local host this work and my database system sqlite3. Heroku datase system is postgree -
Bootstrap grid not aligned properly
With the django framework I use a loop in my templates to display the image inside my database, I also use the Bootstrap grid to make it clean, but it not working correctly. As you can see the image on at the bottom are not align correctly. hmtl <div class="container"> <div class="row"> <div class="col-sm-12 col-md-3 col-lg-2"> <div class="card-filter" style="width: 10rem;"> <div class="card-header"> Pattern Type </div> <ul class="list-group list-group-flush"> {% for pattern in categories %} <li class="list-group-item">{{pattern.name}}</li> {% endfor %} </ul> </div> </div> {% for photo in photos %} <div class="col-sm-12 col-md-5 col-ld-5"> <div class="card" style="width: 25rem;"> <img class="card-img-top" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <p class="card-text">Symbol: GBPUSD<br>Pattern: ButterFly Bullish</p> <a href="{% url 'photo' photo.id %}" class="btn btn-dark">View Pattern</a> </div> </div> </div> {% endfor %} </div> </div> views.py def home(request): categories = Category.objects.all() photos = Photo.objects.all() context = {'categories': categories, 'photos': photos} return render(request, "main/home.html", context)