Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app working locally but throws 'NotSupportedError at /accounts/login/' on Elastic Beanstalk
I don't understand why my django app works locally but throws a NotSupportedError error upon elastic beanstalk deploy using the awsebcli. I follow the normal password flow for logging in and redirecting to a certain app, however when I'm doing this via the deployment it throws the following error: NotSupportedError at /accounts/login/ deterministic=True requires SQLite 3.8.3 or higher Additional info Django Version: 3.2.7 Exception Type: NotSupportedError Exception Value: deterministic=True requires SQLite 3.8.3 or higher Exception Location: /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 217, in get_new_connection Python Executable: /var/app/venv/staging-LQM1lest/bin/python Python Version: 3.8.5 Python Path: ['/var/app/current', '/var/app/venv/staging-LQM1lest/bin', '/var/app/venv/staging-LQM1lest/bin', '/usr/lib64/python38.zip', '/usr/lib64/python3.8', '/usr/lib64/python3.8/lib-dynload', '/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages', '/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages'] Server time: Thu, 30 Sep 2021 06:32:23 +0000 I've roughly followed this tutorial for deploying a Django app via eb, albeit with python 3.8 changes login/logout setup followed this tutorial this post has a similar issue with a different deployment method Thanks for reading! Any help is appreciated. -
RotatingFileHandler is not creating file on crossing maxBytes value
I am working on rotating file handler. I need another file to be created once the file size crosses the given maxBytes value. but the code does not seems to working fine import logging from logging.handlers import RotatingFileHandler logging.basicConfig(format='%(asctime)s - %(message)s', handlers=[RotatingFileHandler("/app.log", maxBytes=100, backupCount=5)]) logger = logging.getLogger('DemoLogger') @router.get('/demo_api/v1') def default_rd(db: Session = Depends(get_db)): try: Category_data = db.query(models.table_new.id, models.table_new.Label).filter(models.table_new.classCode=='Category').all() except Exception: logger.exception("Database Error") else: logger.warning("Fetched Category data") -
how can my django form grab current username and email and submit them into another database table?
In my django project I have a form VisitorRegForm which collects scanned_id and body_temp and submits data to my database table ClinicalData, since the current user is already logged in, how can I make this form to also be able grab current logged in user's username and email (Note: username and email were both created from the built-in django User model) and submit these four items: 'scanned_id', 'body_temp', 'username', 'email' into the database table ClinicalData? Don't mind the missing details and inports, the form works and am able to submit 'scanned_id', 'body_temp'. Help me on the easiest way I will be able to submit these four items: 'scanned_id', 'body_temp', 'username', 'email' looking at the details shown in the files below: Where should it be easier to achieve this; in the views.py or the template file? forms.py class VisitorRegForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ScannerForm(ModelForm): class Meta: model = ClinicalData fields = ['scanned_id', 'body_temp', 'username', 'email'] models.py class ClinicalData(models.Model): ... scanned_id = models.CharField(verbose_name="Scanned ID", max_length=50, null=True) body_temp = models.DecimalField(verbose_name="Body Temperature", max_digits=3, decimal_places=1, null=True) username = models.CharField(verbose_name="Facility Name", max_length=200, null=True) email = models.EmailField(verbose_name="Visitor Email", max_length=200, null=True) ... views.py Am assuming I might need like two … -
Plotly Dash: How to save/cache Dash DataTable without making an external file?
I am looking for a set of functions or a library that could allow me to do the following operations: There is a Dash DataTable displayed in my web app. I select specific rows in the table and click the save button. Then the selected rows transform into a pd.dataframe object then it's changed to a json object using df.to_json('records'). The created json file stays in the web browser or server(like heroku) without making an external json or excel file on the local server(aka my laptop). And this saved file stays permanently in the storage (server or wherever) unless I do something on it. When I click another button on my web app, Dash DataTable object is displayed sourcing from that json file. When I click again another button on my web app, the file is deleted permanently. This series of operations is beyond my knowledge as I have never touched server-side caching or whatsoever in my life... (sorry I am a newb :( ). Hope my question was clear! Thank you! -
why django shows NoReverseMatch at /articles/3/ Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: []
Whenever I try to Link Edit (article_edit.html) and Delete(article_detail.html) Django shows this error. NoReverseMatch at /articles/3/ Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['articles/(?P<pk>[0-9]+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/articles/3/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'article_edit' with arguments '('',)' not found. 1 pattern(s) tried: ['articles/(?P<pk>[0-9]+)/edit/$'] I tried without Linking these tags (Edit and Delete), the app runs absolutely fine but whenever I add these lines of codes the app stop working. here's my article_detail.html template {% extends 'base.html' %} {% block content %} <div class="article-entry"> <h2>{{object.title}}</h2> <p>by {{object.author}} | {{object.date}}</p> <p>{{object.body}}</p> </div> <p> <a href="{% url 'article_edit' article.pk %}">Edit</a> | <a href="{% url 'article_delete' article.pk %}">Delete</a> </p> <p>back to <a href="{% url 'article_list' %}"></a>All Articles</p> {% endblock content %} here are models.py , urls.py and views.py for 'articles' app from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class Articles(models.Model): title = models.CharField(max_length=250) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse("article_detail", args=[str(self.id)]) from django.urls import reverse_lazy from django.urls.base import reverse from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView from .models import Articles class ArticleListView(ListView): model = … -
Django Email Template Different styling in gmail and in mailhog
I have an html email template in Django and trying to align the footer items in 1 column, it is aligned properly in mailhog and when I open the html template in browser, but when it is sent using gmail smtp, the alignment looks different. Please help me with the correct styling that works in Gmail. Attached below are the images Incorrect alignment in gmail: Correct alignment: <tr> <td align="center" bgcolor="#ffffff" class="footer"> <p style="margin: 0; color:#2B4C4C">6th Floor, 259 CLMC Building, EDSA, Mandaluyong City<br> <a href="mailto:admin@folaglobal.com" style="color:#0563c1">admin@folaglobal.com</a><br> </p> <div style="display:flex; flex-direction: row; justify-content: center; margin-top: 5px; margin-bottom: 5px;"> <a href="https://www.instagram.com/folaglobalinc/" target="_blank" style="margin-right: 15px; height: 20px; width: 20px;"> <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/instagram-square-brands.png" alt="instagram" title="instagram" width="20px" height="20px" style="display:block" /> </a> <a href="https://www.facebook.com/FolaGlobalInc/" target="_blank" style="margin-right: 15px; height: 20px; width: 20px;"> <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/facebook-square-brands.png" alt="facebook" title="facebook" width="20px" height="20px" style="display:block" /> </a> <a href="https://www.tiktok.com/@folaglobal?lang=en" target="_blank" style="height: 20px; width: 20px;"> <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/tiktok-brands.png" alt="tiktok" title="tiktok" width="20px" height="20px" style="display:block" /> </a> </div> <p style="margin: 0; color:#2B4C4C; font-size: 8pt;">This is a system generated message. Please do not reply to this email</p> <!-- <img src="https://folaglobal-production-bucket.s3.ap-southeast-1.amazonaws.com/logo/letter-head.png" style="width: 100%; margin-top: 10px;" alt="tiktok" /> --> </td> </tr> -
How to take input of ManyToManyField of django?
I have 2 models - Rooms and Modules. A module can contain many rooms and a room can be contained by many different modules. below are the models - Rooms model - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) Module model - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() is_deleted = models.BooleanField(default=False) rooms = models.ManyToManyField(Rooms) Module serializer - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" Module view.py file - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response("response":module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) How do I take multiple rooms as input in views.py file while creating my module object. Also if i want to test my API in postman, then how can i take multiple inputs in postman. -
'AddForm' object has no attribute 'reception'
I have a page where it allow the user to enter the reception number, so when the user enter the reception number, it should verify with the database if the reception number exist, but i am having this error: 'AddForm' object has no attribute 'reception'. How do I solve this error? views.py @login_required() def verifydetails(request): if request.method == 'POST': #Customername = request.GET['Customername'] form = AddForm(request.POST or None) if form.reception == Photo.reception: messages.success(request, 'Both Reception and customer name match') return redirect('AddMCO') else: messages.success(request, 'Both Reception and customer do not match') return redirect('verifydetails') else: form = AddForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) class meta: model = Photo fields = ('reception') verifydetails.html <!DOCTYPE html> <html> <head> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS verify details</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <!-- Font Awesome --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script> <!-- Tempus Dominus Bootstrap 4 --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css" integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" /> … -
django migrations: django.db.utils.ProgrammingError: relation does not exist
I started working on an existing project that is being developed by others as well. When I cloned it from git I could not makemigrations and every time I try to migrate I got this "django.db.utils.ProgrammingError: relation does not exist" error. If I can make only migrations I think the problem will be solved. Can anyone help me here to do that or if you know any other solution for it please let me know. Traceback (most recent call last): File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "app_customer" does not exist LINE 1: ...LECT "app_customer"."customer_mobile_number" FROM "app_custo... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/ss/projects/backend/manage.py", line 21, in <module> main() File "/Users/ss/projects/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/ss/projects/backend/.venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, … -
Polynomial coefficients in Python without numpy
Write a program that first receives the number m from the user and then the number n, and then receives the polynomial coefficients P (x) of the order m from the user and prints the polynomial coefficients P (x) ^ n in the output. As an example of the calculation of P (x) ^ n, suppose. P (x) = x ^ 2 + 2x + 3 and n = 2: P (x) ^ n = (x ^ 2 + 2x + 3) (x ^ 2 + 2x + 3) = x ^ 4 + 4x ^ 3 + 10x ^ 2 + 12x + 9 Input sample 3 2 1 2 3 4 Sample output 1 4 10 20 25 24 16 -
In Django filter posts in between two specific times
I want to filter the posts which was added in between last 2 or 3 hours.. i have already used timedelta etc but the filter keyword always want to get exact date, whereas dt = timezone.now() - timedelta(hours=2) never give exact datetime.. how can i achieve that?? models.py from django.db import models from datetime import datetime # Create your models here. class addPost(models.Model): date = models.DateTimeField(auto_now_add=True) postId = models.AutoField(primary_key=True) title = models.CharField(max_length=100) category = models.CharField(max_length=60) image = models.ImageField(upload_to="blog/images", default="") content = models.TextField(default="") views.py def index(request): dt = timezone.now() - timedelta(minutes=23) obj = addPost.objects.filter(date=dt) print(obj[0].date) return render(request, "blog\home.html", {"obj":obj}) -
How to Migrate only required models table if using Multiple DB in django
I have tried migrating models when using Multiple DB in django. It is creating all table in both the DB by default, Can we customize it so unnecessary table can't be made in the DB. -
Many To Many Field Django throwing errors
I am trying to store form-data to a model, when the user submits the form all of the data is saved correctly but a many to many field (catagory) which is throwing errors. Can someone please help me edit my view so that I can save this information? Thank you in advance. I tried to save the field 'Catagory' but at first couldn't. Then I came across answers that said to add self.save_m2m() before self.save(commit=False). But this leads to another error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/ Django Version: 3.2.5 Python Version: 3.9.6 Installed Applications: ['fontawesome_free', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jquery', 'portfolio', 'blog', 'import_export', 'tinymce', 'hitcount', 'taggit', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Babli\Desktop\My-Projects\MySite\mysite\blog\views.py", line 35, in make_post form.save_m2m() File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 451, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related.py", line 1668, in save_form_data getattr(instance, self.attname).set(data) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related_descriptors.py", line 536, in __get__ return self.related_manager_cls(instance) File "C:\Users\Babli\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\related_descriptors.py", line 851, in __init__ raise ValueError('"%r" needs to have a value for … -
I want to use Django-ratelimit api when my api request fails . So it there any way out to use if condition or this type of condition .?
I want to use Django-ratelimit api when my api request fails . So it there any way out to use if condition or this type of condition ?? -
how to kill uwsgi process without worker respawn
I have had trouble to kill uwsgi processes. Whenever I use below commands to shutdown uwsgi, another uwsgi workers respawned after a few seconds. So after shutdown uwsgi process and start up uwsgi server again, uwsgi processes continues to accumulate in memory. sudo pkill -f uwsgi -9 kill -9 cat /tmp/MyProject.pid uwsgi --stop /tmp/MyProject.pid I want to know how to kill uwsgi processes not making uwsgi workers respawned. I attach ini file as below. [uwsgi] chdir = /home/data/MyProject/ module = MyProject.wsgi home = /home/data/anaconda3/envs/env1 master = true pidfile = /tmp/MyProject.pid single-interpreter = true die-on-term = true processes = 4 socket = /home/data/MyProject/MyProject.sock chmod-socket = 666 vacuum = true Thank you in advance!! -
How to compare html input value in django?
I am allowing users to input certain data. I got the user input data in the Django view.py but when I try to compare the user with other data. It doesn't work properly def compare(request) if request.method == 'POST': data = request.POST.get('data') if data == 'yes': print("no") elif data == 'menu': print(True) html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="your_name"> Specific Data </label> <input type="text" name="data" placeholder="Enter yes or menu "> <br> <button type="submit" name="submit">submit</button> </form> I entered the "menu" on the input section but it is working with a ( " if data == 'yes' ) statement -
Selenium webdriver for Django/React for Github Actions
So, to use webdriver for a django react project, I start the backend and frontend and then I use the url with webdriver, and it works fine locally. But I can't do that with Github Actions as python manage.py runserver and npm start get into infinite loops... How to get around this to make selenium work on Github Actions? -
HTML "capture" attribute for desktop computer/pc
I'm making a web app using Django that requests images from users and processes them. When I use the following code: <label for="imageFile">Upload a photo:</label> <input type="file" id="imageFile" capture="user" accept="image/*"> I don't get an option to take a photo from the laptop's camera. Several websites said that the capture attribute might not work for desktop computers and I don't know what I should use instead. -
Django request.POST.get doesn't work with Vanilla JavaScript requests
I already found a solution to this problem, but I only know that it works. I don't know how or why and that's the purpose of this question. I have a Vanilla JavaScript file that controls a dependent drop-down list of countries-regions-cities triplets. Here is the code: {% load i18n %} {% load static %} <script> /* This function retrieve the csrf token from the cookies */ function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } /* This function just sorts the list of regions or cities */ function sortList(dataList){ return dataList.sort(function(a, b){ if (a[1] < b[1]) return -1; if (a[1] > b[1]) return 1; return 0; }); } /** Creates a XmlReq request and send it. @param function func_name - it's the function in the server that will be called asynchronously. @param string token - it's the csrf token necessary to validate django forms. @param data json object - it's the data to send to the server @param callback callback - it's the callback function to be called on success. **/ function createXmlReq(func_name, token, data, callback){ var xhr = new XMLHttpRequest(); xhr.addEventListener("load", callback); xhr.open("POST", func_name); xhr.setRequestHeader("X-CSRFToken", token); /* … -
Allauth doesn't work with twitch in django
I am trying to authenticate via twitch on my site. I use allauth for github and everything works, but not for twitch. This is all I have: #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.twitch', #'django.extensions', 'django.contrib.sites', 'allauth.socialaccount.providers.github', ] LOGIN_REDIRECT_URL = "home" ACCOUNT_EMAIL_VERIFICATION = 'none' SITE_ID = 1 I also want to show what I get as a result: here it is And twitch settings: here it is Maybe someone knows how to fix this? Would really appreciate any help -
Custom permissions for different user types django rest framework
For Django-reactjs project, I have a user model in django which has 3 boolean fields (is_admin, is_moderator, is_normal_user), and I also have 3 other models, I want to set permissions for each user type. The user can only create objects for 1 model only, the moderator is the only one that can edit a certain model field, and admins can do everything. It might be a trivial question but I am a newbie in Django and React so If you could please tell me how can I handle it with custom permissions(some steps to follow) and also how these permissions are handled from React. Thanks in advance! -
Is there a way to compare the stored values and the inputs by user to remove duplicates in django views?
I have a variable in Django View which is interfacelist and it contains [TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2, TenGigabitEthernet1/0/20, TenGigabitEthernet1/0/21]. This is what the user input from the HTML and I request.POST.get it to the view. And in my database (SQL), I have the following: Here comes the question, how do i compare the data in the database and interfacelist and remove any duplicates? Like in this case, TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2 so I would remove it and keep the TenGigabitEthernet1/0/20, TenGigabitEthernet1/0/21 to be updated in the database. I tried the following codes: (This is happening is Django View) cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2") righttable = cursor.fetchall() print(righttable) #Notworking #for i in righttable: # if interfacelist[i] == righttable[i]: # interfacelist.remove(a) #Notworking for i in interfacelist: updatequery2 = f"INSERT INTO {tablename}(interface) VALUES('{i}')" cursor.execute(updatequery2) cursor.close() The variable righttable in this case will be the image shown earlier. It contains [TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5]. Also, the commented out codes are not working as it gives me a error of list indices must be integers or slices, not tuple. How do I fix this to achieve what I wanted? Would greatly appreciate if anyone can advise or help me. Thank you! -
django model object filter from 2 different model
So I am trying to filter comments made by a specific user within a specific station. First I have a model named comment and it has a relationship with the post. class Comment(Votable): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments_authored', on_delete=models.CASCADE, blank=True) text = RichTextUploadingField(blank=True, null=True) parent = models.ForeignKey('self', related_name='children', null=True, blank=True, on_delete=models.PROTECT) It's pretty easy to filter just based on author. And then I have the model for post: class Post(Votable): title = models.CharField(max_length=200, unique=False) submitter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts_submitted', on_delete=models.CASCADE) url = models.URLField('URL', max_length=200, null=True, blank=True) text = RichTextUploadingField(blank=True, null=True) def children(self): return self.comments.filter(parent=None) def __str__(self): return self.title def save(self, *args, **kwargs): # new if not self.post_slug: self.post_slug = slugify(str(self.title)+str(self.pk)) return super().save(*args, **kwargs) The post model has a relationship with the station, which I use StationPost to establish the relationship. So a station can have many posts: class StationPost(BaseModel): station = models.ForeignKey('Station', related_name='posts_set', on_delete=models.CASCADE) post = models.ForeignKey('Post', related_name='station', on_delete=models.CASCADE) class Meta: unique_together = ['station', 'post'] And in case of any confusion, here is the model for station class Station(BaseModel): #this is to add the station for each posts: alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') station_name=models.CharField(max_length=19,validators=[alphanumeric], unique=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='station_creator', on_delete=models.CASCADE) text = models.TextField(max_length=200, default='brief … -
how to use csrf token with django, react and axios and nginx
It been a few hours that i am getting the following errors while doing a post request to the backend from react frontend Access to XMLHttpRequest at 'https ://api.foo.com/api/create/' from origin 'https ://www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. My full stack app was working correctly, react front end, django backend, infrastructure made of s3 for react, both hosted on aws cloudfront using terraform until i tried to implement the csrf token below i created the following config react axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true const Create = () => { const [fields, handleFieldChange] = FormFields({ name: "", }); const options = { headers: { 'Content-Type': 'application/json', } }; const handleSubmit = (e) => { e.preventDefault(); axios.post("https ://api.foo.com/create/", fields, options) .then(response => { ... django settings.py CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = "csrftoken" CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Access-Control-Allow-Origin', ] nginx ... location / { add_header 'Access-Control-Allow-Origin' 'https ://www.foo.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,X-CSRFToken'; ... } Any help would be much appreciated, thanks -
Unable to ssh into aws EC2 instance
I have a django application running on EC2. I was able to ssh into the server instance. However, just before running certbot to obtain ssl certificate, I ran the command sudo ufw enable. That command prompted an alert that running it might alter ssh command (or something of that nature), but I ignored the warning and proceeded to enable ufw. After obtaining the ssl certificate I logged out of the server. When I tried to connect to the server subsequently, I keep getting the error ssh: connect to host ec2-xxx-xxx-xxx.us-east-2.compute.amazonaws.com port 22: Connection timed out I have spent several hours trying to fix the error but it persists. Why am I unable to connect to my ec2 instance after running sudo ufw enable.Though I'm not very sure, does using let's encrypt certbot to obtaining ssl certificate alter certain configurations in the server? I'm somewhat confused about the whole process. (the major commands I ran to obtain the ssl certificate are: sudo apt install python3-certbot-nginx and sudo certbot --nginx -d your_domain)